feat: add folder uploads and archives with simpler account and plan forms

This commit is contained in:
canglan committed 2026-11-15 18:57:02 +08:00
1 parent 9afd7d0067
commit faaa614cee
41 files changed
+1027 -71

No files matched your search

@@ -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)