Files
vHost/backend/internal/panel/client_test.go
T

809 lines
36 KiB
Go

package panel
import (
"context"
"encoding/json"
"net"
"net/http"
"net/http/httptest"
"net/url"
"reflect"
"strings"
"testing"
"time"
)
func TestSignatureMatchesPanelProtocol(t *testing.T) {
got := Signature("example-key", 1700000000)
const want = "22f7cc469919f6fdfe667286a3c7a64a"
if got != want {
t.Fatalf("Signature() = %q, want %q", got, want)
}
}
func TestDeleteDomainUsesExactSiteAndRetriesAfterRemoval(t *testing.T) {
deleted := 0
present := true
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_ = r.ParseForm()
w.Header().Set("Content-Type", "application/json")
if r.URL.Path == "/data" {
if r.Form.Get("search") != "17" || r.Form.Get("table") != "domain" || r.Form.Get("list") != "true" {
t.Error("unscoped domain query")
}
if present {
_, _ = w.Write([]byte(`[{"pid":17,"name":"custom.example.com","port":80}]`))
} else {
_, _ = w.Write([]byte(`[]`))
}
return
}
if r.URL.Path != "/site" || r.Form.Get("action") != "DelDomain" || r.Form.Get("id") != "17" || r.Form.Get("domain") != "custom.example.com" || r.Form.Get("port") != "80" {
t.Error("incorrect deletion payload")
}
deleted++
present = false
_, _ = w.Write([]byte(`{"status":true,"msg":"ok"}`))
}))
defer server.Close()
client := NewClient(server.URL, "key", false, 5*time.Second)
var err error
for range 2 {
if err = client.DeleteDomain(context.Background(), 17, "host.example.com", "custom.example.com"); err != nil {
t.Fatal(err)
}
}
if deleted != 1 {
t.Fatalf("delete calls=%d", deleted)
}
}
func TestLatestPythonBranchesExcludePrereleasesAndOrderPatchesNumerically(t *testing.T) {
got := latestPythonBranchVersions([]string{
"3.12.9", "3.12.15", "3.12.15", "3.14.9", "3.14.10rc1", "3.16.0a1",
"3.13.17", "3.13.18.dev1", "3.010.99", "3.12.015", "3.9.25", "2.7.18", "bad",
})
want := []string{"3.14.9", "3.13.17", "3.12.15"}
if !reflect.DeepEqual(got, want) {
t.Fatalf("latest stable branches = %#v, want %#v", got, want)
}
}
func TestParsePanelByteSize(t *testing.T) {
tests := map[string]uint64{"0.00b": 0, "1 KB": 1024, "1.5 MB": 1572864, "2GB": 2147483648}
for input, want := range tests {
got, err := parsePanelByteSize(input)
if err != nil || got != want {
t.Fatalf("parsePanelByteSize(%q) = %d, %v; want %d", input, got, err, want)
}
}
if _, err := parsePanelByteSize("unknown"); err == nil {
t.Fatal("invalid panel size was accepted")
}
}
func TestRuntimeCatalogUsesAaPanelProjectRoutes(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
switch r.URL.Path {
case "/site":
if r.FormValue("action") != "GetPHPVersion" {
t.Fatalf("unexpected site action %q", r.FormValue("action"))
}
_ = json.NewEncoder(w).Encode([]map[string]any{{"version": "74", "status": true}, {"version": "84", "status": true}, {"version": "00", "status": true}, {"version": "83", "status": false}})
case "/project/nodejs/get_nodejs_version/stype":
_ = json.NewEncoder(w).Encode([]string{"v24.21.0", "v22.23.3", "v24.22.1"})
case "/plugin":
if r.FormValue("action") != "a" || r.FormValue("name") != "pythonmamager" || r.FormValue("s") != "GetPythonV" {
t.Fatalf("unexpected Python manager request: %#v", r.Form)
}
_ = json.NewEncoder(w).Encode([]string{"3.12.15", "3.12.0", "3.11.17", "3.9.10"})
case "/project/go/list_go_sdk/stype":
_ = json.NewEncoder(w).Encode(map[string]any{"status": true, "installed": []string{"go1.25.14", "go1.27.1", "go1.27.3"}})
case "/mod/java/project/get_system_info/stype":
if r.Method != http.MethodGet {
t.Fatalf("Java inventory method = %s, want GET", r.Method)
}
_ = json.NewEncoder(w).Encode(map[string]any{"status": true, "data": map[string]any{"jdk_info": []map[string]any{{"name": "jdk-21.0.2", "path": "/www/server/java/jdk-21.0.2", "operation": 1}, {"name": "jdk-25.0.3", "path": "/www/server/java/jdk-25.0.3", "operation": 1}, {"name": "invalid value", "path": "/tmp", "operation": 1}}}})
default:
http.NotFound(w, r)
}
}))
defer server.Close()
client := NewClient(server.URL, "test-key", false, 5*time.Second)
catalog, err := client.RuntimeCatalog(context.Background())
if err != nil {
t.Fatal(err)
}
want := RuntimeCatalog{
"PHP": {"8.4", "7.4"}, "Node.js": {"v24.22.1", "v24.21.0", "v22.23.3"}, "Python": {"3.12.15", "3.11.17"},
"Go": {"go1.27.3", "go1.27.1", "go1.25.14"}, "Java": {"jdk-25.0.3", "jdk-21.0.2"},
}
if !reflect.DeepEqual(catalog, want) {
t.Fatalf("RuntimeCatalog() = %#v, want %#v", catalog, want)
}
}
func TestRuntimeCapabilitiesDoNotFailAsAGroup(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
switch r.URL.Path {
case "/site":
_ = json.NewEncoder(w).Encode([]map[string]any{{"version": "84", "status": true}})
case "/project/nodejs/get_nodejs_version/stype":
http.Error(w, "not installed", http.StatusNotFound)
case "/plugin":
_ = json.NewEncoder(w).Encode([]string{})
case "/project/go/list_go_sdk/stype":
_ = json.NewEncoder(w).Encode(map[string]any{"status": true, "installed": []string{"go1.27.1"}})
case "/mod/java/project/get_system_info/stype":
_ = json.NewEncoder(w).Encode(map[string]any{"status": false, "msg": "module unavailable"})
default:
http.NotFound(w, r)
}
}))
defer server.Close()
client := NewClient(server.URL, "test-key", false, 5*time.Second)
capabilities, err := client.RuntimeCapabilities(context.Background())
if err != nil {
t.Fatal(err)
}
if capabilities["PHP"].Status != RuntimeAvailable || capabilities["Python"].Status != RuntimeNotInstalled {
t.Fatalf("unexpected available/not-installed states: %#v", capabilities)
}
if capabilities["Node.js"].Status != RuntimeProbeFailed || capabilities["Java"].Status != RuntimeProbeFailed {
t.Fatalf("optional project failures were not isolated: %#v", capabilities)
}
if capabilities["Node.js"].Detail != "接口不存在或组件未安装" || strings.Contains(capabilities["Node.js"].Detail, "request_token") {
t.Fatalf("runtime probe detail is unsafe or unclear: %#v", capabilities["Node.js"])
}
if capabilities["Go"].Policy != PolicyFreeProject || capabilities["PHP"].Policy != PolicyFreeCore {
t.Fatalf("unexpected runtime policies: %#v", capabilities)
}
catalog, err := client.RuntimeCatalog(context.Background())
if err != nil || len(catalog["PHP"]) != 1 || len(catalog["Node.js"]) != 0 {
t.Fatalf("partial catalog = %#v, err = %v", catalog, err)
}
}
func TestFreePanelRequestPolicyRejectsPaidAndGenericRoutes(t *testing.T) {
for _, test := range []struct {
method, path, action string
}{
{http.MethodPost, "/plugin", "btwaf"},
{http.MethodPost, "/site", "GetWafConfig"},
{http.MethodPost, "/system", "SetSystemHardening"},
} {
if err := validateFreePanelRequest(test.method, test.path, url.Values{"action": {test.action}}); err == nil {
t.Fatalf("request unexpectedly allowed: %s %s action=%s", test.method, test.path, test.action)
}
}
if err := validateFreePanelRequest(http.MethodPost, "/site", url.Values{"action": {"AddSite"}}); err != nil {
t.Fatalf("free-core site request was rejected: %v", err)
}
if err := validateFreePanelRequest(http.MethodPost, "/data", url.Values{"action": {"getData"}, "table": {"users"}}); err == nil {
t.Fatal("generic panel data-table access was accepted")
}
if err := validateFreePanelRequest(http.MethodPost, "/data", url.Values{"action": {"getData"}, "table": {"ftps"}}); err != nil {
t.Fatalf("managed FTP lookup was rejected: %v", err)
}
if err := validateFreePanelRequest(http.MethodPost, "/plugin", url.Values{"action": {"get_soft_find"}, "sName": {"btwaf"}}); err == nil {
t.Fatal("paid plugin metadata request was accepted")
}
if err := validateFreePanelRequest(http.MethodPost, "/plugin", url.Values{"action": {"a"}, "name": {"nodejs"}, "s": {"uninstall_nodejs"}}); err == nil {
t.Fatal("Node.js plugin uninstall method was accepted")
}
}
func TestRuntimeEnvironmentInventoryUsesOnlyAdvertisedVersions(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
switch r.URL.Path {
case "/site":
_ = json.NewEncoder(w).Encode([]map[string]any{{"version": "84", "status": true}})
case "/plugin":
switch r.FormValue("action") {
case "get_soft_find":
switch r.FormValue("sName") {
case "php-8.4":
_ = json.NewEncoder(w).Encode(map[string]any{"name": "php-8.4", "price": 0, "panel_free": 1, "setup": true, "version": "8.4.25", "versions": []map[string]any{{"m_version": "8.4", "version": "27", "beta": 0}}})
case "nodejs":
_ = json.NewEncoder(w).Encode(map[string]any{"name": "nodejs", "title": "Node.js版本管理器", "price": 0, "panel_free": 1, "setup": true, "version": "8", "versions": []map[string]any{{"m_version": "2", "version": "8", "beta": 0}}})
case "pythonmamager":
_ = json.NewEncoder(w).Encode(map[string]any{"name": "pythonmamager", "title": "Python项目管理器", "price": 0, "panel_free": 1, "setup": true, "version": "2.5.1", "versions": []map[string]any{{"m_version": "2", "version": "5.1", "beta": 0}}})
default:
t.Fatalf("unexpected plugin metadata name %q", r.FormValue("sName"))
}
case "a":
switch r.FormValue("name") + "/" + r.FormValue("s") {
case "nodejs/get_online_version_list":
_ = json.NewEncoder(w).Encode([]map[string]any{{"version": "v24.12.0"}, {"version": "v22.23.3"}})
case "pythonmamager/GetCloudPython":
_ = json.NewEncoder(w).Encode([][]string{{"3.12.0", "0"}, {"3.11.4", "0"}})
case "pythonmamager/GetPythonV":
_ = json.NewEncoder(w).Encode([]string{"3.12.0"})
default:
t.Fatalf("unexpected plugin method %s/%s", r.FormValue("name"), r.FormValue("s"))
}
default:
t.Fatalf("unexpected plugin action %q", r.FormValue("action"))
}
case "/project/nodejs/get_nodejs_version/stype":
_ = json.NewEncoder(w).Encode([]string{"v22.23.3"})
case "/project/python/list_py_version/stype":
_ = json.NewEncoder(w).Encode(map[string]any{"status": true, "sdk": map[string]any{"streamline": []map[string]any{{"version": "3.15.1"}, {"version": "3.14.9"}, {"version": "3.13.17"}, {"version": "3.12.15"}, {"version": "3.11.17"}, {"version": "3.10.22"}, {"version": "3.9.25"}}}})
case "/project/go/list_go_sdk/stype":
_ = json.NewEncoder(w).Encode(map[string]any{"status": true, "installed": []string{"go1.25.4"}, "sdk": map[string]any{"streamline": []map[string]any{{"version": "go1.26.1", "installed": false}, {"version": "go1.25.4", "installed": true}}}})
case "/mod/java/project/get_system_info/stype":
_ = json.NewEncoder(w).Encode(map[string]any{"status": true, "data": map[string]any{"jdk_info": []map[string]any{{"name": "jdk-25.0.1", "path": "", "operation": 0}, {"name": "jdk-21.0.2", "path": "/www/server/java/jdk-21.0.2", "operation": 1}}}})
default:
http.NotFound(w, r)
}
}))
defer server.Close()
client := NewClient(server.URL, "test-key", false, 5*time.Second)
items, err := client.RuntimeEnvironments(context.Background())
if err != nil {
t.Fatal(err)
}
if len(items) != 5 || items[1].Recommended != "v24.12.0" || !reflect.DeepEqual(items[2].Installed, []string{"3.12.0"}) || !reflect.DeepEqual(items[2].Available, []string{"3.15.1", "3.14.9", "3.13.17", "3.12.15", "3.11.17", "3.10.22"}) || items[2].Recommended != "3.15.1" || items[3].Recommended != "go1.26.1" || items[4].Recommended != "jdk-25.0.1" {
t.Fatalf("unexpected runtime inventory: %#v", items)
}
}
func TestInstallPythonComponentUsesOfficialFreePlugin(t *testing.T) {
installed := false
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
if r.URL.Path != "/plugin" {
http.NotFound(w, r)
return
}
switch r.FormValue("action") {
case "get_soft_find":
_ = json.NewEncoder(w).Encode(map[string]any{
"name": "pythonmamager", "price": 0, "panel_free": 1, "setup": false,
"versions": []map[string]any{{"m_version": "2", "version": "5.1", "beta": 0}},
})
case "install_plugin":
if r.FormValue("sName") != "pythonmamager" || r.FormValue("version") != "2" || r.FormValue("min_version") != "5.1" || r.FormValue("type") != "0" {
t.Fatalf("unexpected Python component install form: %#v", r.Form)
}
_ = json.NewEncoder(w).Encode(map[string]any{"name": "pythonmamager", "tmp_path": "/www/server/panel/temp/pythonmamager", "install_opt": "i"})
case "input_package":
if r.FormValue("plugin_name") != "pythonmamager" || r.FormValue("tmp_path") != "/www/server/panel/temp/pythonmamager" || r.FormValue("install_opt") != "i" {
t.Fatalf("unexpected Python component package form: %#v", r.Form)
}
installed = true
_ = json.NewEncoder(w).Encode(map[string]any{"status": true})
default:
t.Fatalf("unexpected plugin action %q", r.FormValue("action"))
}
}))
defer server.Close()
client := NewClient(server.URL, "test-key", false, 5*time.Second)
if err := client.InstallRuntimeComponent(context.Background(), "Python"); err != nil {
t.Fatal(err)
}
if !installed {
t.Fatal("Python component installation was not completed")
}
}
func TestDirectPanelClientCannotInstallPythonSource(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
if r.URL.Path == "/site" {
_ = json.NewEncoder(w).Encode([]map[string]any{})
return
}
if r.URL.Path == "/plugin" && r.FormValue("action") == "get_soft_find" {
_ = json.NewEncoder(w).Encode(map[string]any{"name": r.FormValue("sName"), "price": 0, "panel_free": 1, "setup": true, "version": "2.5.1", "versions": []map[string]any{{"m_version": "2", "version": "5.1", "beta": 0}}})
return
}
if r.URL.Path == "/plugin" && r.FormValue("name") == "pythonmamager" {
switch r.FormValue("s") {
case "GetPythonV":
_ = json.NewEncoder(w).Encode([]string{})
default:
t.Fatalf("unexpected Python manager method %q", r.FormValue("s"))
}
return
}
switch r.URL.Path {
case "/project/nodejs/get_nodejs_version/stype":
_ = json.NewEncoder(w).Encode([]string{})
case "/project/python/list_py_version/stype":
_ = json.NewEncoder(w).Encode(map[string]any{"status": true, "sdk": map[string]any{"streamline": []map[string]any{{"version": "3.12.15"}}}})
case "/project/go/list_go_sdk/stype":
_ = json.NewEncoder(w).Encode(map[string]any{"status": true, "sdk": map[string]any{}})
case "/mod/java/project/get_system_info/stype":
_ = json.NewEncoder(w).Encode(map[string]any{"status": true, "data": map[string]any{"jdk_info": []any{}}})
default:
http.NotFound(w, r)
}
}))
defer server.Close()
client := NewClient(server.URL, "test-key", false, 5*time.Second)
err := client.InstallRuntimeEnvironment(context.Background(), "Python", "3.12.15")
if err == nil || !strings.Contains(err.Error(), "isolation installer") {
t.Fatalf("direct Python install error = %v", err)
}
}
func TestInstallNodeComponentUsesLatestStablePluginRelease(t *testing.T) {
prepared := false
installed := false
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
if r.URL.Path != "/plugin" {
http.NotFound(w, r)
return
}
switch r.FormValue("action") {
case "get_soft_find":
_ = json.NewEncoder(w).Encode(map[string]any{
"name": "nodejs", "price": 0, "panel_free": 1, "setup": false,
"versions": []map[string]any{{"m_version": "2", "version": "8", "beta": 0}, {"m_version": "3", "version": "9", "beta": 1}},
})
case "install_plugin":
if r.FormValue("sName") != "nodejs" || r.FormValue("version") != "2" || r.FormValue("min_version") != "8" || r.FormValue("type") != "0" {
t.Fatalf("unexpected Node.js component install form: %#v", r.Form)
}
prepared = true
_ = json.NewEncoder(w).Encode(map[string]any{"name": "nodejs", "tmp_path": "/www/server/panel/temp/nodejs", "install_opt": "i"})
case "input_package":
if !prepared || r.FormValue("plugin_name") != "nodejs" || r.FormValue("tmp_path") != "/www/server/panel/temp/nodejs" || r.FormValue("install_opt") != "i" {
t.Fatalf("unexpected Node.js component package form: %#v", r.Form)
}
installed = true
_ = json.NewEncoder(w).Encode(map[string]any{"status": true, "msg": "安装成功"})
default:
t.Fatalf("unexpected plugin action %q", r.FormValue("action"))
}
}))
defer server.Close()
client := NewClient(server.URL, "test-key", false, 5*time.Second)
if err := client.InstallRuntimeComponent(context.Background(), "Node.js"); err != nil {
t.Fatal(err)
}
if !installed {
t.Fatal("Node.js component installation was not submitted")
}
}
func TestRecommendedRuntimeVersionDoesNotSuggestAnOlderRelease(t *testing.T) {
available := []string{"v26.12.1", "v26.12.0", "v24.22.1"}
if got := recommendedVersion(available, []string{"v26.12.1"}); got != "" {
t.Fatalf("recommendedVersion() = %q; want no downgrade recommendation", got)
}
if got := recommendedVersion(available, []string{"v24.22.1"}); got != "v26.12.1" {
t.Fatalf("recommendedVersion() = %q; want latest release", got)
}
}
func TestUpdateNodeComponentUsesTwoPhaseUpgrade(t *testing.T) {
upgraded := false
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
if r.URL.Path != "/plugin" {
http.NotFound(w, r)
return
}
switch r.FormValue("action") {
case "get_soft_find":
_ = json.NewEncoder(w).Encode(map[string]any{
"name": "nodejs", "price": 0, "panel_free": 1, "setup": true, "version": "2.7",
"versions": []map[string]any{{"m_version": "2", "version": "8", "beta": 0}},
})
case "upgrade_plugin":
if r.FormValue("plugin_name") != "nodejs" || r.FormValue("version") != "2" || r.FormValue("min_version") != "8" {
t.Fatalf("unexpected Node.js component update form: %#v", r.Form)
}
_ = json.NewEncoder(w).Encode(map[string]any{"name": "nodejs", "tmp_path": "/www/server/panel/temp/nodejs", "install_opt": "u"})
case "input_package":
if r.FormValue("install_opt") != "u" {
t.Fatalf("unexpected Node.js component update package form: %#v", r.Form)
}
upgraded = true
_ = json.NewEncoder(w).Encode(map[string]any{"status": true})
default:
t.Fatalf("unexpected plugin action %q", r.FormValue("action"))
}
}))
defer server.Close()
client := NewClient(server.URL, "test-key", false, 5*time.Second)
if err := client.InstallRuntimeComponent(context.Background(), "Node.js"); err != nil {
t.Fatal(err)
}
if !upgraded {
t.Fatal("Node.js component update was not completed")
}
}
func TestCreateResourcesResolveIDsWhenAaPanelOmitsThem(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
switch r.URL.Path {
case "/ftp", "/database":
_ = json.NewEncoder(w).Encode(map[string]any{"status": true})
case "/data":
switch r.FormValue("table") {
case "ftps":
_ = json.NewEncoder(w).Encode(map[string]any{"data": []map[string]any{{"id": "17", "name": "sv0123456789"}}})
case "databases":
_ = json.NewEncoder(w).Encode(map[string]any{"data": []map[string]any{{"id": 29, "name": "sv0123456789", "username": "sv0123456789"}}})
default:
http.Error(w, "unexpected table", http.StatusBadRequest)
}
default:
http.NotFound(w, r)
}
}))
defer server.Close()
client := NewClient(server.URL, "test-key", false, 5*time.Second)
ftpID, err := client.CreateFTP(context.Background(), "sv0123456789", "Aa0123456789Bb012345", "/managed", 1<<30)
if err != nil || ftpID != 17 {
t.Fatalf("CreateFTP() = %d, %v; want 17", ftpID, err)
}
databaseID, err := client.CreateDatabase(context.Background(), "sv0123456789", "sv0123456789", "Cc0123456789Dd012345", 3)
if err != nil || databaseID != 29 {
t.Fatalf("CreateDatabase() = %d, %v; want 29", databaseID, err)
}
}
func TestMutationParametersMatchAaPanelAPI(t *testing.T) {
requests := make(chan *http.Request, 5)
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
t.Fatal(err)
}
clone := r.Clone(r.Context())
clone.Form = cloneValues(r.Form)
requests <- clone
_ = json.NewEncoder(w).Encode(map[string]any{"status": true})
}))
defer server.Close()
client := NewClient(server.URL, "test-key", false, 5*time.Second)
if err := client.DeleteDatabase(context.Background(), 42, "sv_acme_blog"); err != nil {
t.Fatal(err)
}
deleted := <-requests
if deleted.Form.Get("sid") != "0" || deleted.Form.Get("db_user") != "sv_acme_blog" {
t.Fatalf("DeleteDatabase form = %#v", deleted.Form)
}
if err := client.ConfigureProxy(context.Background(), 7, "blog.hosts.example.com", 20020); err != nil {
t.Fatal(err)
}
proxy := <-requests
if proxy.Form.Get("cachetime") == "" || proxy.Form.Get("todomain") != "blog.hosts.example.com" {
t.Fatalf("ConfigureProxy form = %#v", proxy.Form)
}
if err := client.SetSiteRunPath(context.Background(), 7, "/apps/web/public"); err != nil {
t.Fatal(err)
}
runPath := <-requests
if runPath.Form.Get("action") != "SetSiteRunPath" || runPath.Form.Get("id") != "7" || runPath.Form.Get("runPath") != "/apps/web/public" {
t.Fatalf("SetSiteRunPath form = %#v", runPath.Form)
}
if err := client.InstallCertificate(context.Background(), 7, "blog.hosts.example.com", "private-key-pem", "certificate-chain-pem"); err != nil {
t.Fatal(err)
}
certificate := <-requests
if certificate.URL.Path != "/site" || certificate.Form.Get("action") != "SetSSL" || certificate.Form.Get("siteName") != "blog.hosts.example.com" || certificate.Form.Get("key") != "private-key-pem" || certificate.Form.Get("csr") != "certificate-chain-pem" {
t.Fatalf("InstallCertificate form = %#v", certificate.Form)
}
if err := client.DisableCertificate(context.Background(), 7, "blog.hosts.example.com"); err != nil {
t.Fatal(err)
}
disabled := <-requests
if disabled.URL.Path != "/site" || disabled.Form.Get("action") != "CloseSSLConf" || disabled.Form.Get("siteName") != "blog.hosts.example.com" || disabled.Form.Get("updateOf") != "1" {
t.Fatalf("DisableCertificate form = %#v", disabled.Form)
}
}
func TestRequestCertificateDeploysValidACMEOrder(t *testing.T) {
requests := make(chan url.Values, 3)
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
t.Fatal(err)
}
requests <- cloneValues(r.Form)
w.Header().Set("Content-Type", "application/json")
switch r.FormValue("action") {
case "apply_cert_api":
_ = json.NewEncoder(w).Encode(map[string]any{"status": "valid", "index": "order-123"})
case "SetCertToSite":
_ = json.NewEncoder(w).Encode(map[string]any{"status": true, "msg": "SSL enabled"})
default:
t.Fatalf("unexpected ACME action %q", r.FormValue("action"))
}
}))
defer server.Close()
client := NewClient(server.URL, "test-key", false, 5*time.Second)
if err := client.RequestCertificate(context.Background(), 7, "/www/example", []string{"blog.hosts.example.com", "www.example.com"}); err != nil {
t.Fatal(err)
}
created := <-requests
if created.Get("action") != "apply_cert_api" || created.Get("id") != "7" || created.Get("auth_type") != "http" || created.Get("auth_to") != "7" || created.Get("domains") != `["blog.hosts.example.com","www.example.com"]` {
t.Fatalf("ACME create form = %#v", created)
}
deployed := <-requests
if deployed.Get("action") != "SetCertToSite" || deployed.Get("index") != "order-123" || deployed.Get("siteName") != "blog.hosts.example.com" {
t.Fatalf("ACME deployment form = %#v", deployed)
}
}
func TestRequestCertificateRejectsMissingOrderIndex(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
_ = json.NewEncoder(w).Encode(map[string]any{"status": "pending"})
}))
defer server.Close()
client := NewClient(server.URL, "test-key", false, 5*time.Second)
err := client.RequestCertificate(context.Background(), 7, "/www/example", []string{"blog.hosts.example.com"})
if err == nil || !strings.Contains(err.Error(), "order index") {
t.Fatalf("RequestCertificate() error = %v", err)
}
}
func TestConfigureJavaResolvesServerOwnedJDKPath(t *testing.T) {
var createData map[string]any
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
switch r.URL.Path {
case "/mod/java/project/get_system_info/stype":
_ = json.NewEncoder(w).Encode(map[string]any{"status": true, "data": map[string]any{"jdk_info": []map[string]any{{"name": "jdk-21.0.2", "path": "/www/server/java/jdk-21/bin/java", "operation": 1}}}})
case "/mod/java/project/create_spring_boot_project/stype":
if err := json.Unmarshal([]byte(r.FormValue("data")), &createData); err != nil {
t.Fatal(err)
}
_ = json.NewEncoder(w).Encode(map[string]any{"status": true})
case "/mod/java/project/project_list/stype":
_ = json.NewEncoder(w).Encode(map[string]any{"data": []map[string]any{{"name": "sv0123456789", "pid": "1234", "listen": []int{20020}}}})
default:
http.NotFound(w, r)
}
}))
defer server.Close()
client := NewClient(server.URL, "test-key", false, 5*time.Second)
err := client.ConfigureRuntime(context.Background(), RuntimeSpec{ProjectName: "sv0123456789", Runtime: "Java", Version: "jdk-21.0.2", Path: "/www/wwwroot/seavHost/vHost/sv0123456789", RunPath: "/public", EntryFile: "app.jar", Domain: "sv0123456789.hosts.example.com", RunUser: "www", Port: 20020})
if err != nil {
t.Fatal(err)
}
if createData["project_jdk"] != "/www/server/java/jdk-21/bin/java" {
t.Fatalf("project_jdk = %#v", createData["project_jdk"])
}
if createData["project_jar"] != "/www/wwwroot/seavHost/vHost/sv0123456789/public/app.jar" || createData["bind_extranet"] != float64(0) {
t.Fatalf("Java project data = %#v", createData)
}
if err := client.ConfigureRuntime(context.Background(), RuntimeSpec{ProjectName: "sv0123456789", Runtime: "Java", Version: "jdk-21.0.2", Path: "/www/wwwroot/seavHost/vHost/sv0123456789", RunPath: "/public", EntryFile: "app.jar", Domain: "sv0123456789.hosts.example.com", RunUser: "www", Port: 20020, Runner: true}); err != nil {
t.Fatal(err)
}
if createData["project_cmd"] != "/usr/local/libexec/sea-vhost-run sv0123456789 --java /www/server/java/jdk-21/bin/java /www/wwwroot/seavHost/vHost/sv0123456789/public/app.jar" {
t.Fatal("Java launcher must carry verified native-module paths")
}
}
func TestConfigureLanguageRuntimeContracts(t *testing.T) {
created := make(map[string]url.Values)
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
t.Fatal(err)
}
w.Header().Set("Content-Type", "application/json")
switch r.URL.Path {
case "/project/nodejs/get_nodejs_version/stype":
_ = json.NewEncoder(w).Encode([]string{"v24.21.0"})
case "/plugin":
if r.FormValue("name") == "pythonmamager" && r.FormValue("s") == "GetPythonV" {
_ = json.NewEncoder(w).Encode([]string{"3.12.0"})
return
}
http.NotFound(w, r)
case "/project/go/list_go_sdk/stype":
_ = json.NewEncoder(w).Encode(map[string]any{"status": true, "installed": []string{"go1.27.1"}})
case "/mod/python/environment/add_environment/stype":
if r.FormValue("add_type") != "system" || r.FormValue("path") != "/www/server/python_manager/versions/3.12.0/bin/python3.12" {
t.Fatalf("only root-managed SDKs may be detected: %#v", r.Form)
}
_ = json.NewEncoder(w).Encode(map[string]any{"status": true})
case "/project/nodejs/create_project/stype", "/project/python/CreateProject", "/project/go/create_project/stype":
created[r.URL.Path] = cloneValues(r.Form)
_ = json.NewEncoder(w).Encode(map[string]any{"status": true})
case "/project/nodejs/get_project_list/stype", "/project/python/GetProjectList/stype", "/project/go/get_project_list/stype":
_ = json.NewEncoder(w).Encode(map[string]any{"data": []map[string]any{{"name": r.FormValue("search"), "run": true, "listen_ok": true}}})
default:
http.NotFound(w, r)
}
}))
defer server.Close()
client := NewClient(server.URL, "test-key", false, 5*time.Second)
base := RuntimeSpec{ProjectName: "sv0123456789", Path: "/www/wwwroot/seavHost/vHost/sv0123456789", RunPath: "/apps/api", Domain: "sv0123456789.hosts.example.com", RunUser: "www", Port: 20020, ProcessLimit: 4}
for _, test := range []struct {
runtime, version, entry string
}{
{"Node.js", "v24.21.0", "package.json"},
{"Python", "3.12.0", "app.py"},
{"Go", "go1.27.1", "app"},
} {
spec := base
spec.Runtime, spec.Version, spec.EntryFile = test.runtime, test.version, test.entry
if err := client.ConfigureRuntime(context.Background(), spec); err != nil {
t.Fatalf("ConfigureRuntime(%s): %v", test.runtime, err)
}
}
if form := created["/project/nodejs/create_project/stype"]; form.Get("project_cwd") != base.Path+"/apps/api" || form.Get("project_script") != "env PORT=20020 npm run start" || form.Get("bind_extranet") != "0" {
t.Fatalf("Node.js create form = %#v", form)
}
if form := created["/project/python/CreateProject"]; !strings.Contains(form.Get("project_cmd"), "/.sea-runtime/python/sv0123456789-3.12.0/bin/python3 "+base.Path+"/apps/api/app.py") || form.Get("venv_path") != base.Path+"/apps/api/.sea-runtime/python/sv0123456789-3.12.0" || form.Get("python_bin") != "/www/server/python_manager/versions/3.12.0/bin/python3.12" || form.Get("user") != "www" || form.Get("stype") != "command" {
t.Fatalf("Python create form = %#v", form)
}
if form := created["/project/go/create_project/stype"]; form.Get("project_exe") != base.Path+"/apps/api/app" || form.Get("project_cmd") != base.Path+"/apps/api/app" {
t.Fatalf("Go create form = %#v", form)
}
}
func TestPythonEnvironmentRegistrationRejectsTenantInterpreters(t *testing.T) {
const endpoint = "/mod/python/environment/add_environment/stype"
for _, input := range []url.Values{
{"add_type": {"venv"}, "path": {"/www/server/python_manager/versions/3.12.15/bin/python3.12"}},
{"add_type": {"system"}, "path": {"/www/wwwroot/seavHost/vHost/sv0123456789/.sea-runtime/bin/python3.12"}},
{"add_type": {"system"}, "path": {"/www/server/python_manager/versions/../../../wwwroot/app/bin/python3.12"}},
} {
if err := validateFreePanelRequest(http.MethodPost, endpoint, input); err == nil {
t.Fatalf("untrusted interpreter registration accepted: %#v", input)
}
}
}
func TestConfigureRuntimeDoesNotReportStoppedProcessAsSuccess(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
switch r.URL.Path {
case "/project/go/list_go_sdk/stype":
_ = json.NewEncoder(w).Encode(map[string]any{"status": true, "installed": []string{"go1.27.1"}})
case "/project/go/create_project/stype", "/project/go/remove_project/stype":
_ = json.NewEncoder(w).Encode(map[string]any{"status": true})
case "/project/go/get_project_list/stype":
_ = json.NewEncoder(w).Encode(map[string]any{"data": []map[string]any{{"name": "sv0123456789", "run": false}}})
default:
http.NotFound(w, r)
}
}))
defer server.Close()
client := NewClient(server.URL, "test-key", false, time.Second)
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond)
defer cancel()
err := client.ConfigureRuntime(ctx, RuntimeSpec{ProjectName: "sv0123456789", Runtime: "Go", Version: "go1.27.1", Path: "/www/wwwroot/seavHost/vHost/sv0123456789", RunPath: "/", EntryFile: "app", RunUser: "www", Port: 20020, ProcessLimit: 2})
if err == nil {
t.Fatal("stopped Go process was reported as successfully deployed")
}
}
func TestConfigureRuntimeRemovesExactPartialProjectAfterCreateError(t *testing.T) {
removed := false
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
switch r.URL.Path {
case "/project/nodejs/get_nodejs_version/stype":
_ = json.NewEncoder(w).Encode([]string{"v24.21.0"})
case "/project/nodejs/create_project/stype":
_ = json.NewEncoder(w).Encode(map[string]any{"status": false, "msg": "PID file was not created"})
case "/project/nodejs/get_project_list/stype":
_ = r.ParseForm()
_ = json.NewEncoder(w).Encode(map[string]any{"data": []map[string]any{{
"name": r.FormValue("search"), "path": "/www/wwwroot/seavHost/vHost/sv0123456789/public", "port": 20020,
}}})
case "/project/nodejs/remove_project/stype":
removed = true
_ = json.NewEncoder(w).Encode(map[string]any{"status": true})
default:
http.NotFound(w, r)
}
}))
defer server.Close()
client := NewClient(server.URL, "test-key", false, time.Second)
err := client.ConfigureRuntime(context.Background(), RuntimeSpec{
ProjectName: "sv0123456789", Runtime: "Node.js", Version: "v24.21.0",
Path: "/www/wwwroot/seavHost/vHost/sv0123456789", RunPath: "/public",
EntryFile: "package.json", RunUser: "sv0123456789", Port: 20020,
})
if err == nil || !strings.Contains(err.Error(), "PID file") {
t.Fatalf("create error = %v", err)
}
if !removed {
t.Fatal("exact partial Node.js project was not removed")
}
}
func TestConfigureRuntimeRefusesToRemovePartialProjectAtUnexpectedPath(t *testing.T) {
removed := false
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
switch r.URL.Path {
case "/project/nodejs/get_nodejs_version/stype":
_ = json.NewEncoder(w).Encode([]string{"v24.21.0"})
case "/project/nodejs/create_project/stype":
_ = json.NewEncoder(w).Encode(map[string]any{"status": false, "msg": "create failed"})
case "/project/nodejs/get_project_list/stype":
_ = r.ParseForm()
_ = json.NewEncoder(w).Encode(map[string]any{"data": []map[string]any{{
"name": r.FormValue("search"), "path": "/www/wwwroot/unmanaged", "port": 20020,
}}})
case "/project/nodejs/remove_project/stype":
removed = true
_ = json.NewEncoder(w).Encode(map[string]any{"status": true})
default:
http.NotFound(w, r)
}
}))
defer server.Close()
client := NewClient(server.URL, "test-key", false, time.Second)
err := client.ConfigureRuntime(context.Background(), RuntimeSpec{
ProjectName: "sv0123456789", Runtime: "Node.js", Version: "v24.21.0",
Path: "/www/wwwroot/seavHost/vHost/sv0123456789", RunPath: "/public",
EntryFile: "package.json", RunUser: "sv0123456789", Port: 20020,
})
if err == nil || !strings.Contains(err.Error(), "untrusted path") {
t.Fatalf("unsafe cleanup error = %v", err)
}
if removed {
t.Fatal("unexpected-path project was removed")
}
}
func TestWaitRuntimePortStopped(t *testing.T) {
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
port := listener.Addr().(*net.TCPAddr).Port
spec := RuntimeSpec{Runtime: "Python", Port: port}
if err = waitRuntimePortStopped(context.Background(), spec, 4); err == nil || !strings.Contains(err.Error(), "仍在监听") {
t.Fatalf("listening port error = %v", err)
}
if err = listener.Close(); err != nil {
t.Fatal(err)
}
if err = waitRuntimePortStopped(context.Background(), spec, 4); err != nil {
t.Fatalf("closed port error = %v", err)
}
}
func TestWaitRuntimePortStoppedRejectsTransientClosure(t *testing.T) {
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
address := listener.Addr().String()
port := listener.Addr().(*net.TCPAddr).Port
if err = listener.Close(); err != nil {
t.Fatal(err)
}
result := make(chan error, 1)
go func() {
result <- waitRuntimePortStopped(context.Background(), RuntimeSpec{Runtime: "Python", Port: port}, 4)
}()
time.Sleep(100 * time.Millisecond)
active, err := net.Listen("tcp", address)
if err != nil {
t.Fatal("cannot reopen transient listener:", err)
}
defer active.Close()
if err = <-result; err == nil || !strings.Contains(err.Error(), "仍在监听") {
t.Fatalf("transient closure error = %v", err)
}
}