完善配置审计与数据库迁移安全链路
This commit is contained in:
1 parent
84440d8761
commit
3af1fc4147
117 files changed
+4703
-1110
No files matched your search
@@ -247,7 +247,11 @@ func ConfigAuditQuery(ctx *appcontext.Context, w http.ResponseWriter, req *http.
|
||||
writeConfigAccessError(w, err)
|
||||
return
|
||||
}
|
||||
query := parseAuditQuery(req)
|
||||
query, err := parseAuditQuery(req)
|
||||
if err != nil {
|
||||
writeConfigError(w, err)
|
||||
return
|
||||
}
|
||||
items, err := manager.AuditQuery(req.Context(), query)
|
||||
if err != nil {
|
||||
writeConfigError(w, err)
|
||||
@@ -273,11 +277,26 @@ func ExportConfigAudit(ctx *appcontext.Context, w http.ResponseWriter, req *http
|
||||
writeConfigError(w, err)
|
||||
return
|
||||
}
|
||||
query := parseAuditQuery(req)
|
||||
query, err := parseAuditQuery(req)
|
||||
if err != nil {
|
||||
writeConfigError(w, err)
|
||||
return
|
||||
}
|
||||
query.Limit = input.Limit
|
||||
if err := config.ValidateConfigAuditQuery(query); err != nil {
|
||||
writeConfigError(w, err)
|
||||
return
|
||||
}
|
||||
format := strings.ToLower(strings.TrimSpace(input.Format))
|
||||
if format == "" {
|
||||
format = "json"
|
||||
}
|
||||
if format != "json" && format != "csv" {
|
||||
writeConfigError(w, config.ErrInvalidAuditFormat)
|
||||
return
|
||||
}
|
||||
var data []byte
|
||||
var err error
|
||||
if strings.EqualFold(input.Format, "csv") {
|
||||
if format == "csv" {
|
||||
data, err = manager.ExportAuditCSV(req.Context(), query)
|
||||
} else {
|
||||
data, err = manager.ExportAuditJSON(req.Context(), query)
|
||||
@@ -287,7 +306,7 @@ func ExportConfigAudit(ctx *appcontext.Context, w http.ResponseWriter, req *http
|
||||
return
|
||||
}
|
||||
contentType := "application/json; charset=utf-8"
|
||||
if strings.EqualFold(input.Format, "csv") {
|
||||
if format == "csv" {
|
||||
contentType = "text/csv; charset=utf-8"
|
||||
}
|
||||
w.Header().Set("Content-Type", contentType)
|
||||
@@ -348,17 +367,48 @@ func configActor(ctx *appcontext.Context, req *http.Request) config.AuditActor {
|
||||
return actor
|
||||
}
|
||||
|
||||
func parseAuditQuery(req *http.Request) config.ConfigAuditQuery {
|
||||
func parseAuditQuery(req *http.Request) (config.ConfigAuditQuery, error) {
|
||||
query := req.URL.Query()
|
||||
result := config.ConfigAuditQuery{ActorID: strings.TrimSpace(query.Get("actorId")), Operation: config.ConfigOperation(strings.TrimSpace(query.Get("operation"))), Section: config.Section(strings.TrimSpace(query.Get("section")))}
|
||||
result.Limit, _ = strconv.Atoi(query.Get("limit"))
|
||||
if value, err := time.Parse(time.RFC3339, query.Get("from")); err == nil {
|
||||
for key, values := range query {
|
||||
if len(values) != 1 {
|
||||
return config.ConfigAuditQuery{}, config.ErrInvalidAuditQuery
|
||||
}
|
||||
switch key {
|
||||
case "actorId", "operation", "section", "limit", "from", "to":
|
||||
default:
|
||||
return config.ConfigAuditQuery{}, config.ErrInvalidAuditQuery
|
||||
}
|
||||
}
|
||||
result := config.ConfigAuditQuery{
|
||||
ActorID: strings.TrimSpace(query.Get("actorId")),
|
||||
Operation: config.ConfigOperation(strings.TrimSpace(query.Get("operation"))),
|
||||
Section: config.Section(strings.TrimSpace(query.Get("section"))),
|
||||
}
|
||||
if rawLimit := strings.TrimSpace(query.Get("limit")); rawLimit != "" {
|
||||
limit, err := strconv.Atoi(rawLimit)
|
||||
if err != nil {
|
||||
return config.ConfigAuditQuery{}, config.ErrInvalidAuditQuery
|
||||
}
|
||||
result.Limit = limit
|
||||
}
|
||||
if rawFrom := strings.TrimSpace(query.Get("from")); rawFrom != "" {
|
||||
value, err := time.Parse(time.RFC3339, rawFrom)
|
||||
if err != nil {
|
||||
return config.ConfigAuditQuery{}, config.ErrInvalidAuditQuery
|
||||
}
|
||||
result.From = value
|
||||
}
|
||||
if value, err := time.Parse(time.RFC3339, query.Get("to")); err == nil {
|
||||
if rawTo := strings.TrimSpace(query.Get("to")); rawTo != "" {
|
||||
value, err := time.Parse(time.RFC3339, rawTo)
|
||||
if err != nil {
|
||||
return config.ConfigAuditQuery{}, config.ErrInvalidAuditQuery
|
||||
}
|
||||
result.To = value
|
||||
}
|
||||
return result
|
||||
if err := config.ValidateConfigAuditQuery(result); err != nil {
|
||||
return config.ConfigAuditQuery{}, err
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func publicConfigSection(runtime config.RuntimeConfig, section config.Section) (any, error) {
|
||||
@@ -407,11 +457,18 @@ func publicConfigSection(runtime config.RuntimeConfig, section config.Section) (
|
||||
case config.SectionPlugins:
|
||||
plugins := make(map[string]any, len(runtime.Plugins.Plugins))
|
||||
for id, item := range runtime.Plugins.Plugins {
|
||||
settings := any(nil)
|
||||
if len(item.Settings) > 0 {
|
||||
var value any
|
||||
if err := config.ParseStrict(item.Settings, &value); err == nil {
|
||||
settings = value
|
||||
}
|
||||
}
|
||||
plugins[id] = map[string]any{
|
||||
"enabled": item.Enabled,
|
||||
"executable": item.Executable,
|
||||
"permissions": item.Permissions,
|
||||
"settings": nil,
|
||||
"settings": settings,
|
||||
"secretStatus": publicSecret(item.Secret),
|
||||
}
|
||||
}
|
||||
@@ -420,23 +477,3 @@ func publicConfigSection(runtime config.RuntimeConfig, section config.Section) (
|
||||
return nil, errors.New("invalid configuration section")
|
||||
}
|
||||
}
|
||||
|
||||
func writeConfigAccessError(w http.ResponseWriter, err error) { writeConfigError(w, err) }
|
||||
func writeConfigError(w http.ResponseWriter, err error) {
|
||||
status := response.NoAccessPrivileges
|
||||
message := "无权访问或请求不满足安全条件"
|
||||
var data any = ""
|
||||
var denial *access.Denial
|
||||
if errors.As(err, &denial) {
|
||||
data = map[string]string{"code": string(denial.Code)}
|
||||
}
|
||||
if errors.Is(err, config.ErrManagerStorage) {
|
||||
status = response.ServerError
|
||||
message = "配置服务不可用"
|
||||
}
|
||||
if errors.Is(err, config.ErrGenerationConflict) {
|
||||
status = response.ParamsError
|
||||
message = "配置已发生变化,请刷新后重试"
|
||||
}
|
||||
response.NewErrorResponse(status, message, data).FPrint(w)
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
package controllers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.pcux.cn/xuans/Smail/config"
|
||||
"git.pcux.cn/xuans/Smail/dto/response"
|
||||
"git.pcux.cn/xuans/Smail/services/access"
|
||||
appcontext "git.pcux.cn/xuans/Smail/utils/context"
|
||||
)
|
||||
|
||||
// GetConfigAuditDetail 返回一条已脱敏的配置审计事件。
|
||||
func GetConfigAuditDetail(ctx *appcontext.Context, w http.ResponseWriter, req *http.Request) {
|
||||
manager, ok := configManagerOrError(w)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if err := authorizeCapability(ctx, access.CapabilityAuditRead, "", false); err != nil {
|
||||
writeConfigAccessError(w, err)
|
||||
return
|
||||
}
|
||||
parts := strings.Split(strings.Trim(req.URL.Path, "/"), "/")
|
||||
if len(parts) != 5 || parts[0] != "api" || parts[1] != "v1" || parts[2] != "audits" || parts[3] != "config" || strings.TrimSpace(parts[4]) == "" {
|
||||
writeConfigError(w, config.ErrInvalidAuditQuery)
|
||||
return
|
||||
}
|
||||
event, err := manager.AuditDetail(req.Context(), parts[4])
|
||||
if err != nil {
|
||||
writeConfigError(w, err)
|
||||
return
|
||||
}
|
||||
response.NewSuccessResponse(event).FPrint(w)
|
||||
}
|
||||
|
||||
type configAuditExportRequest struct {
|
||||
Format string `json:"format"`
|
||||
ID string `json:"id"`
|
||||
ActorID string `json:"actorId"`
|
||||
Operation string `json:"operation"`
|
||||
Section string `json:"section"`
|
||||
Limit int `json:"limit"`
|
||||
From string `json:"from"`
|
||||
To string `json:"to"`
|
||||
}
|
||||
|
||||
// ExportConfigAuditFormal 实现正式配置审计导出接口。
|
||||
func ExportConfigAuditFormal(ctx *appcontext.Context, w http.ResponseWriter, req *http.Request) {
|
||||
manager, ok := configManagerOrError(w)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if err := authorizeCapability(ctx, access.CapabilityAuditExport, "", false); err != nil {
|
||||
writeConfigAccessError(w, err)
|
||||
return
|
||||
}
|
||||
var input configAuditExportRequest
|
||||
if err := decodeJSONRequest(w, req, &input); err != nil {
|
||||
writeConfigError(w, err)
|
||||
return
|
||||
}
|
||||
query, err := auditExportQuery(input)
|
||||
if err != nil {
|
||||
writeConfigError(w, err)
|
||||
return
|
||||
}
|
||||
format := strings.ToLower(strings.TrimSpace(input.Format))
|
||||
if format == "" {
|
||||
format = "json"
|
||||
}
|
||||
if format != "json" && format != "csv" {
|
||||
writeConfigError(w, config.ErrInvalidAuditFormat)
|
||||
return
|
||||
}
|
||||
var data []byte
|
||||
if format == "csv" {
|
||||
data, err = manager.ExportAuditCSV(req.Context(), query)
|
||||
} else {
|
||||
data, err = manager.ExportAuditJSON(req.Context(), query)
|
||||
}
|
||||
if err != nil {
|
||||
writeConfigError(w, err)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
w.Header().Set("Content-Disposition", `attachment; filename="config-audit.`+format+`"`)
|
||||
if format == "csv" {
|
||||
w.Header().Set("Content-Type", "text/csv; charset=utf-8")
|
||||
} else {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
}
|
||||
_, _ = w.Write(data)
|
||||
}
|
||||
|
||||
func auditExportQuery(input configAuditExportRequest) (config.ConfigAuditQuery, error) {
|
||||
query := config.ConfigAuditQuery{
|
||||
ID: strings.TrimSpace(input.ID),
|
||||
ActorID: strings.TrimSpace(input.ActorID),
|
||||
Operation: config.ConfigOperation(strings.TrimSpace(input.Operation)),
|
||||
Section: config.Section(strings.TrimSpace(input.Section)),
|
||||
Limit: input.Limit,
|
||||
}
|
||||
if raw := strings.TrimSpace(input.From); raw != "" {
|
||||
value, err := time.Parse(time.RFC3339, raw)
|
||||
if err != nil {
|
||||
return config.ConfigAuditQuery{}, config.ErrInvalidAuditQuery
|
||||
}
|
||||
query.From = value
|
||||
}
|
||||
if raw := strings.TrimSpace(input.To); raw != "" {
|
||||
value, err := time.Parse(time.RFC3339, raw)
|
||||
if err != nil {
|
||||
return config.ConfigAuditQuery{}, config.ErrInvalidAuditQuery
|
||||
}
|
||||
query.To = value
|
||||
}
|
||||
if err := config.ValidateConfigAuditQuery(query); err != nil {
|
||||
return config.ConfigAuditQuery{}, err
|
||||
}
|
||||
return query, nil
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package controllers
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"git.pcux.cn/xuans/Smail/config"
|
||||
)
|
||||
|
||||
func TestParseAuditQueryRejectsUnknownAndMalformedParameters(t *testing.T) {
|
||||
tests := []string{
|
||||
"/api/v1/audits/config?unknown=value",
|
||||
"/api/v1/audits/config?limit=not-a-number",
|
||||
"/api/v1/audits/config?from=not-a-time",
|
||||
"/api/v1/audits/config?operation=unknown",
|
||||
"/api/v1/audits/config?limit=10&limit=20",
|
||||
}
|
||||
for _, target := range tests {
|
||||
request := httptest.NewRequest("GET", target, nil)
|
||||
if _, err := parseAuditQuery(request); !errors.Is(err, config.ErrInvalidAuditQuery) {
|
||||
t.Fatalf("target %s returned %v, want invalid audit query", target, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseAuditQueryAcceptsSupportedParameters(t *testing.T) {
|
||||
request := httptest.NewRequest("GET", "/api/v1/audits/config?actorId=42&operation=update§ion=smtp&limit=10&from=2026-08-01T00:00:00Z&to=2026-08-30T00:00:00Z", nil)
|
||||
query, err := parseAuditQuery(request)
|
||||
if err != nil {
|
||||
t.Fatalf("valid audit query rejected: %v", err)
|
||||
}
|
||||
if query.ActorID != "42" || query.Limit != 10 || string(query.Operation) != "update" || string(query.Section) != "smtp" {
|
||||
t.Fatalf("unexpected parsed query: %+v", query)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuditExportQueryRejectsInvalidStableID(t *testing.T) {
|
||||
query, err := auditExportQuery(configAuditExportRequest{ID: "audit-not-valid"})
|
||||
if !errors.Is(err, config.ErrInvalidAuditQuery) {
|
||||
t.Fatalf("invalid export ID returned query=%+v error=%v", query, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuditExportQueryDefaultsLimitAndParsesTimeRange(t *testing.T) {
|
||||
query, err := auditExportQuery(configAuditExportRequest{
|
||||
ActorID: "42",
|
||||
From: "2026-08-01T00:00:00Z",
|
||||
To: "2026-08-30T00:00:00Z",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if query.ActorID != "42" || query.From.IsZero() || query.To.IsZero() || query.Limit != 0 {
|
||||
t.Fatalf("unexpected export query: %+v", query)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
package controllers
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"git.pcux.cn/xuans/Smail/config"
|
||||
"git.pcux.cn/xuans/Smail/dto/response"
|
||||
"git.pcux.cn/xuans/Smail/services/access"
|
||||
"git.pcux.cn/xuans/Smail/services/dbmigration"
|
||||
)
|
||||
|
||||
var requestIDPattern = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`)
|
||||
|
||||
// EnsureConfigRequestID 为配置 API 设置可回溯但不包含敏感信息的请求 ID.
|
||||
func EnsureConfigRequestID(w http.ResponseWriter, req *http.Request) string {
|
||||
requestID := ""
|
||||
if req != nil {
|
||||
requestID = strings.TrimSpace(req.Header.Get("X-Request-ID"))
|
||||
}
|
||||
if !requestIDPattern.MatchString(requestID) {
|
||||
requestID = newConfigRequestID()
|
||||
}
|
||||
w.Header().Set("X-Request-ID", requestID)
|
||||
return requestID
|
||||
}
|
||||
|
||||
func newConfigRequestID() string {
|
||||
value := make([]byte, 16)
|
||||
if _, err := rand.Read(value); err != nil {
|
||||
return "config-request"
|
||||
}
|
||||
return hex.EncodeToString(value)
|
||||
}
|
||||
|
||||
func configErrorDetails(err error) (string, int, string, map[string]string) {
|
||||
code := "CONFIG_REQUEST_FAILED"
|
||||
status := http.StatusBadRequest
|
||||
message := "配置请求未完成"
|
||||
fields := map[string]string(nil)
|
||||
|
||||
var denial *access.Denial
|
||||
switch {
|
||||
case errors.As(err, &denial):
|
||||
code = string(denial.Code)
|
||||
status = http.StatusForbidden
|
||||
message = "无权访问或请求不满足安全条件"
|
||||
case errors.Is(err, config.ErrManagerStorage):
|
||||
code = "CONFIG_MANAGER_UNAVAILABLE"
|
||||
status = http.StatusServiceUnavailable
|
||||
message = "配置服务暂时不可用,请稍后重试"
|
||||
case errors.Is(err, config.ErrGenerationConflict):
|
||||
code = "CONFIG_GENERATION_CONFLICT"
|
||||
status = http.StatusConflict
|
||||
message = "配置已发生变化,请刷新后重试"
|
||||
case errors.Is(err, config.ErrAuthorizationRequired):
|
||||
code = "CONFIG_AUTHORIZATION_REQUIRED"
|
||||
status = http.StatusForbidden
|
||||
message = "当前账户没有执行此配置操作的权限"
|
||||
case errors.Is(err, config.ErrStepUpRequired):
|
||||
code = "CONFIG_STEP_UP_REQUIRED"
|
||||
status = http.StatusPreconditionRequired
|
||||
message = "请完成近期重新认证或 WebAuthn 二次确认"
|
||||
case errors.Is(err, config.ErrAuditWrite):
|
||||
code = "CONFIG_AUDIT_WRITE_FAILED"
|
||||
status = http.StatusServiceUnavailable
|
||||
message = "配置审计暂时不可用,操作未完成"
|
||||
case errors.Is(err, config.ErrBackupListingUnavailable), errors.Is(err, config.ErrAuditQueryUnavailable), errors.Is(err, config.ErrAuditStorageUnavailable), errors.Is(err, config.ErrConfigRecoveryRequired):
|
||||
code = "CONFIG_READ_UNAVAILABLE"
|
||||
status = http.StatusServiceUnavailable
|
||||
message = "配置历史数据暂时不可用,请稍后重试"
|
||||
case errors.Is(err, config.ErrNoBackup):
|
||||
code = "CONFIG_BACKUP_NOT_FOUND"
|
||||
status = http.StatusNotFound
|
||||
message = "未找到可用的配置备份"
|
||||
case errors.Is(err, config.ErrAuditNotFound):
|
||||
code = "CONFIG_AUDIT_NOT_FOUND"
|
||||
status = http.StatusNotFound
|
||||
message = "未找到指定的配置审计记录"
|
||||
case errors.Is(err, dbmigration.ErrMigrationNotFound):
|
||||
code = "DATABASE_MIGRATION_NOT_FOUND"
|
||||
status = http.StatusNotFound
|
||||
message = "未找到指定的数据库迁移记录"
|
||||
case errors.Is(err, dbmigration.ErrPreviewExpired):
|
||||
code = "DATABASE_MIGRATION_PREVIEW_EXPIRED"
|
||||
status = http.StatusConflict
|
||||
message = "数据库迁移预览已过期,请重新生成预览"
|
||||
case errors.Is(err, dbmigration.ErrExecutorUnavailable):
|
||||
code = "DATABASE_MIGRATION_UNAVAILABLE"
|
||||
status = http.StatusServiceUnavailable
|
||||
message = "数据库迁移执行器暂未配置,请先完成服务部署"
|
||||
case errors.Is(err, dbmigration.ErrMigrationState):
|
||||
code = "DATABASE_MIGRATION_STATE_INVALID"
|
||||
status = http.StatusConflict
|
||||
message = "数据库迁移当前状态不允许执行该操作"
|
||||
case errors.Is(err, dbmigration.ErrPreviewInvalid):
|
||||
code = "DATABASE_MIGRATION_PREVIEW_INVALID"
|
||||
status = http.StatusForbidden
|
||||
message = "数据库迁移预览票据无效"
|
||||
case errors.Is(err, dbmigration.ErrInvalidRequest), errors.Is(err, dbmigration.ErrInvalidTargetName), errors.Is(err, dbmigration.ErrImmutableSetting), errors.Is(err, dbmigration.ErrSourceDatabase):
|
||||
code = "DATABASE_MIGRATION_VALIDATION_FAILED"
|
||||
status = http.StatusUnprocessableEntity
|
||||
message = "数据库迁移参数校验未通过"
|
||||
case errors.Is(err, config.ErrInvalidRuntimeConfig), errors.Is(err, config.ErrPortConflict), errors.Is(err, config.ErrInvalidDomainConfig), errors.Is(err, config.ErrPluginCapability), errors.Is(err, config.ErrInvalidSetupState), errors.Is(err, config.ErrInvalidDatabase), errors.Is(err, config.ErrInvalidSMTP), errors.Is(err, config.ErrInvalidSSL), errors.Is(err, config.ErrInvalidPlugin), errors.Is(err, config.ErrInvalidHTTP), errors.Is(err, config.ErrInvalidEmail), errors.Is(err, config.ErrInvalidLogLevel), errors.Is(err, config.ErrInvalidSecretChange), errors.Is(err, config.ErrSecretClearDenied), errors.Is(err, config.ErrSecretUnavailable), errors.Is(err, config.ErrInvalidSection), errors.Is(err, config.ErrInvalidSectionReference), errors.Is(err, config.ErrSectionGenerationMismatch), errors.Is(err, config.ErrInvalidSSLMode), errors.Is(err, config.ErrInvalidSSLMaterial), errors.Is(err, config.ErrInvalidSSLReference), errors.Is(err, config.ErrUnsafeSSLFile), errors.Is(err, config.ErrSSLCertificateMismatch), errors.Is(err, config.ErrSSLCertificateDomain), errors.Is(err, config.ErrSSLCertificateExpired), errors.Is(err, config.ErrSSLPrivateKeyPermission), errors.Is(err, config.ErrInvalidAuditQuery), errors.Is(err, config.ErrInvalidAuditFormat):
|
||||
code = "CONFIG_VALIDATION_FAILED"
|
||||
status = http.StatusUnprocessableEntity
|
||||
message = "配置校验未通过,请检查填写内容"
|
||||
case errors.Is(err, config.ErrTransactionInvalid), errors.Is(err, config.ErrTransactionPhase), errors.Is(err, config.ErrConfigDigestMismatch), errors.Is(err, config.ErrConfigGenerationMismatch):
|
||||
code = "CONFIG_TRANSACTION_FAILED"
|
||||
status = http.StatusServiceUnavailable
|
||||
message = "配置事务未完成,系统仍保持原有配置"
|
||||
default:
|
||||
fields = map[string]string{"request": "invalid"}
|
||||
}
|
||||
|
||||
return code, status, message, fields
|
||||
}
|
||||
|
||||
func writeConfigError(w http.ResponseWriter, err error) {
|
||||
requestID := strings.TrimSpace(w.Header().Get("X-Request-ID"))
|
||||
if !requestIDPattern.MatchString(requestID) {
|
||||
requestID = EnsureConfigRequestID(w, nil)
|
||||
}
|
||||
code, status, message, fields := configErrorDetails(err)
|
||||
data := response.ConfigErrorData{Code: code, RequestID: requestID, Fields: fields}
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.WriteHeader(status)
|
||||
response.NewErrorResponse(response.ConfigErrorNumber(status), message, data).FPrint(w)
|
||||
}
|
||||
|
||||
func writeConfigAccessError(w http.ResponseWriter, err error) {
|
||||
writeConfigError(w, err)
|
||||
}
|
||||
@@ -6,6 +6,8 @@ import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.pcux.cn/xuans/Smail/config"
|
||||
|
||||
"git.pcux.cn/xuans/Smail/dto/response"
|
||||
"git.pcux.cn/xuans/Smail/services/access"
|
||||
)
|
||||
@@ -40,3 +42,51 @@ func TestWriteConfigErrorDoesNotExposeInternalErrorText(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnsureConfigRequestIDPreservesSafeHeader(t *testing.T) {
|
||||
recorder := httptest.NewRecorder()
|
||||
request := httptest.NewRequest("GET", "/api/v1/config/status", nil)
|
||||
request.Header.Set("X-Request-ID", "ui-request-42")
|
||||
if got := EnsureConfigRequestID(recorder, request); got != "ui-request-42" {
|
||||
t.Fatalf("safe request id was not preserved: %q", got)
|
||||
}
|
||||
if recorder.Header().Get("X-Request-ID") != "ui-request-42" {
|
||||
t.Fatalf("response request id header was not preserved: %q", recorder.Header().Get("X-Request-ID"))
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnsureConfigRequestIDReplacesUnsafeHeader(t *testing.T) {
|
||||
recorder := httptest.NewRecorder()
|
||||
request := httptest.NewRequest("GET", "/api/v1/config/status", nil)
|
||||
request.Header.Set("X-Request-ID", "../../secret")
|
||||
requestID := EnsureConfigRequestID(recorder, request)
|
||||
if requestID == "../../secret" || !requestIDPattern.MatchString(requestID) {
|
||||
t.Fatalf("unsafe request id was not replaced: %q", requestID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWriteConfigErrorUsesStableCodeAndHTTPStatus(t *testing.T) {
|
||||
recorder := httptest.NewRecorder()
|
||||
recorder.Header().Set("X-Request-ID", "request-99")
|
||||
writeConfigError(recorder, config.ErrGenerationConflict)
|
||||
|
||||
if recorder.Code != 409 {
|
||||
t.Fatalf("unexpected HTTP status: %d", recorder.Code)
|
||||
}
|
||||
var payload struct {
|
||||
ErrorMsg string `json:"errorMsg"`
|
||||
Data response.ConfigErrorData `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(recorder.Body.Bytes(), &payload); err != nil {
|
||||
t.Fatalf("failed to decode configuration error response: %v", err)
|
||||
}
|
||||
if payload.Data.Code != "CONFIG_GENERATION_CONFLICT" {
|
||||
t.Fatalf("unexpected stable error code: %q", payload.Data.Code)
|
||||
}
|
||||
if payload.Data.RequestID != "request-99" {
|
||||
t.Fatalf("unexpected request id: %q", payload.Data.RequestID)
|
||||
}
|
||||
if payload.ErrorMsg == "" || strings.Contains(payload.ErrorMsg, "generation conflict") {
|
||||
t.Fatalf("configuration error message is not a Chinese public message: %q", payload.ErrorMsg)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package controllers
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
|
||||
"git.pcux.cn/xuans/Smail/config"
|
||||
)
|
||||
|
||||
func TestPublicPluginConfigIncludesNonSensitiveSettings(t *testing.T) {
|
||||
runtime := config.RuntimeConfig{
|
||||
Plugins: config.PluginsSectionConfig{
|
||||
Meta: config.SectionMeta{Schema: config.CurrentSectionSchema, Generation: 3},
|
||||
Plugins: map[string]config.PluginInstance{
|
||||
"spam_block": {
|
||||
Enabled: true,
|
||||
Executable: "spam_block.exe",
|
||||
Settings: json.RawMessage(`{"url":"https://model.example.com/v1/predict","timeout":3000,"threshold":20}`),
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
public, err := publicConfigSection(runtime, config.SectionPlugins)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
data, err := json.Marshal(public)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
var decoded struct {
|
||||
Plugins map[string]struct {
|
||||
Settings map[string]any `json:"settings"`
|
||||
} `json:"plugins"`
|
||||
}
|
||||
if err := json.Unmarshal(data, &decoded); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
settings, ok := decoded.Plugins["spam_block"].Settings["url"]
|
||||
if !ok || settings != "https://model.example.com/v1/predict" {
|
||||
t.Fatalf("public plugin settings were not returned: %s", data)
|
||||
}
|
||||
if _, ok := decoded.Plugins["spam_block"].Settings["password"]; ok {
|
||||
t.Fatalf("public plugin settings contain a password field: %s", data)
|
||||
}
|
||||
if _, ok := decoded.Plugins["spam_block"].Settings["secret"]; ok {
|
||||
t.Fatalf("public plugin settings contain a secret field: %s", data)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package controllers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"git.pcux.cn/xuans/Smail/config"
|
||||
"git.pcux.cn/xuans/Smail/dto/response"
|
||||
"git.pcux.cn/xuans/Smail/services/access"
|
||||
"git.pcux.cn/xuans/Smail/services/dbmigration"
|
||||
appcontext "git.pcux.cn/xuans/Smail/utils/context"
|
||||
)
|
||||
|
||||
type databaseMigrationPreviewRequest struct {
|
||||
TargetName string `json:"targetName"`
|
||||
ExpectedGeneration uint64 `json:"expectedGeneration"`
|
||||
}
|
||||
|
||||
type databaseMigrationExecuteRequest struct {
|
||||
ID string `json:"id"`
|
||||
Token string `json:"token"`
|
||||
}
|
||||
|
||||
// PreviewDatabaseMigration 校验只改数据库名称的迁移计划,不连接或修改目标数据库。
|
||||
func PreviewDatabaseMigration(ctx *appcontext.Context, w http.ResponseWriter, req *http.Request) {
|
||||
if err := authorizeCapability(ctx, access.CapabilityDatabaseMigrate, "", false); err != nil {
|
||||
writeConfigAccessError(w, err)
|
||||
return
|
||||
}
|
||||
manager, ok := configManagerOrError(w)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
service := dbmigration.Current()
|
||||
if service == nil {
|
||||
writeConfigError(w, dbmigration.ErrExecutorUnavailable)
|
||||
return
|
||||
}
|
||||
var input databaseMigrationPreviewRequest
|
||||
if err := decodeJSONRequest(w, req, &input); err != nil || input.ExpectedGeneration == 0 {
|
||||
writeConfigError(w, dbmigration.ErrInvalidRequest)
|
||||
return
|
||||
}
|
||||
status := manager.Status()
|
||||
if input.ExpectedGeneration != status.ActiveGeneration {
|
||||
writeConfigError(w, config.ErrGenerationConflict)
|
||||
return
|
||||
}
|
||||
record, token, err := service.Preview(req.Context(), manager.Snapshot().Root.Database, status.ActiveGeneration, input.TargetName)
|
||||
if err != nil {
|
||||
writeConfigError(w, err)
|
||||
return
|
||||
}
|
||||
response.NewSuccessResponse(map[string]any{"migration": record, "token": token}).FPrint(w)
|
||||
}
|
||||
|
||||
// ExecuteDatabaseMigration 执行预览票据对应的固定迁移计划,不接受 DSN、SQL 或连接参数。
|
||||
func ExecuteDatabaseMigration(ctx *appcontext.Context, w http.ResponseWriter, req *http.Request) {
|
||||
if err := authorizeCapability(ctx, access.CapabilityDatabaseMigrate, "", false); err != nil {
|
||||
writeConfigAccessError(w, err)
|
||||
return
|
||||
}
|
||||
if dbmigration.Current() == nil {
|
||||
writeConfigError(w, dbmigration.ErrExecutorUnavailable)
|
||||
return
|
||||
}
|
||||
var input databaseMigrationExecuteRequest
|
||||
if err := decodeJSONRequest(w, req, &input); err != nil {
|
||||
writeConfigError(w, dbmigration.ErrInvalidRequest)
|
||||
return
|
||||
}
|
||||
record, err := dbmigration.Current().Execute(req.Context(), input.ID, input.Token)
|
||||
if err != nil {
|
||||
writeConfigError(w, err)
|
||||
return
|
||||
}
|
||||
response.NewSuccessResponse(record).FPrint(w)
|
||||
}
|
||||
|
||||
// GetDatabaseMigration 返回迁移状态,不返回密码、密钥或底层数据库错误。
|
||||
func GetDatabaseMigration(ctx *appcontext.Context, w http.ResponseWriter, req *http.Request) {
|
||||
if err := authorizeCapability(ctx, access.CapabilityDatabaseMigrate, "", false); err != nil {
|
||||
writeConfigAccessError(w, err)
|
||||
return
|
||||
}
|
||||
service := dbmigration.Current()
|
||||
if service == nil {
|
||||
writeConfigError(w, dbmigration.ErrExecutorUnavailable)
|
||||
return
|
||||
}
|
||||
parts := strings.Split(strings.Trim(req.URL.Path, "/"), "/")
|
||||
if len(parts) != 5 || parts[0] != "api" || parts[1] != "v1" || parts[2] != "database" || parts[3] != "migrations" || strings.TrimSpace(parts[4]) == "" {
|
||||
writeConfigError(w, dbmigration.ErrInvalidRequest)
|
||||
return
|
||||
}
|
||||
record, err := service.Get(parts[4])
|
||||
if err != nil {
|
||||
writeConfigError(w, err)
|
||||
return
|
||||
}
|
||||
response.NewSuccessResponse(record).FPrint(w)
|
||||
}
|
||||
@@ -54,10 +54,10 @@ func TestEditUserPasswordResetRoleMatrix(t *testing.T) {
|
||||
adminContext := &appcontext.Context{UserID: admin.ID, UserAccount: admin.Account, Role: access.RoleAdmin, RecentAuth: true, RecoveryCodeConfigured: true, Lang: "zhCn"}
|
||||
userContext := &appcontext.Context{UserID: user.ID, UserAccount: user.Account, Role: access.RoleUser, RecentAuth: true, RecoveryCodeConfigured: true, Lang: "zhCn"}
|
||||
|
||||
if result := editUserRequest(t, superContext, `{"id":`+itoa(admin.ID)+`,"password":"ResetAdmin123","disabled":0}`); result != 0 {
|
||||
if result := editUserRequest(t, superContext, `{"id":`+itoa(admin.ID)+`,"password":"ResetAdm12","disabled":0}`); result != 0 {
|
||||
t.Fatalf("super administrator could not reset administrator: %d", result)
|
||||
}
|
||||
assertUserPassword(t, admin.ID, "ResetAdmin123")
|
||||
assertUserPassword(t, admin.ID, "ResetAdm12")
|
||||
|
||||
if result := editUserRequest(t, adminContext, `{"id":`+itoa(user.ID)+`,"password":"ResetUser123","disabled":0}`); result != 0 {
|
||||
t.Fatalf("administrator could not reset regular user: %d", result)
|
||||
|
||||
@@ -67,6 +67,11 @@ func SettingsHtml(ctx *context.Context, w http.ResponseWriter, req *http.Request
|
||||
w.Header().Set("Allow", http.MethodGet+", "+http.MethodPost)
|
||||
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
} else {
|
||||
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
|
||||
w.WriteHeader(http.StatusGone)
|
||||
_, _ = w.Write([]byte("旧版插件配置保存接口已停用,请使用新版插件配置接口"))
|
||||
return
|
||||
}
|
||||
req.Body = http.MaxBytesReader(w, req.Body, 64<<10)
|
||||
requestData, err := io.ReadAll(req.Body)
|
||||
@@ -84,12 +89,7 @@ func SettingsHtml(ctx *context.Context, w http.ResponseWriter, req *http.Request
|
||||
response.NewErrorResponse(response.ServerError, "", "").FPrint(w)
|
||||
return
|
||||
}
|
||||
if req.Method == http.MethodPost && content == "success" {
|
||||
if err := hooks.PersistPluginConfig(pluginName, string(requestData)); err != nil {
|
||||
response.NewErrorResponse(response.ServerError, "", "").FPrint(w)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
if req.Method == http.MethodGet {
|
||||
if strings.HasSuffix(resourcePath, ".js") {
|
||||
w.Header().Set("Content-Type", "application/javascript; charset=utf-8")
|
||||
|
||||
@@ -63,8 +63,11 @@ func TestSettingsHtmlSeparatesStaticAndSaveRequests(t *testing.T) {
|
||||
|
||||
postRecorder := httptest.NewRecorder()
|
||||
SettingsHtml(&context.Context{IsAdmin: true}, postRecorder, httptest.NewRequest(http.MethodPost, "/api/plugin/settings/PluginTest/save", strings.NewReader(`{"url":"https://model.example.com"}`)))
|
||||
if hook.resource != "PluginTest/save" || hook.body == "" || !strings.HasPrefix(postRecorder.Header().Get("Content-Type"), "text/plain") {
|
||||
t.Fatalf("plugin save request was not isolated: resource=%s body=%s type=%s", hook.resource, hook.body, postRecorder.Header().Get("Content-Type"))
|
||||
if postRecorder.Code != http.StatusGone {
|
||||
t.Fatalf("legacy plugin save status = %d, want %d", postRecorder.Code, http.StatusGone)
|
||||
}
|
||||
if hook.resource != "PluginTest/index.html" || hook.body != "" {
|
||||
t.Fatalf("stopped plugin save request reached the plugin: resource=%s body=%s", hook.resource, hook.body)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,178 @@
|
||||
package controllers
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"git.pcux.cn/xuans/Smail/dto/response"
|
||||
"git.pcux.cn/xuans/Smail/hooks"
|
||||
"git.pcux.cn/xuans/Smail/hooks/framework"
|
||||
"git.pcux.cn/xuans/Smail/services/access"
|
||||
pluginservice "git.pcux.cn/xuans/Smail/services/plugin"
|
||||
"git.pcux.cn/xuans/Smail/utils/context"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
const maxTelegramUserSettingsBodyBytes int64 = 16 << 10
|
||||
|
||||
type telegramSettingsRequest struct {
|
||||
Settings pluginservice.TelegramUserSettings `json:"settings"`
|
||||
Version uint64 `json:"version"`
|
||||
}
|
||||
|
||||
func GetTelegramUserSettings(ctx *context.Context, w http.ResponseWriter, req *http.Request) {
|
||||
if !authenticatedPluginUser(ctx) {
|
||||
response.NewErrorResponse(response.NeedLogin, "请先登录", "").FPrint(w)
|
||||
return
|
||||
}
|
||||
service := hooks.PluginConfigService()
|
||||
if service == nil {
|
||||
response.NewErrorResponse(response.ServerError, "插件配置服务不可用", "").FPrint(w)
|
||||
return
|
||||
}
|
||||
settings, err := service.GetOwnTelegramSettings(ctx.UserID)
|
||||
if err != nil {
|
||||
writeTelegramSettingsError(w, err)
|
||||
return
|
||||
}
|
||||
response.NewSuccessResponse(settings).FPrint(w)
|
||||
}
|
||||
|
||||
func UpdateTelegramUserSettings(ctx *context.Context, w http.ResponseWriter, req *http.Request) {
|
||||
if !authenticatedPluginUser(ctx) {
|
||||
response.NewErrorResponse(response.NeedLogin, "请先登录", "").FPrint(w)
|
||||
return
|
||||
}
|
||||
var input telegramSettingsRequest
|
||||
if !decodePluginJSONBody(w, req, &input) {
|
||||
return
|
||||
}
|
||||
if err := pluginservice.ValidateTelegramUserSettings(input.Settings); err != nil {
|
||||
writeTelegramSettingsError(w, err)
|
||||
return
|
||||
}
|
||||
service := hooks.PluginConfigService()
|
||||
if service == nil {
|
||||
response.NewErrorResponse(response.ServerError, "插件配置服务不可用", "").FPrint(w)
|
||||
return
|
||||
}
|
||||
settings, err := service.UpdateOwnTelegramSettings(ctx.UserID, input.Settings, input.Version)
|
||||
if err != nil {
|
||||
writeTelegramSettingsError(w, err)
|
||||
return
|
||||
}
|
||||
if err := hooks.SyncTelegramUserSettings(ctx.UserID, settings.Settings); err != nil {
|
||||
log.WithError(err).Warnf("Telegram 用户设置同步失败,用户 ID=%d", ctx.UserID)
|
||||
}
|
||||
response.NewSuccessResponse(settings).FPrint(w)
|
||||
}
|
||||
|
||||
func GetTelegramBotInfo(ctx *context.Context, w http.ResponseWriter, req *http.Request) {
|
||||
if !authenticatedPluginUser(ctx) {
|
||||
response.NewErrorResponse(response.NeedLogin, "请先登录", "").FPrint(w)
|
||||
return
|
||||
}
|
||||
hook, ok := hooks.GetHook("telegram_push")
|
||||
if !ok {
|
||||
response.NewErrorResponse(response.ServerError, "Telegram 插件不可用", "").FPrint(w)
|
||||
return
|
||||
}
|
||||
provider, ok := hook.(framework.BotInfoProvider)
|
||||
if !ok {
|
||||
response.NewErrorResponse(response.ServerError, "Telegram 插件不支持机器人信息", "").FPrint(w)
|
||||
return
|
||||
}
|
||||
info, err := provider.GetBotInfo()
|
||||
if err != nil {
|
||||
log.WithError(err).Warn("获取 Telegram 机器人信息失败")
|
||||
response.NewErrorResponse(response.ServerError, "获取 Telegram 机器人信息失败", "").FPrint(w)
|
||||
return
|
||||
}
|
||||
response.NewSuccessResponse(info).FPrint(w)
|
||||
}
|
||||
|
||||
func TestTelegramMessage(ctx *context.Context, w http.ResponseWriter, req *http.Request) {
|
||||
if !authenticatedPluginUser(ctx) {
|
||||
response.NewErrorResponse(response.NeedLogin, "请先登录", "").FPrint(w)
|
||||
return
|
||||
}
|
||||
var input telegramSettingsRequest
|
||||
if !decodePluginJSONBody(w, req, &input) {
|
||||
return
|
||||
}
|
||||
if strings.TrimSpace(input.Settings.ChatID) == "" {
|
||||
response.NewErrorResponse(response.ParamsError, "请输入 Telegram 聊天 ID", "").FPrint(w)
|
||||
return
|
||||
}
|
||||
if err := pluginservice.ValidateTelegramUserSettings(input.Settings); err != nil {
|
||||
writeTelegramSettingsError(w, err)
|
||||
return
|
||||
}
|
||||
hook, ok := hooks.GetHook("telegram_push")
|
||||
if !ok {
|
||||
response.NewErrorResponse(response.ServerError, "Telegram 插件不可用", "").FPrint(w)
|
||||
return
|
||||
}
|
||||
provider, ok := hook.(framework.TestMessageProvider)
|
||||
if !ok {
|
||||
response.NewErrorResponse(response.ServerError, "Telegram 插件不支持测试消息", "").FPrint(w)
|
||||
return
|
||||
}
|
||||
payload, err := json.Marshal(input.Settings)
|
||||
if err != nil {
|
||||
response.NewErrorResponse(response.ServerError, "测试消息参数处理失败", "").FPrint(w)
|
||||
return
|
||||
}
|
||||
if err := provider.TestMessage(payload); err != nil {
|
||||
log.WithError(err).Warn("发送 Telegram 测试消息失败")
|
||||
response.NewErrorResponse(response.ServerError, "发送 Telegram 测试消息失败", "").FPrint(w)
|
||||
return
|
||||
}
|
||||
response.NewSuccessResponse(map[string]string{"message": "测试消息已发送"}).FPrint(w)
|
||||
}
|
||||
|
||||
func authenticatedPluginUser(ctx *context.Context) bool {
|
||||
return ctx != nil && ctx.UserID > 0
|
||||
}
|
||||
|
||||
func decodePluginJSONBody(w http.ResponseWriter, req *http.Request, target any) bool {
|
||||
req.Body = http.MaxBytesReader(w, req.Body, maxTelegramUserSettingsBodyBytes)
|
||||
defer req.Body.Close()
|
||||
decoder := json.NewDecoder(req.Body)
|
||||
decoder.DisallowUnknownFields()
|
||||
if err := decoder.Decode(target); err != nil {
|
||||
var maxBytesErr *http.MaxBytesError
|
||||
if errors.As(err, &maxBytesErr) {
|
||||
response.NewErrorResponse(response.ParamsError, "请求内容过大", "").FPrint(w)
|
||||
} else {
|
||||
response.NewErrorResponse(response.ParamsError, "请求参数格式不正确", "").FPrint(w)
|
||||
}
|
||||
return false
|
||||
}
|
||||
if err := decoder.Decode(&struct{}{}); !errors.Is(err, io.EOF) {
|
||||
response.NewErrorResponse(response.ParamsError, "请求参数格式不正确", "").FPrint(w)
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func writeTelegramSettingsError(w http.ResponseWriter, err error) {
|
||||
if errors.Is(err, pluginservice.ErrInvalidTelegramChatID) {
|
||||
response.NewErrorResponse(response.ParamsError, "Telegram 聊天 ID 格式不正确", "").FPrint(w)
|
||||
return
|
||||
}
|
||||
if errors.Is(err, pluginservice.ErrPluginSettingConflict) {
|
||||
response.NewErrorResponse(response.ParamsError, "配置已被其他操作更新,请刷新后重试", "").FPrint(w)
|
||||
return
|
||||
}
|
||||
var denial *access.Denial
|
||||
if errors.As(err, &denial) {
|
||||
response.NewErrorResponse(response.NoAccessPrivileges, "无权修改插件设置", "").FPrint(w)
|
||||
return
|
||||
}
|
||||
log.WithError(err).Error("Telegram 插件设置操作失败")
|
||||
response.NewErrorResponse(response.ServerError, "插件设置操作失败", "").FPrint(w)
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
package controllers
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.pcux.cn/xuans/Smail/db/migration"
|
||||
"git.pcux.cn/xuans/Smail/hooks"
|
||||
"git.pcux.cn/xuans/Smail/hooks/framework"
|
||||
"git.pcux.cn/xuans/Smail/models"
|
||||
pluginservice "git.pcux.cn/xuans/Smail/services/plugin"
|
||||
appcontext "git.pcux.cn/xuans/Smail/utils/context"
|
||||
"git.pcux.cn/xuans/Smail/utils/credential"
|
||||
_ "modernc.org/sqlite"
|
||||
"xorm.io/xorm"
|
||||
)
|
||||
|
||||
type telegramControllerTestHook struct {
|
||||
pluginTestHook
|
||||
botInfo framework.BotInfo
|
||||
botInfoErr error
|
||||
testPayload json.RawMessage
|
||||
testMessageErr error
|
||||
userID int
|
||||
userSettings json.RawMessage
|
||||
}
|
||||
|
||||
func (h *telegramControllerTestHook) ConfigureUserSettings(userID int, settings json.RawMessage) error {
|
||||
h.userID = userID
|
||||
h.userSettings = append(h.userSettings[:0], settings...)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h *telegramControllerTestHook) GetBotInfo() (framework.BotInfo, error) {
|
||||
return h.botInfo, h.botInfoErr
|
||||
}
|
||||
|
||||
func (h *telegramControllerTestHook) TestMessage(settings json.RawMessage) error {
|
||||
h.testPayload = append(h.testPayload[:0], settings...)
|
||||
return h.testMessageErr
|
||||
}
|
||||
|
||||
func TestTelegramUserSettingsRequiresLogin(t *testing.T) {
|
||||
request := httptest.NewRequest(http.MethodGet, "/api/v1/plugin/settings/telegram_push/user", nil)
|
||||
recorder := httptest.NewRecorder()
|
||||
GetTelegramUserSettings(nil, recorder, request)
|
||||
if recorder.Code != http.StatusOK || !strings.Contains(recorder.Body.String(), "请先登录") {
|
||||
t.Fatalf("unauthenticated GET status=%d body=%s", recorder.Code, recorder.Body.String())
|
||||
}
|
||||
|
||||
request = httptest.NewRequest(http.MethodPut, "/api/v1/plugin/settings/telegram_push/user", strings.NewReader(`{}`))
|
||||
recorder = httptest.NewRecorder()
|
||||
UpdateTelegramUserSettings(&appcontext.Context{}, recorder, request)
|
||||
if recorder.Code != http.StatusOK || !strings.Contains(recorder.Body.String(), "请先登录") {
|
||||
t.Fatalf("unauthenticated PUT status=%d body=%s", recorder.Code, recorder.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestTelegramUserSettingsRejectsUnknownAndTrailingFields(t *testing.T) {
|
||||
hooks.SetPluginConfigService(nil)
|
||||
t.Cleanup(func() { hooks.SetPluginConfigService(nil) })
|
||||
|
||||
cases := []string{
|
||||
`{"settings":{"chatId":"123","userId":99},"version":0}`,
|
||||
`{"settings":{"chatId":"123"},"version":0} {}`,
|
||||
}
|
||||
for _, body := range cases {
|
||||
recorder := httptest.NewRecorder()
|
||||
request := httptest.NewRequest(http.MethodPut, "/api/v1/plugin/settings/telegram_push/user", bytes.NewBufferString(body))
|
||||
UpdateTelegramUserSettings(&appcontext.Context{UserID: 7}, recorder, request)
|
||||
if recorder.Code != http.StatusOK || !strings.Contains(recorder.Body.String(), "请求参数格式不正确") {
|
||||
t.Fatalf("body=%s status=%d response=%s", body, recorder.Code, recorder.Body.String())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestTelegramUserSettingsUsesSessionUserAndVersion(t *testing.T) {
|
||||
service, engine := newTelegramControllerConfigService(t)
|
||||
previousService := hooks.PluginConfigService()
|
||||
hooks.SetPluginConfigService(service)
|
||||
t.Cleanup(func() { hooks.SetPluginConfigService(previousService) })
|
||||
|
||||
user := models.User{Account: "controller-user", Name: "controller-user", Password: "hash"}
|
||||
if _, err := engine.Insert(&user); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
firstRecorder := httptest.NewRecorder()
|
||||
firstRequest := httptest.NewRequest(http.MethodPut, "/api/v1/plugin/settings/telegram_push/user", strings.NewReader(`{"settings":{"chatId":"-1001234567890","showContent":true},"version":0}`))
|
||||
UpdateTelegramUserSettings(&appcontext.Context{UserID: user.ID}, firstRecorder, firstRequest)
|
||||
if firstRecorder.Code != http.StatusOK || !strings.Contains(firstRecorder.Body.String(), `"version":1`) {
|
||||
t.Fatalf("first update status=%d body=%s", firstRecorder.Code, firstRecorder.Body.String())
|
||||
}
|
||||
if strings.Contains(firstRecorder.Body.String(), "bot-token") {
|
||||
t.Fatal("secret material appeared in settings response")
|
||||
}
|
||||
|
||||
staleRecorder := httptest.NewRecorder()
|
||||
staleRequest := httptest.NewRequest(http.MethodPut, "/api/v1/plugin/settings/telegram_push/user", strings.NewReader(`{"settings":{"chatId":"123"},"version":0}`))
|
||||
UpdateTelegramUserSettings(&appcontext.Context{UserID: user.ID}, staleRecorder, staleRequest)
|
||||
if staleRecorder.Code != http.StatusOK || !strings.Contains(staleRecorder.Body.String(), "配置已被其他操作更新") {
|
||||
t.Fatalf("stale update status=%d body=%s", staleRecorder.Code, staleRecorder.Body.String())
|
||||
}
|
||||
|
||||
getRecorder := httptest.NewRecorder()
|
||||
GetTelegramUserSettings(&appcontext.Context{UserID: user.ID}, getRecorder, httptest.NewRequest(http.MethodGet, "/api/v1/plugin/settings/telegram_push/user", nil))
|
||||
if getRecorder.Code != http.StatusOK || !strings.Contains(getRecorder.Body.String(), "-1001234567890") {
|
||||
t.Fatalf("GET status=%d body=%s", getRecorder.Code, getRecorder.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestTelegramBotInfoDoesNotExposeSecret(t *testing.T) {
|
||||
previousHooks := hooks.HookList
|
||||
hook := &telegramControllerTestHook{botInfo: framework.BotInfo{Username: "smail_test_bot", BotLink: "https://t.me/smail_test_bot"}}
|
||||
hooks.HookList = map[string]framework.EmailHook{"telegram_push": hook}
|
||||
t.Cleanup(func() { hooks.HookList = previousHooks })
|
||||
|
||||
recorder := httptest.NewRecorder()
|
||||
GetTelegramBotInfo(&appcontext.Context{UserID: 7}, recorder, httptest.NewRequest(http.MethodGet, "/api/v1/plugin/settings/telegram_push/bot", nil))
|
||||
if recorder.Code != http.StatusOK || !strings.Contains(recorder.Body.String(), "smail_test_bot") {
|
||||
t.Fatalf("status=%d body=%s", recorder.Code, recorder.Body.String())
|
||||
}
|
||||
if strings.Contains(recorder.Body.String(), "bot-token") || strings.Contains(recorder.Body.String(), "secret") {
|
||||
t.Fatalf("bot response exposed secret material: %s", recorder.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestTelegramTestMessageValidatesChatIDAndDoesNotPersist(t *testing.T) {
|
||||
previousHooks := hooks.HookList
|
||||
hook := &telegramControllerTestHook{}
|
||||
hooks.HookList = map[string]framework.EmailHook{"telegram_push": hook}
|
||||
t.Cleanup(func() { hooks.HookList = previousHooks })
|
||||
|
||||
invalidRecorder := httptest.NewRecorder()
|
||||
invalidRequest := httptest.NewRequest(http.MethodPost, "/api/v1/plugin/settings/telegram_push/test", strings.NewReader(`{"settings":{"chatId":"not-a-chat"}}`))
|
||||
TestTelegramMessage(&appcontext.Context{UserID: 7}, invalidRecorder, invalidRequest)
|
||||
if invalidRecorder.Code != http.StatusOK || !strings.Contains(invalidRecorder.Body.String(), "聊天 ID 格式不正确") {
|
||||
t.Fatalf("invalid message status=%d body=%s", invalidRecorder.Code, invalidRecorder.Body.String())
|
||||
}
|
||||
if hook.testPayload != nil {
|
||||
t.Fatal("invalid test message reached plugin")
|
||||
}
|
||||
|
||||
validRecorder := httptest.NewRecorder()
|
||||
validRequest := httptest.NewRequest(http.MethodPost, "/api/v1/plugin/settings/telegram_push/test", strings.NewReader(`{"settings":{"chatId":"123"},"version":99}`))
|
||||
TestTelegramMessage(&appcontext.Context{UserID: 7}, validRecorder, validRequest)
|
||||
if validRecorder.Code != http.StatusOK || !strings.Contains(validRecorder.Body.String(), "测试消息已发送") {
|
||||
t.Fatalf("valid message status=%d body=%s", validRecorder.Code, validRecorder.Body.String())
|
||||
}
|
||||
if !strings.Contains(string(hook.testPayload), `"chatId":"123"`) {
|
||||
t.Fatalf("plugin did not receive validated settings: %s", hook.testPayload)
|
||||
}
|
||||
}
|
||||
|
||||
func newTelegramControllerConfigService(t *testing.T) (*pluginservice.ConfigService, *xorm.Engine) {
|
||||
t.Helper()
|
||||
engine, err := xorm.NewEngine("sqlite", filepath.Join(t.TempDir(), "telegram-controller.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 := pluginservice.NewConfigService(engine, vault)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return service, engine
|
||||
}
|
||||
@@ -3,12 +3,33 @@ package controllers
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"git.pcux.cn/xuans/Smail/config"
|
||||
"git.pcux.cn/xuans/Smail/dto/response"
|
||||
"git.pcux.cn/xuans/Smail/services/access"
|
||||
"git.pcux.cn/xuans/Smail/services/restart"
|
||||
appcontext "git.pcux.cn/xuans/Smail/utils/context"
|
||||
)
|
||||
|
||||
// PreviewRestartSmail 返回固定的 Smail 重启预览,不执行重启动作。
|
||||
func PreviewRestartSmail(ctx *appcontext.Context, w http.ResponseWriter, req *http.Request) {
|
||||
if err := authorizeCapability(ctx, access.CapabilityServiceRestart, "", false); err != nil {
|
||||
response.NewErrorResponse(response.NoAccessPrivileges, "重启预览需要近期认证和有效离线恢复码", "").FPrint(w)
|
||||
return
|
||||
}
|
||||
manager := config.CurrentManager()
|
||||
if manager == nil {
|
||||
response.NewErrorResponse(response.ServerError, "重启预览暂时不可用", "").FPrint(w)
|
||||
return
|
||||
}
|
||||
status := manager.Status()
|
||||
pending := make([]string, 0, len(status.PendingRestart))
|
||||
for _, service := range status.PendingRestart {
|
||||
pending = append(pending, string(service))
|
||||
}
|
||||
preview := restart.BuildPreview(status.ActiveGeneration, pending, restart.Current() != nil)
|
||||
response.NewSuccessResponse(preview).FPrint(w)
|
||||
}
|
||||
|
||||
// RestartSmail 请求固定的 Smail 服务重启,不接受外部命令或服务参数。
|
||||
func RestartSmail(ctx *appcontext.Context, w http.ResponseWriter, req *http.Request) {
|
||||
if err := authorizeCapability(ctx, access.CapabilityServiceRestart, "", false); err != nil {
|
||||
|
||||
@@ -44,7 +44,7 @@ func newPublicSecurityFixture(t *testing.T) (*recovery.Service, *webauthnservice
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
passwordHash, err := auth.HashPassword("FixturePassword@123")
|
||||
passwordHash, err := auth.HashPassword("FixtureP12")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -76,7 +76,7 @@ func ModifyPassword(ctx *context.Context, w http.ResponseWriter, req *http.Reque
|
||||
}
|
||||
if err := auth.SetPassword(&user, retData.Password); err != nil {
|
||||
if errors.Is(err, password.ErrInvalidLength) {
|
||||
response.NewErrorResponse(response.ParamsError, "\u5bc6\u7801\u957f\u5ea6\u5fc5\u987b\u4e3a 8-256 \u5b57\u8282", "").FPrint(w)
|
||||
response.NewErrorResponse(response.ParamsError, "\u5bc6\u7801\u957f\u5ea6\u5fc5\u987b\u4e3a 8-12 \u5b57\u8282", "").FPrint(w)
|
||||
return
|
||||
}
|
||||
log.WithContext(ctx).WithError(err).Error("password hash failed")
|
||||
|
||||
@@ -50,7 +50,7 @@ func TestModifyPasswordRequiresCurrentPassword(t *testing.T) {
|
||||
}
|
||||
|
||||
user := models.User{Account: "password-change-user", Name: "密码修改用户"}
|
||||
if err := auth.SetPassword(&user, "CorrectPass123"); err != nil {
|
||||
if err := auth.SetPassword(&user, "CorrectP12"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := db.Instance.Insert(&user); err != nil {
|
||||
@@ -77,11 +77,11 @@ func TestModifyPasswordRequiresCurrentPassword(t *testing.T) {
|
||||
if _, err := db.Instance.ID(user.ID).Get(&unchanged); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if unchanged.Password != originalHash || !password.Verify(unchanged.Password, "CorrectPass123") {
|
||||
if unchanged.Password != originalHash || !password.Verify(unchanged.Password, "CorrectP12") {
|
||||
t.Fatal("password was changed after current password verification failed")
|
||||
}
|
||||
|
||||
request = httptest.NewRequest(http.MethodPost, "/api/settings/modify_password", strings.NewReader(`{"current_password":"CorrectPass123","password":"NewPass123"}`))
|
||||
request = httptest.NewRequest(http.MethodPost, "/api/settings/modify_password", strings.NewReader(`{"current_password":"CorrectP12","password":"NewPass123"}`))
|
||||
loadedContext, err := session.Instance.Load(request.Context(), "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
|
||||
@@ -86,7 +86,7 @@ func CreateUser(ctx *context.Context, w http.ResponseWriter, req *http.Request)
|
||||
user.ApplyRole(targetRole)
|
||||
if err := auth.SetPassword(&user, reqData.Password); err != nil {
|
||||
if errors.Is(err, password.ErrInvalidLength) {
|
||||
response.NewErrorResponse(response.ParamsError, "\u5bc6\u7801\u957f\u5ea6\u5fc5\u987b\u4e3a 8-256 \u5b57\u8282", "").FPrint(w)
|
||||
response.NewErrorResponse(response.ParamsError, "\u5bc6\u7801\u957f\u5ea6\u5fc5\u987b\u4e3a 8-12 \u5b57\u8282", "").FPrint(w)
|
||||
return
|
||||
}
|
||||
log.WithContext(ctx).WithError(err).Error("password hash failed")
|
||||
@@ -262,7 +262,7 @@ func EditUser(ctx *context.Context, w http.ResponseWriter, req *http.Request) {
|
||||
if reqData.Password != "" {
|
||||
if err := auth.SetPassword(&user, reqData.Password); err != nil {
|
||||
if errors.Is(err, password.ErrInvalidLength) {
|
||||
response.NewErrorResponse(response.ParamsError, "\u5bc6\u7801\u957f\u5ea6\u5fc5\u987b\u4e3a 8-256 \u5b57\u8282", "").FPrint(w)
|
||||
response.NewErrorResponse(response.ParamsError, "\u5bc6\u7801\u957f\u5ea6\u5fc5\u987b\u4e3a 8-12 \u5b57\u8282", "").FPrint(w)
|
||||
return
|
||||
}
|
||||
log.WithContext(ctx).WithError(err).Error("password hash failed")
|
||||
|
||||
Reference in new issue
Block a user