feat: add folder uploads and archives with simpler account and plan forms
This commit is contained in:
1 parent
9afd7d0067
commit
faaa614cee
41 files changed
+1027
-71
No files matched your search
@@ -0,0 +1,12 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
)
|
||||
|
||||
// Stable internal IDs keep batch previews and retries consistent without exposing an extra form field.
|
||||
func accountSlug(login string) string {
|
||||
digest := sha256.Sum256([]byte(login))
|
||||
return "u-" + hex.EncodeToString(digest[:10])
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"github.com/go-sql-driver/mysql"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"sea-vhost/internal/auth"
|
||||
"sea-vhost/internal/config"
|
||||
"sea-vhost/internal/isolation"
|
||||
"sea-vhost/internal/panel"
|
||||
"sea-vhost/internal/service"
|
||||
"sea-vhost/internal/store"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestNamedAccountMySQL(t *testing.T) {
|
||||
dsn := os.Getenv("SEA_TEST_MYSQL_DSN")
|
||||
if dsn == "" {
|
||||
t.Skip("disposable MySQL schema not supplied")
|
||||
}
|
||||
parsed, err := mysql.ParseDSN(dsn)
|
||||
if err != nil || !strings.HasPrefix(parsed.DBName, "svh_cluster_test_") {
|
||||
t.Fatal("refusing a non-test schema")
|
||||
}
|
||||
db, err := store.Open(dsn)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer db.Close()
|
||||
ctx := context.Background()
|
||||
must := func(err error) {
|
||||
t.Helper()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
must(db.Migrate(ctx))
|
||||
must(db.BootstrapAdmin(ctx, "identity-admin@example.invalid", "测试管理员", "identity-admin-password-123"))
|
||||
admin, err := db.UserByLogin(ctx, "identity-admin@example.invalid")
|
||||
must(err)
|
||||
root := t.TempDir()
|
||||
must(db.InitializeLocalNode(ctx, "hosts.example.invalid", root, "control.example.invalid"))
|
||||
secret := "named-account-test-session-secret-at-least-thirty-two-characters"
|
||||
projects := service.NewProjects(db, panel.NewMock(), isolation.Mock{Root: root}, "hosts.example.invalid", root, true, secret, "control.example.invalid")
|
||||
server := New(config.Config{SessionSecret: secret, ManagementDomain: "control.example.invalid", CookieSecure: true, SessionTTL: time.Hour}, db, projects)
|
||||
token, err := auth.NewSessionToken(secret)
|
||||
must(err)
|
||||
must(db.CreateSession(ctx, admin.ID, token, time.Now().Add(time.Hour)))
|
||||
call := func(method, path string, body any, session string) *httptest.ResponseRecorder {
|
||||
var buffer bytes.Buffer
|
||||
must(json.NewEncoder(&buffer).Encode(body))
|
||||
r := httptest.NewRequest(method, "https://control.example.invalid"+path, &buffer)
|
||||
r.Header.Set("Origin", "https://control.example.invalid")
|
||||
r.Header.Set("Content-Type", "application/json")
|
||||
if session != "" {
|
||||
r.AddCookie(&http.Cookie{Name: "sea_session", Value: session})
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(w, r)
|
||||
return w
|
||||
}
|
||||
expect := func(w *httptest.ResponseRecorder, status int) {
|
||||
t.Helper()
|
||||
if w.Code != status {
|
||||
t.Fatalf("HTTP %d want %d: %s", w.Code, status, w.Body.String())
|
||||
}
|
||||
}
|
||||
input := map[string]any{"loginName": "customer01", "displayName": "测试用户", "email": "customer01@example.invalid", "password": "identity-user-password-123", "planId": 1}
|
||||
created := call("POST", "/api/v1/admin/tenants", input, token)
|
||||
expect(created, 201)
|
||||
var value struct {
|
||||
ID uint64 `json:"id"`
|
||||
}
|
||||
must(json.Unmarshal(created.Body.Bytes(), &value))
|
||||
profile, err := db.AccountProfile(ctx, value.ID)
|
||||
must(err)
|
||||
if profile.LoginName != "customer01" || profile.Name != "测试用户" || profile.DisplayName != "测试用户" || profile.Slug != accountSlug("customer01") {
|
||||
t.Fatalf("unexpected profile: %+v", profile)
|
||||
}
|
||||
for _, login := range []string{"customer01", "customer01@example.invalid"} {
|
||||
expect(call("POST", "/api/v1/auth/login", map[string]string{"identifier": login, "password": "identity-user-password-123"}, ""), 200)
|
||||
}
|
||||
expect(call("POST", "/api/v1/auth/login", map[string]string{"identifier": "customer01", "password": "incorrect-password"}, ""), 401)
|
||||
duplicate := map[string]any{"loginName": "customer01", "displayName": "重复用户", "email": "different@example.invalid", "password": "identity-user-password-123", "planId": 1}
|
||||
expect(call("POST", "/api/v1/admin/tenants", duplicate, token), 422)
|
||||
input["loginName"] = "another-user"
|
||||
expect(call("POST", "/api/v1/admin/tenants", input, token), 422)
|
||||
input["loginName"] = "bad@name"
|
||||
expect(call("POST", "/api/v1/admin/tenants", input, token), 422)
|
||||
list, err := db.ListTenants(ctx)
|
||||
must(err)
|
||||
if len(list) != 1 || list[0].LoginName != "customer01" {
|
||||
t.Fatalf("unexpected user list: %+v", list)
|
||||
}
|
||||
profile.Email = "updated@example.invalid"
|
||||
profile.Name = "修改名称"
|
||||
profile.DisplayName = profile.Name
|
||||
must(db.UpdateAccount(ctx, value.ID, profile))
|
||||
updated, err := db.UserByLogin(ctx, "customer01")
|
||||
must(err)
|
||||
if updated.Email != profile.Email {
|
||||
t.Fatal("email update failed")
|
||||
}
|
||||
_, err = db.UserByLogin(ctx, "customer01@example.invalid")
|
||||
if err == nil {
|
||||
t.Fatal("old email still usable")
|
||||
}
|
||||
batch := batchRequest{Operation: "create_users", Rows: []batchRow{{LoginName: "batch-account", DisplayName: "批量用户", Email: "batch-account@example.invalid"}}}
|
||||
preview, err := server.normalizeBatch(ctx, &batch)
|
||||
must(err)
|
||||
if len(preview) != 1 || !preview[0].Valid {
|
||||
t.Fatalf("batch preview rejected: %+v", preview)
|
||||
}
|
||||
stable := batch.Rows[0].Slug
|
||||
preview, err = server.normalizeBatch(ctx, &batch)
|
||||
must(err)
|
||||
if !preview[0].Valid || stable != batch.Rows[0].Slug {
|
||||
t.Fatal("batch identity changed on retry")
|
||||
}
|
||||
result, err := server.performBatchRow(ctx, "create_users", batch.Rows[0])
|
||||
must(err)
|
||||
if result.Login != "batch-account" || result.Password == "" {
|
||||
t.Fatal("batch credentials missing login account")
|
||||
}
|
||||
expect(call("POST", "/api/v1/auth/login", map[string]string{"identifier": result.Login, "password": result.Password}, ""), 200)
|
||||
preview, err = server.normalizeBatch(ctx, &batch)
|
||||
must(err)
|
||||
if preview[0].Valid {
|
||||
t.Fatal("duplicate batch account accepted")
|
||||
}
|
||||
t.Log("single creation, account/email login, password rejection, duplicate/invalid account rejection, stable batch identity, user listing and email update passed")
|
||||
}
|
||||
@@ -85,6 +85,7 @@ func (s *Server) adminTenants(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
var input struct {
|
||||
Slug string `json:"slug"`
|
||||
LoginName string `json:"loginName"`
|
||||
Name string `json:"name"`
|
||||
Email string `json:"email"`
|
||||
DisplayName string `json:"displayName"`
|
||||
@@ -96,9 +97,18 @@ func (s *Server) adminTenants(w http.ResponseWriter, r *http.Request) {
|
||||
writeError(w, http.StatusBadRequest, "请求格式错误")
|
||||
return
|
||||
}
|
||||
input.LoginName = strings.ToLower(strings.TrimSpace(input.LoginName))
|
||||
if input.LoginName != "" {
|
||||
if !tenantSlugPattern.MatchString(input.LoginName) {
|
||||
writeError(w, 422, "登录账号应为 3–48 位小写字母、数字或连字符,首尾不能是连字符")
|
||||
return
|
||||
}
|
||||
input.Slug = accountSlug(input.LoginName)
|
||||
input.Name = input.DisplayName
|
||||
}
|
||||
input.Slug = strings.ToLower(strings.TrimSpace(input.Slug))
|
||||
if !tenantSlugPattern.MatchString(input.Slug) || strings.TrimSpace(input.Name) == "" || len(input.Password) < 12 {
|
||||
writeError(w, http.StatusUnprocessableEntity, "用户标识、名称或密码不符合要求")
|
||||
if !tenantSlugPattern.MatchString(input.Slug) || strings.TrimSpace(input.Name) == "" || (len(input.Password) < 12 || len(input.Password) > 72) {
|
||||
writeError(w, http.StatusUnprocessableEntity, "登录账号、显示名称或密码不符合要求")
|
||||
return
|
||||
}
|
||||
address, err := mail.ParseAddress(strings.TrimSpace(input.Email))
|
||||
@@ -109,16 +119,16 @@ func (s *Server) adminTenants(w http.ResponseWriter, r *http.Request) {
|
||||
input.Name = strings.TrimSpace(input.Name)
|
||||
input.DisplayName = strings.TrimSpace(input.DisplayName)
|
||||
if len([]rune(input.Name)) > 120 || len([]rune(input.DisplayName)) < 2 || len([]rune(input.DisplayName)) > 80 || input.PlanID == 0 {
|
||||
writeError(w, http.StatusUnprocessableEntity, "用户名称、管理员名称或套餐无效")
|
||||
writeError(w, http.StatusUnprocessableEntity, "显示名称或套餐无效")
|
||||
return
|
||||
}
|
||||
if _, err = s.store.Plan(r.Context(), input.PlanID); err != nil {
|
||||
writeError(w, http.StatusUnprocessableEntity, "所选套餐不存在")
|
||||
return
|
||||
}
|
||||
id, err := s.store.CreateTenant(r.Context(), store.NewTenant{Slug: input.Slug, Name: input.Name, Email: strings.TrimSpace(input.Email), DisplayName: input.DisplayName, Password: input.Password, PlanID: input.PlanID, ExpiresAt: input.ExpiresAt})
|
||||
id, err := s.store.CreateTenant(r.Context(), store.NewTenant{LoginName: input.LoginName, Slug: input.Slug, Name: input.Name, Email: strings.TrimSpace(input.Email), DisplayName: input.DisplayName, Password: input.Password, PlanID: input.PlanID, ExpiresAt: input.ExpiresAt})
|
||||
if err != nil {
|
||||
writeError(w, http.StatusUnprocessableEntity, "无法创建用户,请检查标识或邮箱是否重复")
|
||||
writeError(w, http.StatusUnprocessableEntity, "无法创建用户,请检查登录账号或邮箱是否重复")
|
||||
return
|
||||
}
|
||||
user := currentUser(r)
|
||||
|
||||
@@ -27,6 +27,7 @@ import (
|
||||
type batchRow struct {
|
||||
Name string `json:"name,omitempty"`
|
||||
Slug string `json:"slug,omitempty"`
|
||||
LoginName string `json:"loginName,omitempty"`
|
||||
Email string `json:"email,omitempty"`
|
||||
DisplayName string `json:"displayName,omitempty"`
|
||||
Password string `json:"password,omitempty"`
|
||||
@@ -128,6 +129,16 @@ func (s *Server) normalizeBatch(ctx context.Context, input *batchRequest) ([]bat
|
||||
var validation error
|
||||
switch input.Operation {
|
||||
case "create_users":
|
||||
row.LoginName = strings.ToLower(strings.TrimSpace(row.LoginName))
|
||||
if row.LoginName != "" {
|
||||
if !tenantSlugPattern.MatchString(row.LoginName) {
|
||||
validation = errors.New("登录账号格式无效")
|
||||
}
|
||||
row.Slug = accountSlug(row.LoginName)
|
||||
if row.Name == "" {
|
||||
row.Name = row.DisplayName
|
||||
}
|
||||
}
|
||||
row.Slug = strings.ToLower(strings.TrimSpace(row.Slug))
|
||||
row.Email = strings.ToLower(strings.TrimSpace(row.Email))
|
||||
row.Name = strings.TrimSpace(row.Name)
|
||||
@@ -150,17 +161,24 @@ func (s *Server) normalizeBatch(ctx context.Context, input *batchRequest) ([]bat
|
||||
}
|
||||
key := "user:" + row.Email
|
||||
slugKey := "slug:" + row.Slug
|
||||
if validation == nil && (seen[key] || seen[slugKey]) {
|
||||
if validation == nil && (seen[key] || seen[slugKey] || (row.LoginName != "" && seen["login:"+row.LoginName])) {
|
||||
validation = errors.New("同批邮箱或用户标识重复")
|
||||
}
|
||||
seen[key] = true
|
||||
seen[slugKey] = true
|
||||
if row.LoginName != "" {
|
||||
seen["login:"+row.LoginName] = true
|
||||
}
|
||||
if validation == nil {
|
||||
exists, e := s.store.AccountIdentityExists(ctx, row.Slug, row.Email)
|
||||
if e != nil {
|
||||
validation = errors.New("无法核对现有账号")
|
||||
} else if exists {
|
||||
validation = errors.New("邮箱或用户标识已存在")
|
||||
} else if row.LoginName != "" {
|
||||
if exists, e = s.store.AccountIdentityExists(ctx, row.Slug, row.LoginName); e != nil || exists {
|
||||
validation = errors.New("登录账号已存在或无法核对")
|
||||
}
|
||||
}
|
||||
}
|
||||
preview.Label = row.Email
|
||||
@@ -610,9 +628,12 @@ func (s *Server) performBatchRow(ctx context.Context, operation string, row batc
|
||||
return result, err
|
||||
}
|
||||
}
|
||||
id, err := s.store.CreateTenant(ctx, store.NewTenant{Slug: row.Slug, Name: row.Name, Email: row.Email, DisplayName: row.DisplayName, Password: row.Password, PlanID: row.PlanID})
|
||||
id, err := s.store.CreateTenant(ctx, store.NewTenant{LoginName: row.LoginName, Slug: row.Slug, Name: row.Name, Email: row.Email, DisplayName: row.DisplayName, Password: row.Password, PlanID: row.PlanID})
|
||||
result.ResourceID = id
|
||||
result.Login = row.Email
|
||||
result.Login = row.LoginName
|
||||
if result.Login == "" {
|
||||
result.Login = row.Email
|
||||
}
|
||||
result.Password = row.Password
|
||||
return result, err
|
||||
}
|
||||
|
||||
@@ -185,14 +185,18 @@ func (s *Server) downloadFile(w http.ResponseWriter, r *http.Request, root *node
|
||||
}
|
||||
|
||||
func (s *Server) uploadFile(w http.ResponseWriter, r *http.Request, tenantID uint64, root string) {
|
||||
r.Body = http.MaxBytesReader(w, r.Body, s.cfg.UploadLimitBytes+1<<20)
|
||||
if err := r.ParseMultipartForm(s.cfg.UploadLimitBytes); err != nil {
|
||||
writeError(w, http.StatusRequestEntityTooLarge, uploadLimitMessage(s.cfg.UploadLimitBytes))
|
||||
r.Body = http.MaxBytesReader(w, r.Body, batchUploadLimit+1<<20)
|
||||
if err := r.ParseMultipartForm(1 << 20); err != nil {
|
||||
writeError(w, http.StatusRequestEntityTooLarge, "上传请求过大:单批总量不超过 30 MB,单文件不超过 20 MB")
|
||||
return
|
||||
}
|
||||
if r.MultipartForm != nil {
|
||||
defer r.MultipartForm.RemoveAll()
|
||||
}
|
||||
if r.FormValue("batch") == "true" || len(r.MultipartForm.File["file"]) > 1 {
|
||||
s.uploadBatchFiles(w, r, tenantID, root)
|
||||
return
|
||||
}
|
||||
source, header, err := r.FormFile("file")
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, "缺少上传文件")
|
||||
|
||||
@@ -54,7 +54,7 @@ func (s *Server) adminAccount(w http.ResponseWriter, r *http.Request) {
|
||||
input.Email = strings.ToLower(strings.TrimSpace(input.Email))
|
||||
address, e := mail.ParseAddress(input.Email)
|
||||
if input.Name == "" || len([]rune(input.Name)) > 120 || len([]rune(input.DisplayName)) < 2 || len([]rune(input.DisplayName)) > 80 || e != nil || address.Address != input.Email || len(input.Email) > 190 {
|
||||
writeError(w, 422, "请检查用户名称、联系人姓名和登录邮箱")
|
||||
writeError(w, 422, "请检查显示名称和登录邮箱")
|
||||
return
|
||||
}
|
||||
err = s.store.UpdateAccount(r.Context(), id, input)
|
||||
|
||||
@@ -1,14 +1,18 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"archive/tar"
|
||||
"bytes"
|
||||
"compress/gzip"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"github.com/go-sql-driver/mysql"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sea-vhost/internal/auth"
|
||||
"sea-vhost/internal/config"
|
||||
"sea-vhost/internal/isolation"
|
||||
@@ -55,7 +59,7 @@ func TestResourceCRUDMySQL(t *testing.T) {
|
||||
secret := "crud-test-session-secret-at-least-thirty-two-characters"
|
||||
native := &pendingStatePanel{Mock: panel.NewMock(), states: map[int64]bool{}}
|
||||
projects := service.NewProjects(db, native, isolation.Mock{Root: root}, "hosts.example.invalid", root, true, secret, "control.example.invalid")
|
||||
server := New(config.Config{SessionSecret: secret, ManagementDomain: "control.example.invalid", CookieSecure: true, SessionTTL: time.Hour}, db, projects)
|
||||
server := New(config.Config{SessionSecret: secret, ManagementDomain: "control.example.invalid", CookieSecure: true, SessionTTL: time.Hour, UploadLimitBytes: 20 << 20}, db, projects)
|
||||
token, err := auth.NewSessionToken(secret)
|
||||
must(err)
|
||||
must(db.CreateSession(ctx, admin.ID, token, time.Now().Add(time.Hour)))
|
||||
@@ -124,7 +128,7 @@ func TestResourceCRUDMySQL(t *testing.T) {
|
||||
p := &pythonInstallPanel{Mock: panel.NewMock()}
|
||||
isolator := pythonInstallIsolation{Mock: isolation.Mock{Root: root}, panel: p}
|
||||
svc := service.NewProjects(db, p, isolator, "hosts.example.invalid", root, true, secret, "control.example.invalid")
|
||||
api := New(config.Config{SessionSecret: secret, ManagementDomain: "control.example.invalid", CookieSecure: true, SessionTTL: time.Hour}, db, svc)
|
||||
api := New(config.Config{SessionSecret: secret, ManagementDomain: "control.example.invalid", CookieSecure: true, SessionTTL: time.Hour, UploadLimitBytes: 20 << 20}, db, svc)
|
||||
r := httptest.NewRequest("POST", "https://control.example.invalid/api/v1/admin/runtime-environments/Python/install", strings.NewReader(`{"version":"3.13.1"}`))
|
||||
r.Header.Set("Origin", "https://control.example.invalid")
|
||||
r.Header.Set("Content-Type", "application/json")
|
||||
@@ -194,6 +198,129 @@ func TestResourceCRUDMySQL(t *testing.T) {
|
||||
created, err := projects.CreateManagedHost(scope.WithNode(ctx, 1), account, service.CreateProjectInput{NodeID: 1, PlanID: 1, Name: "crud-host", Runtime: "PHP", Version: "8.4", RunPath: "/public"})
|
||||
must(err)
|
||||
id := created.Project.ID
|
||||
|
||||
t.Run("batch upload and archive formats", func(t *testing.T) {
|
||||
must := func(err error) {
|
||||
t.Helper()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
must(os.MkdirAll(created.Project.Path, 0770))
|
||||
fresh, err := auth.NewSessionToken(secret)
|
||||
must(err)
|
||||
must(db.CreateSession(ctx, user.ID, fresh, time.Now().Add(time.Hour)))
|
||||
upload := func(files map[string][]byte, overwrite bool, folder ...bool) *httptest.ResponseRecorder {
|
||||
var body bytes.Buffer
|
||||
writer := multipart.NewWriter(&body)
|
||||
writer.WriteField("path", "")
|
||||
writer.WriteField("batch", "true")
|
||||
if overwrite {
|
||||
writer.WriteField("overwrite", "true")
|
||||
}
|
||||
relative := []string{}
|
||||
for name, data := range files {
|
||||
relative = append(relative, name)
|
||||
part, e := writer.CreateFormFile("file", name)
|
||||
must(e)
|
||||
_, e = part.Write(data)
|
||||
must(e)
|
||||
}
|
||||
if len(folder) > 0 && folder[0] {
|
||||
raw, e := json.Marshal(relative)
|
||||
must(e)
|
||||
must(writer.WriteField("relativePaths", string(raw)))
|
||||
}
|
||||
must(writer.Close())
|
||||
request := httptest.NewRequest("POST", "https://control.example.invalid/api/v1/projects/"+strconv.FormatUint(id, 10)+"/files", &body)
|
||||
request.Header.Set("Origin", "https://control.example.invalid")
|
||||
request.Header.Set("Content-Type", writer.FormDataContentType())
|
||||
request.AddCookie(&http.Cookie{Name: "sea_session", Value: fresh})
|
||||
response := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(response, request)
|
||||
return response
|
||||
}
|
||||
expect(upload(map[string][]byte{"folder/a/index.php": []byte("alpha"), "folder/b/index.php": []byte("beta")}, false, true), 207)
|
||||
for name, want := range map[string]string{"folder/a/index.php": "alpha", "folder/b/index.php": "beta"} {
|
||||
raw, e := os.ReadFile(filepath.Join(created.Project.Path, name))
|
||||
must(e)
|
||||
if string(raw) != want {
|
||||
t.Fatal("folder structure lost")
|
||||
}
|
||||
}
|
||||
expect(upload(map[string][]byte{"folder/../escape.txt": []byte("unsafe")}, false, true), 400)
|
||||
if _, e := os.Stat(filepath.Join(created.Project.Path, "escape.txt")); !os.IsNotExist(e) {
|
||||
t.Fatal("invalid folder path wrote a file")
|
||||
}
|
||||
valid := upload(map[string][]byte{"bulk-a.txt": []byte("alpha"), "bulk-b.txt": []byte("beta")}, false)
|
||||
expect(valid, 207)
|
||||
data, e := os.ReadFile(filepath.Join(created.Project.Path, "bulk-a.txt"))
|
||||
must(e)
|
||||
if string(data) != "alpha" {
|
||||
t.Fatal("batch content mismatch")
|
||||
}
|
||||
conflict := upload(map[string][]byte{"bulk-a.txt": []byte("different"), "bulk-c.txt": []byte("gamma")}, false)
|
||||
expect(conflict, 207)
|
||||
var result struct {
|
||||
Files []uploadItem `json:"files"`
|
||||
}
|
||||
must(json.Unmarshal(conflict.Body.Bytes(), &result))
|
||||
success, duplicates := 0, 0
|
||||
for _, item := range result.Files {
|
||||
if item.Success {
|
||||
success++
|
||||
}
|
||||
if item.Status == 409 {
|
||||
duplicates++
|
||||
}
|
||||
}
|
||||
if success != 1 || duplicates != 1 {
|
||||
t.Fatalf("partial results: %+v", result.Files)
|
||||
}
|
||||
data, e = os.ReadFile(filepath.Join(created.Project.Path, "bulk-a.txt"))
|
||||
must(e)
|
||||
if string(data) != "alpha" {
|
||||
t.Fatal("unconfirmed overwrite")
|
||||
}
|
||||
expect(upload(map[string][]byte{"bulk-a.txt": []byte("updated")}, true), 207)
|
||||
expect(upload(map[string][]byte{"over-a.bin": make([]byte, 16<<20), "over-b.bin": make([]byte, 15<<20)}, false), 413)
|
||||
if _, e = os.Stat(filepath.Join(created.Project.Path, "over-a.bin")); !os.IsNotExist(e) {
|
||||
t.Fatal("oversized batch wrote a file")
|
||||
}
|
||||
expect(upload(map[string][]byte{"single-too-large.bin": make([]byte, (20<<20)+1)}, false), 413)
|
||||
expect(upload(map[string][]byte{"exact-a.bin": make([]byte, 20<<20), "exact-b.bin": make([]byte, 10<<20)}, false), 207)
|
||||
info, e := os.Stat(filepath.Join(created.Project.Path, "exact-a.bin"))
|
||||
must(e)
|
||||
if info.Size() != 20<<20 {
|
||||
t.Fatal("boundary upload truncated")
|
||||
}
|
||||
for _, ext := range []string{".tar", ".tar.gz", ".tgz"} {
|
||||
var raw bytes.Buffer
|
||||
tw := tar.NewWriter(&raw)
|
||||
must(tw.WriteHeader(&tar.Header{Name: "folder/index.txt", Mode: 0660, Size: 5}))
|
||||
_, e = tw.Write([]byte("hello"))
|
||||
must(e)
|
||||
must(tw.Close())
|
||||
content := raw.Bytes()
|
||||
if ext != ".tar" {
|
||||
var packed bytes.Buffer
|
||||
gz := gzip.NewWriter(&packed)
|
||||
_, e = gz.Write(content)
|
||||
must(e)
|
||||
must(gz.Close())
|
||||
content = packed.Bytes()
|
||||
}
|
||||
name := "archive" + ext
|
||||
expect(upload(map[string][]byte{name: content}, false), 207)
|
||||
dest := "expanded" + strings.ReplaceAll(ext, ".", "-")
|
||||
expect(call("POST", "/api/v1/projects/"+strconv.FormatUint(id, 10)+"/file-actions", map[string]string{"action": "extract", "path": name, "to": dest}, fresh), 204)
|
||||
content, e = os.ReadFile(filepath.Join(created.Project.Path, dest, "folder/index.txt"))
|
||||
must(e)
|
||||
if string(content) != "hello" {
|
||||
t.Fatal("archive content mismatch")
|
||||
}
|
||||
}
|
||||
})
|
||||
pending, err := projects.CreateManagedHost(scope.WithNode(ctx, 1), 0, service.CreateProjectInput{NodeID: 1, PlanID: 1, Name: "pending-runtime", Runtime: "Node.js", Version: "v22.23.3", RunPath: "/"})
|
||||
must(err)
|
||||
if enabled, ok := native.states[pending.Project.PanelSiteID]; !ok || enabled {
|
||||
@@ -314,7 +441,7 @@ func TestResourceCRUDMySQL(t *testing.T) {
|
||||
// Exercise the actual worker while the panel is busy, not just SQL flags.
|
||||
gatePanel := &busyPatchPanel{Mock: panel.NewMock(), entered: make(chan struct{})}
|
||||
gateProjects := service.NewProjects(db, gatePanel, patchProbeIsolation{Mock: isolation.Mock{Root: root}}, "hosts.example.invalid", root, true, secret, "control.example.invalid")
|
||||
gateServer := New(config.Config{SessionSecret: secret, ManagementDomain: "control.example.invalid", CookieSecure: true, SessionTTL: time.Hour}, db, gateProjects)
|
||||
gateServer := New(config.Config{SessionSecret: secret, ManagementDomain: "control.example.invalid", CookieSecure: true, SessionTTL: time.Hour, UploadLimitBytes: 20 << 20}, db, gateProjects)
|
||||
busyJob, e := db.CreateRuntimeJob(scope.WithNode(ctx, 1), store.RuntimeJob{Action: "php_patch", Runtime: "PHP", FromVersion: "7.4.33", TargetVersion: "7.4.35"})
|
||||
must(e)
|
||||
workerCtx, stopWorker := context.WithCancel(ctx)
|
||||
|
||||
@@ -0,0 +1,183 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"sea-vhost/internal/nodefiles"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
const batchUploadLimit int64 = 30 << 20
|
||||
|
||||
type uploadItem struct {
|
||||
Name string `json:"name"`
|
||||
Size int64 `json:"size"`
|
||||
Success bool `json:"success"`
|
||||
Status int `json:"status"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
// Validate the whole selection before any file is committed.
|
||||
var errUploadPath = errors.New("文件夹相对路径无效、重复或包含系统保留目录")
|
||||
|
||||
func batchUploadNames(headers []*multipart.FileHeader, limit int64) ([]string, error) {
|
||||
return batchUploadPaths(headers, limit, nil)
|
||||
}
|
||||
func batchUploadPaths(headers []*multipart.FileHeader, limit int64, relative []string) ([]string, error) {
|
||||
if relative != nil && len(relative) != len(headers) {
|
||||
return nil, errUploadPath
|
||||
}
|
||||
if len(headers) == 0 || len(headers) > 100 {
|
||||
return nil, errors.New("每批请选择 1–100 个文件")
|
||||
}
|
||||
names := make([]string, len(headers))
|
||||
seen := map[string]bool{}
|
||||
var total int64
|
||||
for i, h := range headers {
|
||||
if h.Size < 0 || h.Size > limit {
|
||||
return nil, errors.New(uploadLimitMessage(limit))
|
||||
}
|
||||
if h.Size > batchUploadLimit-total {
|
||||
return nil, errors.New("单批上传总大小不能超过 30 MB")
|
||||
}
|
||||
total += h.Size
|
||||
name := filepath.Base(strings.ReplaceAll(h.Filename, "\\", "/"))
|
||||
if relative != nil {
|
||||
name = relative[i]
|
||||
if !utf8.ValidString(name) || len(name) > 1024 || strings.ContainsAny(name, "\\:\x00\r\n") || strings.HasPrefix(name, "/") || path.Clean(name) != name || nodefiles.IsProtectedPath(name) || path.Base(name) != filepath.Base(strings.ReplaceAll(h.Filename, "\\", "/")) {
|
||||
return nil, errUploadPath
|
||||
}
|
||||
parts := strings.Split(name, "/")
|
||||
if len(parts) > 32 {
|
||||
return nil, errUploadPath
|
||||
}
|
||||
for _, part := range parts {
|
||||
if part == "" || part == "." || part == ".." || len(part) > 255 {
|
||||
return nil, errUploadPath
|
||||
}
|
||||
}
|
||||
}
|
||||
if name == "." || name == ".." || name == "" || seen[name] {
|
||||
return nil, errors.New("文件名无效或本批存在同名文件")
|
||||
}
|
||||
names[i] = name
|
||||
seen[name] = true
|
||||
}
|
||||
for _, name := range names {
|
||||
for parent := path.Dir(name); parent != "."; parent = path.Dir(parent) {
|
||||
if seen[parent] {
|
||||
return nil, errUploadPath
|
||||
}
|
||||
}
|
||||
}
|
||||
return names, nil
|
||||
}
|
||||
|
||||
func (s *Server) uploadBatchFiles(w http.ResponseWriter, r *http.Request, tenantID uint64, root string) {
|
||||
headers := r.MultipartForm.File["file"]
|
||||
limit := min(s.cfg.UploadLimitBytes, int64(20<<20))
|
||||
var relative []string
|
||||
if raw := r.FormValue("relativePaths"); raw != "" {
|
||||
if len(raw) > 128<<10 || json.Unmarshal([]byte(raw), &relative) != nil || relative == nil {
|
||||
writeError(w, 400, "文件夹路径列表无效")
|
||||
return
|
||||
}
|
||||
}
|
||||
names, err := batchUploadPaths(headers, limit, relative)
|
||||
if err != nil {
|
||||
status := 413
|
||||
if errors.Is(err, errUploadPath) {
|
||||
status = 400
|
||||
}
|
||||
writeError(w, status, err.Error())
|
||||
return
|
||||
}
|
||||
dir, err := safeProjectName(root, r.FormValue("path"))
|
||||
if err != nil {
|
||||
writeError(w, 400, "路径无效")
|
||||
return
|
||||
}
|
||||
projectRoot, err := s.projects.OpenFiles(r.Context(), root)
|
||||
if err != nil {
|
||||
writeError(w, 404, "项目目录不存在")
|
||||
return
|
||||
}
|
||||
defer projectRoot.Close()
|
||||
targets := make([]string, len(names))
|
||||
overwrite := r.FormValue("overwrite") == "true"
|
||||
var additional uint64
|
||||
for i, name := range names {
|
||||
targets[i], err = safeProjectName(root, path.Join(dir, name))
|
||||
if err != nil {
|
||||
writeError(w, 400, "路径无效或包含系统保留文件")
|
||||
return
|
||||
}
|
||||
growth := uint64(headers[i].Size)
|
||||
if old, e := projectRoot.Lstat(targets[i]); e == nil && old.Mode().IsRegular() {
|
||||
if !overwrite {
|
||||
growth = 0
|
||||
} else if uint64(old.Size()) >= growth {
|
||||
growth = 0
|
||||
} else {
|
||||
growth -= uint64(old.Size())
|
||||
}
|
||||
}
|
||||
additional += growth
|
||||
}
|
||||
if err = s.projects.CheckStorageWrite(r.Context(), tenantID, additional); err != nil {
|
||||
writeFileQuotaError(w, err)
|
||||
return
|
||||
}
|
||||
results := make([]uploadItem, 0, len(names))
|
||||
for i, name := range names {
|
||||
result := uploadItem{Name: name, Status: 422, Error: "上传失败,请刷新目录核对"}
|
||||
flag := os.O_WRONLY | os.O_CREATE | os.O_EXCL
|
||||
if overwrite {
|
||||
flag = os.O_WRONLY | os.O_CREATE | os.O_TRUNC
|
||||
}
|
||||
source, e := headers[i].Open()
|
||||
if e == nil {
|
||||
if parent := path.Dir(filepath.ToSlash(targets[i])); parent != "." {
|
||||
if mkdirErr := projectRoot.MkdirAll(parent, 0770); mkdirErr != nil {
|
||||
source.Close()
|
||||
s.logFile(r, tenantID, "file_operation", "文件夹上传创建子目录失败:"+name)
|
||||
results = append(results, result)
|
||||
continue
|
||||
}
|
||||
}
|
||||
destination, openErr := projectRoot.OpenFile(targets[i], flag, 0660)
|
||||
if openErr == nil {
|
||||
written, copyErr := io.Copy(destination, io.LimitReader(source, limit+1))
|
||||
if copyErr == nil && written == headers[i].Size && written <= limit {
|
||||
e = destination.Close()
|
||||
} else {
|
||||
e = errors.New("upload truncated")
|
||||
}
|
||||
destination.Abort()
|
||||
if e == nil {
|
||||
result = uploadItem{Name: name, Size: written, Success: true, Status: 201}
|
||||
s.logFile(r, tenantID, "upload", "批量上传文件:"+filepath.ToSlash(targets[i]))
|
||||
}
|
||||
} else {
|
||||
e = openErr
|
||||
}
|
||||
source.Close()
|
||||
}
|
||||
if !result.Success {
|
||||
if errors.Is(e, os.ErrExist) {
|
||||
result.Status = 409
|
||||
result.Error = "同名文件已存在,未覆盖"
|
||||
}
|
||||
s.logFile(r, tenantID, "file_operation", "批量上传失败:"+name)
|
||||
}
|
||||
results = append(results, result)
|
||||
}
|
||||
writeJSON(w, 207, map[string]any{"files": results})
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"mime/multipart"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestBatchUploadLimitsBeforeWriting(t *testing.T) {
|
||||
const mb = 1 << 20
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
files []*multipart.FileHeader
|
||||
ok bool
|
||||
}{
|
||||
{"exact total", []*multipart.FileHeader{{Filename: "a", Size: 20 * mb}, {Filename: "b", Size: 10 * mb}}, true},
|
||||
{"over total", []*multipart.FileHeader{{Filename: "a", Size: 20 * mb}, {Filename: "b", Size: 10*mb + 1}}, false},
|
||||
{"over single", []*multipart.FileHeader{{Filename: "a", Size: 20*mb + 1}}, false},
|
||||
{"duplicate normalized name", []*multipart.FileHeader{{Filename: "a"}, {Filename: "folder/a"}}, false},
|
||||
{"empty", nil, false},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
_, err := batchUploadNames(test.files, 20*mb)
|
||||
if (err == nil) != test.ok {
|
||||
t.Fatalf("unexpected error %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
files := make([]*multipart.FileHeader, 101)
|
||||
for i := range files {
|
||||
files[i] = &multipart.FileHeader{Filename: "x"}
|
||||
}
|
||||
if _, err := batchUploadNames(files, 20*mb); err == nil {
|
||||
t.Fatal("unbounded file count accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestFolderUploadPathsAreRootedAndUnambiguous(t *testing.T) {
|
||||
headers := []*multipart.FileHeader{{Filename: "index.php", Size: 5}, {Filename: "index.php", Size: 4}}
|
||||
paths := []string{"site/a/index.php", "site/b/index.php"}
|
||||
names, err := batchUploadPaths(headers, 20<<20, paths)
|
||||
if err != nil || names[0] != paths[0] || names[1] != paths[1] {
|
||||
t.Fatalf("folder paths lost: %v %v", names, err)
|
||||
}
|
||||
for _, name := range []string{"../index.php", "/index.php", "site/../index.php", "site//index.php", "site/./index.php", `site\index.php`, "C:/index.php", "site/.sea-runtime/index.php", "site/.sea-trash/index.php", "site/.user.ini/index.php", "site/other.php"} {
|
||||
if _, err = batchUploadPaths(headers[:1], 20<<20, []string{name}); err == nil {
|
||||
t.Errorf("unsafe path accepted: %q", name)
|
||||
}
|
||||
}
|
||||
if _, err = batchUploadPaths(headers, 20<<20, paths[:1]); err == nil {
|
||||
t.Fatal("path count mismatch accepted")
|
||||
}
|
||||
conflicting := []*multipart.FileHeader{{Filename: "site"}, {Filename: "index.php"}}
|
||||
if _, err = batchUploadPaths(conflicting, 20<<20, []string{"site", "site/index.php"}); err == nil {
|
||||
t.Fatal("file/directory collision accepted")
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user