feat: import Sea vHost single-server testing release
This commit is contained in:
commit
248badd33e
441 files changed
+63221
No files matched your search
@@ -0,0 +1,285 @@
|
||||
package panel
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type BrokerCredentials struct {
|
||||
URL string `json:"url"`
|
||||
APIKey string `json:"apiKey"`
|
||||
TLSInsecure bool `json:"tlsInsecure"`
|
||||
}
|
||||
|
||||
type PanelInspection struct {
|
||||
Versions RuntimeCatalog `json:"versions"`
|
||||
Runtimes RuntimeCapabilities `json:"runtimes"`
|
||||
}
|
||||
|
||||
type BrokerClient struct {
|
||||
http *http.Client
|
||||
internalToken string
|
||||
}
|
||||
|
||||
func NewTransportClient(transport http.RoundTripper, timeout time.Duration) *BrokerClient {
|
||||
return &BrokerClient{http: &http.Client{Transport: transport, Timeout: timeout}}
|
||||
}
|
||||
|
||||
type brokerRequest struct {
|
||||
Operation string `json:"operation"`
|
||||
Site *SiteSpec `json:"site,omitempty"`
|
||||
Runtime *RuntimeSpec `json:"runtime,omitempty"`
|
||||
ID int64 `json:"id,omitempty"`
|
||||
SiteID int64 `json:"siteId,omitempty"`
|
||||
Name string `json:"name,omitempty"`
|
||||
Version string `json:"version,omitempty"`
|
||||
Username string `json:"username,omitempty"`
|
||||
Password string `json:"password,omitempty"`
|
||||
Path string `json:"path,omitempty"`
|
||||
Domain string `json:"domain,omitempty"`
|
||||
MaxBytes int64 `json:"maxBytes,omitempty"`
|
||||
Port int `json:"port,omitempty"`
|
||||
Domains []string `json:"domains,omitempty"`
|
||||
PrivateKey string `json:"privateKey,omitempty"`
|
||||
Certificate string `json:"certificate,omitempty"`
|
||||
Enabled bool `json:"enabled,omitempty"`
|
||||
Credentials *BrokerCredentials `json:"credentials,omitempty"`
|
||||
SourcePath string `json:"sourcePath,omitempty"`
|
||||
}
|
||||
|
||||
type brokerResponse struct {
|
||||
Runtime *RuntimeSpec `json:"runtime,omitempty"`
|
||||
Pending bool `json:"pending"`
|
||||
ID int64 `json:"id,omitempty"`
|
||||
Bytes uint64 `json:"bytes,omitempty"`
|
||||
Catalog RuntimeCatalog `json:"catalog,omitempty"`
|
||||
Capabilities RuntimeCapabilities `json:"capabilities,omitempty"`
|
||||
Environments []RuntimeEnvironment `json:"environments,omitempty"`
|
||||
Sites []ExistingSite `json:"sites,omitempty"`
|
||||
Message string `json:"message,omitempty"`
|
||||
}
|
||||
|
||||
func NewBrokerClient(socket string, timeout time.Duration, internalToken ...string) *BrokerClient {
|
||||
transport := &http.Transport{DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) {
|
||||
return (&net.Dialer{Timeout: 5 * time.Second}).DialContext(ctx, "unix", socket)
|
||||
}}
|
||||
token := ""
|
||||
if len(internalToken) > 0 {
|
||||
token = strings.TrimSpace(internalToken[0])
|
||||
}
|
||||
return &BrokerClient{http: &http.Client{Transport: transport, Timeout: timeout}, internalToken: token}
|
||||
}
|
||||
|
||||
func (c *BrokerClient) call(ctx context.Context, path, setupToken string, input any, output any) error {
|
||||
body, err := json.Marshal(input)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
request, err := http.NewRequestWithContext(ctx, http.MethodPost, "http://unix"+path, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
if c.internalToken != "" {
|
||||
request.Header.Set("Authorization", "Bearer "+c.internalToken)
|
||||
}
|
||||
if setupToken != "" {
|
||||
request.Header.Set("X-Setup-Token", setupToken)
|
||||
}
|
||||
response, err := c.http.Do(request)
|
||||
if err != nil {
|
||||
return fmt.Errorf("panel broker: %w", err)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
data, err := io.ReadAll(io.LimitReader(response.Body, 128<<10))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if response.StatusCode < 200 || response.StatusCode > 299 {
|
||||
var payload struct {
|
||||
Error struct {
|
||||
Message string `json:"message"`
|
||||
} `json:"error"`
|
||||
}
|
||||
if json.Unmarshal(data, &payload) == nil && strings.TrimSpace(payload.Error.Message) != "" {
|
||||
return errors.New(payload.Error.Message)
|
||||
}
|
||||
return fmt.Errorf("panel broker rejected request (%d)", response.StatusCode)
|
||||
}
|
||||
if output != nil && len(data) > 0 {
|
||||
return json.Unmarshal(data, output)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *BrokerClient) TestCredentials(ctx context.Context, credentials BrokerCredentials, setupToken string) error {
|
||||
_, err := c.InspectCredentials(ctx, credentials, setupToken)
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *BrokerClient) InspectCredentials(ctx context.Context, credentials BrokerCredentials, setupToken string) (PanelInspection, error) {
|
||||
var inspection PanelInspection
|
||||
err := c.call(ctx, "/v1/setup/test", setupToken, credentials, &inspection)
|
||||
return inspection, err
|
||||
}
|
||||
|
||||
func (c *BrokerClient) Configure(ctx context.Context, credentials BrokerCredentials, setupToken string) error {
|
||||
return c.call(ctx, "/v1/setup/configure", setupToken, credentials, nil)
|
||||
}
|
||||
|
||||
func (c *BrokerClient) operation(ctx context.Context, request brokerRequest) (brokerResponse, error) {
|
||||
var response brokerResponse
|
||||
err := c.call(ctx, "/v1/operations", "", request, &response)
|
||||
return response, err
|
||||
}
|
||||
|
||||
func (c *BrokerClient) Ping(ctx context.Context) error {
|
||||
_, err := c.operation(ctx, brokerRequest{Operation: "ping"})
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *BrokerClient) RuntimeCatalog(ctx context.Context) (RuntimeCatalog, error) {
|
||||
response, err := c.operation(ctx, brokerRequest{Operation: "runtime_catalog"})
|
||||
return response.Catalog, err
|
||||
}
|
||||
|
||||
func (c *BrokerClient) RuntimeCapabilities(ctx context.Context) (RuntimeCapabilities, error) {
|
||||
response, err := c.operation(ctx, brokerRequest{Operation: "runtime_capabilities"})
|
||||
return response.Capabilities, err
|
||||
}
|
||||
|
||||
func (c *BrokerClient) RuntimeEnvironments(ctx context.Context) ([]RuntimeEnvironment, error) {
|
||||
response, err := c.operation(ctx, brokerRequest{Operation: "runtime_environments"})
|
||||
return response.Environments, err
|
||||
}
|
||||
|
||||
func (c *BrokerClient) InstallRuntimeComponent(ctx context.Context, runtimeName string) error {
|
||||
_, err := c.operation(ctx, brokerRequest{Operation: "install_runtime_component", Name: runtimeName})
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *BrokerClient) InstallRuntimeEnvironment(ctx context.Context, runtimeName, version string) error {
|
||||
_, err := c.operation(ctx, brokerRequest{Operation: "install_runtime_environment", Name: runtimeName, Version: version})
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *BrokerClient) CreateSite(ctx context.Context, spec SiteSpec) (int64, error) {
|
||||
response, err := c.operation(ctx, brokerRequest{Operation: "create_site", Site: &spec})
|
||||
return response.ID, err
|
||||
}
|
||||
func (c *BrokerClient) ListUnmanagedSites(ctx context.Context) ([]ExistingSite, error) {
|
||||
response, err := c.operation(ctx, brokerRequest{Operation: "list_unmanaged_sites"})
|
||||
return response.Sites, err
|
||||
}
|
||||
func (c *BrokerClient) AdoptSite(ctx context.Context, id int64, sourcePath string, spec SiteSpec) error {
|
||||
_, err := c.operation(ctx, brokerRequest{Operation: "adopt_site", ID: id, SourcePath: sourcePath, Site: &spec})
|
||||
return err
|
||||
}
|
||||
func (c *BrokerClient) RollbackAdoption(ctx context.Context, id int64, name, sourcePath string) error {
|
||||
_, err := c.operation(ctx, brokerRequest{Operation: "rollback_adoption", ID: id, Name: name, SourcePath: sourcePath})
|
||||
return err
|
||||
}
|
||||
func (c *BrokerClient) SetSitePath(context.Context, int64, string) error {
|
||||
return errors.New("site path changes are only available through managed adoption")
|
||||
}
|
||||
|
||||
func (c *BrokerClient) DeleteSite(ctx context.Context, id int64, name string) error {
|
||||
_, err := c.operation(ctx, brokerRequest{Operation: "delete_site", ID: id, Name: name})
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *BrokerClient) AddDomain(ctx context.Context, siteID int64, siteName, domain string) error {
|
||||
_, err := c.operation(ctx, brokerRequest{Operation: "add_domain", SiteID: siteID, Name: siteName, Domain: domain})
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *BrokerClient) DeleteDomain(ctx context.Context, siteID int64, siteName, domain string) error {
|
||||
_, err := c.operation(ctx, brokerRequest{Operation: "delete_domain", SiteID: siteID, Name: siteName, Domain: domain})
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *BrokerClient) CreateFTP(ctx context.Context, username, password, path string, maxBytes int64) (int64, error) {
|
||||
response, err := c.operation(ctx, brokerRequest{Operation: "create_ftp", Username: username, Password: password, Path: path, MaxBytes: maxBytes})
|
||||
return response.ID, err
|
||||
}
|
||||
|
||||
func (c *BrokerClient) DeleteFTP(ctx context.Context, id int64, username string) error {
|
||||
_, err := c.operation(ctx, brokerRequest{Operation: "delete_ftp", ID: id, Username: username})
|
||||
return err
|
||||
}
|
||||
func (c *BrokerClient) SetFTPState(ctx context.Context, id int64, username string, enabled bool) error {
|
||||
_, err := c.operation(ctx, brokerRequest{Operation: "set_ftp_state", ID: id, Username: username, Enabled: enabled})
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *BrokerClient) CreateDatabase(ctx context.Context, name, username, password string, siteID int64) (int64, error) {
|
||||
response, err := c.operation(ctx, brokerRequest{Operation: "create_database", Name: name, Username: username, Password: password, SiteID: siteID})
|
||||
return response.ID, err
|
||||
}
|
||||
|
||||
func (c *BrokerClient) DeleteDatabase(ctx context.Context, id int64, name string) error {
|
||||
_, err := c.operation(ctx, brokerRequest{Operation: "delete_database", ID: id, Name: name})
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *BrokerClient) DatabaseSize(ctx context.Context, id int64, name string) (uint64, error) {
|
||||
response, err := c.operation(ctx, brokerRequest{Operation: "database_size", ID: id, Name: name})
|
||||
return response.Bytes, err
|
||||
}
|
||||
|
||||
func (c *BrokerClient) ConfigureRuntime(ctx context.Context, spec RuntimeSpec) error {
|
||||
_, err := c.operation(ctx, brokerRequest{Operation: "configure_runtime", Runtime: &spec})
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *BrokerClient) RemoveRuntime(ctx context.Context, spec RuntimeSpec) error {
|
||||
_, err := c.operation(ctx, brokerRequest{Operation: "remove_runtime", Runtime: &spec})
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *BrokerClient) SetRuntimeState(ctx context.Context, spec RuntimeSpec, enabled bool) error {
|
||||
_, err := c.operation(ctx, brokerRequest{Operation: "set_runtime_state", Runtime: &spec, Enabled: enabled})
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *BrokerClient) ConfigureProxy(ctx context.Context, siteID int64, domain string, port int) error {
|
||||
_, err := c.operation(ctx, brokerRequest{Operation: "configure_proxy", SiteID: siteID, Domain: domain, Port: port})
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *BrokerClient) RequestCertificate(ctx context.Context, siteID int64, path string, domains []string) error {
|
||||
_, err := c.operation(ctx, brokerRequest{Operation: "request_certificate", SiteID: siteID, Path: path, Domains: domains})
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *BrokerClient) InstallCertificate(ctx context.Context, siteID int64, siteName, privateKey, certificate string) error {
|
||||
_, err := c.operation(ctx, brokerRequest{Operation: "install_certificate", SiteID: siteID, Name: siteName, PrivateKey: privateKey, Certificate: certificate})
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *BrokerClient) DisableCertificate(ctx context.Context, siteID int64, siteName string) error {
|
||||
_, err := c.operation(ctx, brokerRequest{Operation: "disable_certificate", SiteID: siteID, Name: siteName})
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *BrokerClient) SetSiteState(ctx context.Context, siteID int64, name string, enabled bool) error {
|
||||
_, err := c.operation(ctx, brokerRequest{Operation: "set_site_state", SiteID: siteID, Name: name, Enabled: enabled})
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *BrokerClient) SetSiteRunPath(ctx context.Context, siteID int64, runPath string) error {
|
||||
_, err := c.operation(ctx, brokerRequest{Operation: "set_site_run_path", SiteID: siteID, Path: runPath})
|
||||
return err
|
||||
}
|
||||
func (c *BrokerClient) MigrateRuntimeIdentity(ctx context.Context, siteID int64, runUser string, enabled bool) error {
|
||||
_, err := c.operation(ctx, brokerRequest{Operation: "migrate_runtime_identity", SiteID: siteID, Username: runUser, Enabled: enabled})
|
||||
return err
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,237 @@
|
||||
package panel
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type trackingPanel struct {
|
||||
Interface
|
||||
deletedSites int
|
||||
installedCertificates int
|
||||
disabledCertificates int
|
||||
clearedOrders []string
|
||||
}
|
||||
|
||||
func (p *trackingPanel) DeleteSite(ctx context.Context, id int64, name string) error {
|
||||
p.deletedSites++
|
||||
return p.Interface.DeleteSite(ctx, id, name)
|
||||
}
|
||||
|
||||
func (p *trackingPanel) InstallCertificate(ctx context.Context, id int64, name, privateKey, certificate string) error {
|
||||
p.installedCertificates++
|
||||
return p.Interface.InstallCertificate(ctx, id, name, privateKey, certificate)
|
||||
}
|
||||
|
||||
func (p *trackingPanel) DisableCertificate(ctx context.Context, id int64, name string) error {
|
||||
p.disabledCertificates++
|
||||
return p.Interface.DisableCertificate(ctx, id, name)
|
||||
}
|
||||
|
||||
func (p *trackingPanel) IssueManagedCertificate(ctx context.Context, id int64, path string, domains []string) (string, error) {
|
||||
return "owned-order", p.Interface.RequestCertificate(ctx, id, path, domains)
|
||||
}
|
||||
func (p *trackingPanel) ClearManagedCertificateOrder(_ context.Context, index string) error {
|
||||
p.clearedOrders = append(p.clearedOrders, index)
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestBrokerConfigAndManagedResourceBoundary(t *testing.T) {
|
||||
stateDir := filepath.Join(t.TempDir(), "broker")
|
||||
tenantRoot := filepath.Join(t.TempDir(), "tenants")
|
||||
token := strings.Repeat("t", 32)
|
||||
direct := &trackingPanel{Interface: NewMock()}
|
||||
server, err := newBrokerServer(stateDir, tenantRoot, token, func(BrokerCredentials) Interface { return direct })
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
credentials := BrokerCredentials{URL: "https://127.0.0.1:8888", APIKey: strings.Repeat("k", 32), TLSInsecure: true}
|
||||
body, _ := json.Marshal(credentials)
|
||||
request := httptest.NewRequest(http.MethodPost, "/v1/setup/configure", strings.NewReader(string(body)))
|
||||
request.Header.Set("X-Setup-Token", token)
|
||||
response := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(response, request)
|
||||
if response.Code != http.StatusCreated {
|
||||
t.Fatalf("configure status = %d, body = %s", response.Code, response.Body.String())
|
||||
}
|
||||
info, err := os.Stat(filepath.Join(stateDir, "credentials.json"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if runtime.GOOS != "windows" && info.Mode().Perm() != 0600 {
|
||||
t.Fatalf("credential mode = %o, want 600", info.Mode().Perm())
|
||||
}
|
||||
catalogResponse, err := server.execute(context.Background(), brokerRequest{Operation: "runtime_catalog"})
|
||||
if err != nil || len(catalogResponse.Catalog["PHP"]) == 0 {
|
||||
t.Fatalf("runtime catalog unavailable through broker: catalog=%v err=%v", catalogResponse.Catalog, err)
|
||||
}
|
||||
if _, err = server.execute(context.Background(), brokerRequest{Operation: "install_runtime_component", Name: "Python"}); err != nil {
|
||||
t.Fatalf("broker rejected the official Python component: %v", err)
|
||||
}
|
||||
if _, err = server.execute(context.Background(), brokerRequest{Operation: "install_runtime_component", Name: "Go"}); err == nil {
|
||||
t.Fatal("broker accepted a runtime without an installable manager component")
|
||||
}
|
||||
|
||||
hostName := "sv0123456789"
|
||||
sitePath := filepath.Join(tenantRoot, hostName)
|
||||
if err := os.MkdirAll(sitePath, 0750); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = server.validateSite(SiteSpec{Name: hostName, Domain: hostName + ".hosts.example.com", Path: sitePath, Runtime: "Docker", Version: "Compose-v2", RunUser: hostName, Port: 20020, ProcessLimit: 10}); err == nil {
|
||||
t.Fatal("broker accepted the removed Docker runtime")
|
||||
}
|
||||
if err = server.validateSite(SiteSpec{Name: hostName, Domain: hostName + ".hosts.example.com", Path: sitePath, RunPath: "/../etc", Runtime: "PHP", Version: "8.3", RunUser: hostName, Port: 20020, ProcessLimit: 10}); err == nil {
|
||||
t.Fatal("broker accepted an escaping run path")
|
||||
}
|
||||
created, err := server.execute(context.Background(), brokerRequest{Operation: "create_site", Site: &SiteSpec{Name: hostName, Domain: hostName + ".hosts.example.com", Path: sitePath, RunPath: "/public", Runtime: "PHP", Version: "8.3", RunUser: hostName, Port: 20020, ProcessLimit: 10}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if created.ID <= 0 {
|
||||
t.Fatal("broker did not return a managed site id")
|
||||
}
|
||||
primary := hostName + ".hosts.example.com"
|
||||
if _, err = server.execute(context.Background(), brokerRequest{Operation: "delete_domain", SiteID: created.ID, Name: primary, Domain: primary}); !errors.Is(err, errOutsideManaged) {
|
||||
t.Fatal("primary domain removal allowed")
|
||||
}
|
||||
if _, err = server.execute(context.Background(), brokerRequest{Operation: "add_domain", SiteID: created.ID, Name: primary, Domain: "custom.example.com"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = server.execute(context.Background(), brokerRequest{Operation: "delete_domain", SiteID: created.ID, Name: primary, Domain: "custom.example.com"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if server.registry.Sites[created.ID].Domains["custom.example.com"] {
|
||||
t.Fatal("removed binding still registered")
|
||||
}
|
||||
if _, err = server.execute(context.Background(), brokerRequest{Operation: "delete_domain", SiteID: created.ID, Name: primary, Domain: "custom.example.com"}); err != nil {
|
||||
t.Fatal("removal retry failed", err)
|
||||
}
|
||||
second, err := server.execute(context.Background(), brokerRequest{Operation: "create_site", Site: &SiteSpec{Name: hostName, Domain: hostName + "-docs.hosts.example.com", Path: sitePath, RunPath: "/docs", Runtime: "Node.js", Version: "v24.21.0", RunUser: hostName, Port: 20021, ProcessLimit: 10}})
|
||||
if err != nil || second.ID <= 0 {
|
||||
t.Fatalf("broker rejected a second website inside the same managed host: id=%d err=%v", second.ID, err)
|
||||
}
|
||||
if err = server.validateSite(SiteSpec{Name: hostName, Domain: hostName + "-duplicate.hosts.example.com", Path: sitePath, RunPath: "/docs", Runtime: "PHP", Version: "8.3", RunUser: hostName, Port: 20022, ProcessLimit: 10}); err == nil {
|
||||
t.Fatal("broker accepted two websites with the same host-relative run path")
|
||||
}
|
||||
if _, err = server.execute(context.Background(), brokerRequest{Operation: "set_site_run_path", SiteID: created.ID, Path: "/apps/web/public"}); err != nil {
|
||||
t.Fatalf("managed run path update failed: %v", err)
|
||||
}
|
||||
if _, err = server.execute(context.Background(), brokerRequest{Operation: "configure_proxy", SiteID: created.ID, Domain: hostName + ".hosts.example.com", Port: 20040}); !errors.Is(err, errOutsideManaged) {
|
||||
t.Fatalf("broker accepted a port not bound to the managed site: %v", err)
|
||||
}
|
||||
if _, err = server.execute(context.Background(), brokerRequest{Operation: "install_certificate", SiteID: created.ID + 100, Name: "outside.example.com", PrivateKey: "key", Certificate: "cert"}); !errors.Is(err, errOutsideManaged) || direct.installedCertificates != 0 {
|
||||
t.Fatalf("unmanaged certificate install reached panel: err=%v installs=%d", err, direct.installedCertificates)
|
||||
}
|
||||
if _, err = server.execute(context.Background(), brokerRequest{Operation: "request_certificate", SiteID: created.ID, Path: sitePath, Domains: []string{primary}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if server.registry.Sites[created.ID].ACMEOrder != "owned-order" {
|
||||
t.Fatal("issued renewal order not recorded")
|
||||
}
|
||||
if _, err = server.execute(context.Background(), brokerRequest{Operation: "install_certificate", SiteID: created.ID, Name: hostName + ".hosts.example.com", PrivateKey: "key", Certificate: "cert"}); err != nil {
|
||||
t.Fatalf("managed certificate install failed: %v", err)
|
||||
}
|
||||
if len(direct.clearedOrders) != 1 || direct.clearedOrders[0] != "owned-order" || server.registry.Sites[created.ID].ACMEOrder != "" {
|
||||
t.Fatal("manual certificate did not clear only its tracked renewal")
|
||||
}
|
||||
server.registry.Sites[created.ID].ACMEOrder = "second-owned-order"
|
||||
if direct.installedCertificates != 1 {
|
||||
t.Fatalf("managed certificate install count = %d, want 1", direct.installedCertificates)
|
||||
}
|
||||
if _, err = server.execute(context.Background(), brokerRequest{Operation: "disable_certificate", SiteID: created.ID + 100, Name: "outside.example.com"}); !errors.Is(err, errOutsideManaged) || direct.disabledCertificates != 0 {
|
||||
t.Fatalf("unmanaged certificate disable reached panel: err=%v disables=%d", err, direct.disabledCertificates)
|
||||
}
|
||||
if _, err = server.execute(context.Background(), brokerRequest{Operation: "disable_certificate", SiteID: created.ID, Name: hostName + ".hosts.example.com"}); err != nil {
|
||||
t.Fatalf("managed certificate disable failed: %v", err)
|
||||
}
|
||||
if len(direct.clearedOrders) != 2 || direct.clearedOrders[1] != "second-owned-order" || server.registry.Sites[created.ID].ACMEOrder != "" {
|
||||
t.Fatal("SSL disable did not cancel tracked renewal")
|
||||
}
|
||||
if direct.disabledCertificates != 1 {
|
||||
t.Fatalf("managed certificate disable count = %d, want 1", direct.disabledCertificates)
|
||||
}
|
||||
wrongRuntime := RuntimeSpec{ProjectName: hostName, Runtime: "Java", Version: "21", Path: sitePath, Domain: hostName + ".hosts.example.com", RunUser: "root", Port: 20020, ProcessLimit: 10}
|
||||
if _, err = server.execute(context.Background(), brokerRequest{Operation: "configure_runtime", Runtime: &wrongRuntime}); !errors.Is(err, errOutsideManaged) {
|
||||
t.Fatalf("broker accepted another tenant run user: %v", err)
|
||||
}
|
||||
if _, err = server.execute(context.Background(), brokerRequest{Operation: "create_ftp", Username: "sv_other_project", Password: strings.Repeat("p", 24), Path: sitePath, MaxBytes: 1024}); err == nil {
|
||||
t.Fatal("broker accepted an FTP account not bound to the managed site")
|
||||
}
|
||||
_, err = server.execute(context.Background(), brokerRequest{Operation: "delete_site", ID: created.ID + 100, Name: "outside.example.com"})
|
||||
if !errors.Is(err, errOutsideManaged) || direct.deletedSites != 0 {
|
||||
t.Fatalf("unmanaged delete reached panel: err=%v deletes=%d", err, direct.deletedSites)
|
||||
}
|
||||
if _, err = server.execute(context.Background(), brokerRequest{Operation: "delete_site", ID: created.ID, Name: hostName + ".hosts.example.com"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if direct.deletedSites != 1 {
|
||||
t.Fatalf("managed delete count = %d, want 1", direct.deletedSites)
|
||||
}
|
||||
restarted, err := newBrokerServer(stateDir, tenantRoot, "", func(BrokerCredentials) Interface { return direct })
|
||||
if err != nil {
|
||||
t.Fatalf("configured broker should restart without the one-time setup token: %v", err)
|
||||
}
|
||||
request = httptest.NewRequest(http.MethodPost, "/v1/setup/test", strings.NewReader(string(body)))
|
||||
response = httptest.NewRecorder()
|
||||
restarted.Handler().ServeHTTP(response, request)
|
||||
if response.Code != http.StatusNotFound {
|
||||
t.Fatalf("setup endpoint remained registered after restart: status=%d", response.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBrokerSetupRequiresToken(t *testing.T) {
|
||||
server, err := newBrokerServer(t.TempDir(), t.TempDir(), strings.Repeat("t", 32), func(BrokerCredentials) Interface { return NewMock() })
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
request := httptest.NewRequest(http.MethodPost, "/v1/setup/test", strings.NewReader(`{}`))
|
||||
response := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(response, request)
|
||||
if response.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("status = %d, want 401", response.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBrokerOperationsRequireInternalToken(t *testing.T) {
|
||||
server, err := newBrokerServer(t.TempDir(), t.TempDir(), strings.Repeat("t", 32), func(BrokerCredentials) Interface { return NewMock() }, strings.Repeat("i", 32))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
request := httptest.NewRequest(http.MethodPost, "/v1/operations", strings.NewReader(`{"operation":"ping"}`))
|
||||
response := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(response, request)
|
||||
if response.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("unauthenticated operation status = %d, want 401", response.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBrokerSetupInspectionReturnsRuntimeVersions(t *testing.T) {
|
||||
token := strings.Repeat("t", 32)
|
||||
server, err := newBrokerServer(t.TempDir(), t.TempDir(), token, func(BrokerCredentials) Interface { return NewMock() })
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
body, _ := json.Marshal(BrokerCredentials{URL: "https://127.0.0.1:8888", APIKey: strings.Repeat("k", 32), TLSInsecure: true})
|
||||
request := httptest.NewRequest(http.MethodPost, "/v1/setup/test", strings.NewReader(string(body)))
|
||||
request.Header.Set("X-Setup-Token", token)
|
||||
response := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(response, request)
|
||||
if response.Code != http.StatusOK || !strings.Contains(response.Body.String(), `"PHP"`) || !strings.Contains(response.Body.String(), `"Node.js"`) {
|
||||
t.Fatalf("inspection status = %d, body = %s", response.Code, response.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnconfiguredBrokerRejectsMissingSetupToken(t *testing.T) {
|
||||
_, err := newBrokerServer(t.TempDir(), t.TempDir(), "", func(BrokerCredentials) Interface { return NewMock() })
|
||||
if err == nil {
|
||||
t.Fatal("unconfigured broker started without a setup token")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package panel
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/ecdsa"
|
||||
"crypto/elliptic"
|
||||
"crypto/rand"
|
||||
"crypto/x509"
|
||||
"crypto/x509/pkix"
|
||||
"encoding/json"
|
||||
"encoding/pem"
|
||||
"math/big"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestSynchronousHTTPCertificateIsValidatedAndInstalledWithoutOrderIndex(t *testing.T) {
|
||||
key, e := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
cert := &x509.Certificate{SerialNumber: big.NewInt(42), Subject: pkix.Name{CommonName: "host.example.com"}, DNSNames: []string{"host.example.com"}, NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(90 * 24 * time.Hour), KeyUsage: x509.KeyUsageDigitalSignature}
|
||||
der, e := x509.CreateCertificate(rand.Reader, cert, cert, &key.PublicKey, key)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
rawKey, e := x509.MarshalPKCS8PrivateKey(key)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
chain := string(pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}))
|
||||
private := string(pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: rawKey}))
|
||||
installed := 0
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
_ = r.ParseForm()
|
||||
switch r.Form.Get("action") {
|
||||
case "apply_cert_api":
|
||||
if r.Form.Get("auth_to") != "7" {
|
||||
t.Error("issuance must resolve the site's current run directory")
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"status": true, "msg": "申请成功", "cert": chain, "root": "", "private_key": private})
|
||||
case "SetSSL":
|
||||
installed++
|
||||
if r.Form.Get("siteName") != "host.example.com" || r.Form.Get("key") != private || r.Form.Get("csr") == "" {
|
||||
t.Error("invalid fixed-site installation")
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"status": true})
|
||||
default:
|
||||
t.Error("unexpected certificate operation", r.Form.Get("action"))
|
||||
w.WriteHeader(404)
|
||||
}
|
||||
}))
|
||||
defer server.Close()
|
||||
client := NewClient(server.URL, "test-key", false, 5*time.Second)
|
||||
if e = client.RequestCertificate(context.Background(), 7, "/www/example", []string{"host.example.com"}); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if installed != 1 {
|
||||
t.Fatal("inline certificate was not installed")
|
||||
}
|
||||
if e = client.RequestCertificate(context.Background(), 7, "/www/example", []string{"outside.example.net"}); e == nil {
|
||||
t.Fatal("certificate outside requested domains accepted")
|
||||
}
|
||||
if installed != 1 {
|
||||
t.Fatal("invalid certificate reached panel installation")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package panel
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/md5"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// aaPanel indexes orders with the MD5 of Python's JSON identifiers array.
|
||||
func managedACMEIndex(domains []string) string {
|
||||
parts := make([]string, 0, len(domains))
|
||||
for _, domain := range domains {
|
||||
raw, _ := json.Marshal(domain)
|
||||
parts = append(parts, `{"type": "dns", "value": `+string(raw)+`}`)
|
||||
}
|
||||
sum := md5.Sum([]byte("[" + strings.Join(parts, ", ") + "]"))
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
func sameDomainSet(a, b []string) bool {
|
||||
if len(a) != len(b) {
|
||||
return false
|
||||
}
|
||||
set := map[string]bool{}
|
||||
for _, v := range b {
|
||||
set[strings.ToLower(v)] = true
|
||||
}
|
||||
for _, v := range a {
|
||||
key := strings.ToLower(v)
|
||||
if !set[key] {
|
||||
return false
|
||||
}
|
||||
delete(set, key)
|
||||
}
|
||||
return len(set) == 0
|
||||
}
|
||||
func (c *Client) ClearManagedCertificateOrder(ctx context.Context, index string) error {
|
||||
if !validIdentifierForOrder(index) {
|
||||
return errors.New("invalid managed certificate order")
|
||||
}
|
||||
_, err := c.call(ctx, http.MethodPost, "/acme", url.Values{"action": {"remove_order"}, "index": {index}})
|
||||
if err != nil && strings.Contains(err.Error(), "指定订单不存在") {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
func validIdentifierForOrder(v string) bool {
|
||||
if len(v) < 1 || len(v) > 128 {
|
||||
return false
|
||||
}
|
||||
for _, c := range v {
|
||||
if !(c >= 'a' && c <= 'z') && !(c >= 'A' && c <= 'Z') && !(c >= '0' && c <= '9') && c != '-' && c != '_' {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package panel
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/md5"
|
||||
"encoding/hex"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestManagedACMEIndexUsesNativePythonJSON(t *testing.T) {
|
||||
raw := `[{"type": "dns", "value": "a.example.com"}, {"type": "dns", "value": "b.example.com"}]`
|
||||
sum := md5.Sum([]byte(raw))
|
||||
if got := managedACMEIndex([]string{"a.example.com", "b.example.com"}); got != hex.EncodeToString(sum[:]) {
|
||||
t.Fatal("native order index mismatch", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClearManagedCertificateOrderIsScopedAndIdempotent(t *testing.T) {
|
||||
calls := 0
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
_ = r.ParseForm()
|
||||
calls++
|
||||
if r.URL.Path != "/acme" || r.Form.Get("action") != "remove_order" || r.Form.Get("index") != "owned-order" {
|
||||
t.Error("unexpected order mutation")
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"status":false,"msg":"指定订单不存在!"}`))
|
||||
}))
|
||||
defer server.Close()
|
||||
c := NewClient(server.URL, "test-key", false, time.Second)
|
||||
if err := c.ClearManagedCertificateOrder(context.Background(), "../foreign"); err == nil || calls != 0 {
|
||||
t.Fatal("invalid index reached panel")
|
||||
}
|
||||
if err := c.ClearManagedCertificateOrder(context.Background(), "owned-order"); err != nil || calls != 1 {
|
||||
t.Fatal("missing owned order retry failed", err)
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,808 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package panel
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
var managedPasswordPattern = regexp.MustCompile(`^[A-Za-z0-9_-]{20,128}$`)
|
||||
|
||||
func (c *Client) SetFTPPassword(ctx context.Context, id int64, name, password string) error {
|
||||
if id <= 0 || !brokerHostPattern.MatchString(name) || !managedPasswordPattern.MatchString(password) {
|
||||
return errors.New("invalid managed credential reset")
|
||||
}
|
||||
_, err := c.call(ctx, http.MethodPost, "/ftp", url.Values{"action": {"SetUserPassword"}, "id": {strconv.FormatInt(id, 10)}, "ftp_username": {name}, "new_password": {password}})
|
||||
return err
|
||||
}
|
||||
func (c *Client) SetDatabasePassword(ctx context.Context, id int64, name, password string) error {
|
||||
if id <= 0 || !brokerHostPattern.MatchString(name) || !managedPasswordPattern.MatchString(password) {
|
||||
return errors.New("invalid managed credential reset")
|
||||
}
|
||||
_, err := c.call(ctx, http.MethodPost, "/database", url.Values{"action": {"ResDatabasePassword"}, "id": {strconv.FormatInt(id, 10)}, "name": {name}, "password": {password}})
|
||||
return err
|
||||
}
|
||||
func (c *BrokerClient) SetFTPPassword(ctx context.Context, id int64, name, password string) error {
|
||||
_, err := c.operation(ctx, brokerRequest{Operation: "set_ftp_password", ID: id, Username: name, Password: password})
|
||||
return err
|
||||
}
|
||||
func (c *BrokerClient) SetDatabasePassword(ctx context.Context, id int64, name, password string) error {
|
||||
_, err := c.operation(ctx, brokerRequest{Operation: "set_database_password", ID: id, Name: name, Password: password})
|
||||
return err
|
||||
}
|
||||
func (*Mock) SetFTPPassword(context.Context, int64, string, string) error { return nil }
|
||||
func (*Mock) SetDatabasePassword(context.Context, int64, string, string) error { return nil }
|
||||
@@ -0,0 +1,72 @@
|
||||
package panel
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestCredentialResetUsesInstalledPanelArgumentsAndRejectsShellText(t *testing.T) {
|
||||
calls := 0
|
||||
password := strings.Repeat("aB9_", 6)
|
||||
name := "sv0123456789"
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
calls++
|
||||
r.ParseForm()
|
||||
if r.Method != "POST" || r.FormValue("id") != "17" {
|
||||
t.Error("wrong reset target")
|
||||
}
|
||||
switch r.URL.Path {
|
||||
case "/ftp":
|
||||
if r.FormValue("action") != "SetUserPassword" || r.FormValue("ftp_username") != name || r.FormValue("new_password") != password {
|
||||
t.Error("incorrect FTP API arguments")
|
||||
}
|
||||
case "/database":
|
||||
if r.FormValue("action") != "ResDatabasePassword" || r.FormValue("name") != name || r.FormValue("password") != password {
|
||||
t.Error("incorrect database API arguments")
|
||||
}
|
||||
default:
|
||||
t.Error("unexpected panel path")
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.Write([]byte(`{"status":true}`))
|
||||
}))
|
||||
defer server.Close()
|
||||
c := &Client{baseURL: server.URL, apiKey: "test", http: server.Client()}
|
||||
ctx := context.Background()
|
||||
if err := c.SetFTPPassword(ctx, 17, name, password); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := c.SetDatabasePassword(ctx, 17, name, password); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, bad := range []string{"short", strings.Repeat("a", 20) + "\nEOF\nid", strings.Repeat("a", 20) + "$(id)"} {
|
||||
if c.SetFTPPassword(ctx, 17, name, bad) == nil || c.SetDatabasePassword(ctx, 17, name, bad) == nil {
|
||||
t.Fatal("unsafe password accepted")
|
||||
}
|
||||
}
|
||||
if calls != 2 {
|
||||
t.Fatal("invalid reset reached native panel")
|
||||
}
|
||||
}
|
||||
func TestBrokerCredentialResetRequiresExactManagedIDAndName(t *testing.T) {
|
||||
server, err := newBrokerServer(t.TempDir(), t.TempDir(), strings.Repeat("t", 32), func(BrokerCredentials) Interface { return NewMock() })
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
server.direct = NewMock()
|
||||
server.registry.FTP[17] = "sv0123456789"
|
||||
server.registry.Databases[18] = "sv0123456789"
|
||||
for _, request := range []brokerRequest{{Operation: "set_ftp_password", ID: 17, Username: "sv0123456789", Password: strings.Repeat("a", 24)}, {Operation: "set_database_password", ID: 18, Name: "sv0123456789", Password: strings.Repeat("b", 24)}} {
|
||||
if _, err = server.execute(context.Background(), request); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
request.ID++
|
||||
if _, err = server.execute(context.Background(), request); !errors.Is(err, errOutsideManaged) {
|
||||
t.Fatal("unmanaged credential reset allowed")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package panel
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"time"
|
||||
)
|
||||
|
||||
// aaPanel caches Go release lists until force=true is supplied. Refresh that
|
||||
// metadata at most once a minute; installed SDKs still come from its real ls.
|
||||
func (c *Client) goSDKInventory(ctx context.Context, refresh bool) ([]byte, error) {
|
||||
c.goMetadataMu.Lock()
|
||||
force := refresh && time.Now().After(c.goRefreshAfter)
|
||||
if force {
|
||||
c.goRefreshAfter = time.Now().Add(time.Minute)
|
||||
}
|
||||
cached, measured := append([]byte(nil), c.goLastGood...), c.goLastGoodAt
|
||||
c.goMetadataMu.Unlock()
|
||||
valid := func(body []byte, err error) bool {
|
||||
var state struct {
|
||||
Status any `json:"status"`
|
||||
}
|
||||
return err == nil && json.Unmarshal(body, &state) == nil && !failed(state.Status)
|
||||
}
|
||||
body, err := c.request(ctx, http.MethodPost, "/project/go/list_go_sdk/stype", nil)
|
||||
good := valid(body, err)
|
||||
if force && ctx.Err() == nil {
|
||||
updated, updateErr := c.request(ctx, http.MethodPost, "/project/go/list_go_sdk/stype", url.Values{"force": {"true"}})
|
||||
if valid(updated, updateErr) {
|
||||
body, err, good = updated, nil, true
|
||||
}
|
||||
}
|
||||
if good {
|
||||
c.goMetadataMu.Lock()
|
||||
c.goLastGood = append([]byte(nil), body...)
|
||||
c.goLastGoodAt = time.Now()
|
||||
c.goMetadataMu.Unlock()
|
||||
return body, nil
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
if len(cached) > 0 && time.Since(measured) < time.Minute {
|
||||
return cached, nil
|
||||
}
|
||||
if err == nil {
|
||||
err = errors.New("Go SDK metadata is temporarily unavailable")
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package panel
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestGoReleaseRefreshDoesNotRemainOnPanelCachedPatch(t *testing.T) {
|
||||
force := 0
|
||||
latest := "go1.27.1"
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.FormValue("force") == "true" {
|
||||
force++
|
||||
latest = "go1.27.3"
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"status": true, "installed": []string{"go1.27.1"}, "sdk": map[string]any{"all": []map[string]any{{"version": latest}}}})
|
||||
}))
|
||||
defer server.Close()
|
||||
client := NewClient(server.URL, "test-key", false, time.Second)
|
||||
for range 2 {
|
||||
body, err := client.goSDKInventory(context.Background(), true)
|
||||
if err != nil || !strings.Contains(string(body), "go1.27.3") {
|
||||
t.Fatalf("stale SDK list: %s %v", body, err)
|
||||
}
|
||||
}
|
||||
if force != 1 {
|
||||
t.Fatalf("metadata refresh requests: %d", force)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGoMetadataRefreshFailurePreservesInstalledInventory(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.FormValue("force") == "true" {
|
||||
http.Error(w, "cloud unavailable", 502)
|
||||
return
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"status": true, "installed": []string{"go1.27.1"}})
|
||||
}))
|
||||
defer server.Close()
|
||||
client := NewClient(server.URL, "test-key", false, time.Second)
|
||||
body, err := client.goSDKInventory(context.Background(), true)
|
||||
if err != nil || !strings.Contains(string(body), "go1.27.1") {
|
||||
t.Fatalf("lost installed SDK inventory: %s %v", body, err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package panel
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
)
|
||||
|
||||
type Mock struct {
|
||||
mu sync.Mutex
|
||||
next int64
|
||||
}
|
||||
|
||||
func NewMock() *Mock { return &Mock{next: 1000} }
|
||||
func (m *Mock) id() int64 { m.mu.Lock(); defer m.mu.Unlock(); m.next++; return m.next }
|
||||
func (*Mock) Ping(context.Context) error { return nil }
|
||||
func (*Mock) RuntimeCapabilities(context.Context) (RuntimeCapabilities, error) {
|
||||
versions := RuntimeCatalog{
|
||||
"PHP": {"8.4", "8.2", "8.1"},
|
||||
"Node.js": {"v22.23.3", "v20.19.5"},
|
||||
"Python": {"3.12.3", "3.11.9"},
|
||||
"Go": {"go1.25.4", "go1.24.10"},
|
||||
"Java": {"jdk-21.0.2", "jdk-17.0.12"},
|
||||
}
|
||||
capabilities := make(RuntimeCapabilities, len(versions))
|
||||
for runtime, items := range versions {
|
||||
policy := PolicyFreeProject
|
||||
if runtime == "PHP" {
|
||||
policy = PolicyFreeCore
|
||||
}
|
||||
capabilities[runtime] = RuntimeCapability{Status: RuntimeAvailable, Versions: items, Policy: policy}
|
||||
}
|
||||
return capabilities, nil
|
||||
}
|
||||
func (m *Mock) RuntimeCatalog(ctx context.Context) (RuntimeCatalog, error) {
|
||||
capabilities, err := m.RuntimeCapabilities(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
catalog := make(RuntimeCatalog, len(capabilities))
|
||||
for runtime, capability := range capabilities {
|
||||
catalog[runtime] = capability.Versions
|
||||
}
|
||||
return catalog, nil
|
||||
}
|
||||
func (*Mock) RuntimeEnvironments(context.Context) ([]RuntimeEnvironment, error) {
|
||||
return []RuntimeEnvironment{
|
||||
{Name: "PHP", ComponentTitle: "PHP 运行环境", ComponentStatus: RuntimeComponentReady, Installed: []string{"8.4", "8.2"}, Available: []string{}, Installing: []string{}},
|
||||
{Name: "Node.js", ComponentTitle: "Node.js 版本管理器", ComponentStatus: RuntimeComponentReady, Installed: []string{"v22.23.3"}, Available: []string{"v24.12.0", "v22.23.3"}, Installing: []string{}, Recommended: "v24.12.0"},
|
||||
{Name: "Python", ComponentTitle: "Python 项目管理器", ComponentStatus: RuntimeComponentReady, Installed: []string{"3.12.3"}, Available: []string{"3.13.1", "3.12.3"}, Installing: []string{}, Recommended: "3.13.1"},
|
||||
{Name: "Go", ComponentTitle: "Go 项目环境", ComponentStatus: RuntimeComponentReady, Installed: []string{"go1.25.4"}, Available: []string{"go1.26.1", "go1.25.4"}, Installing: []string{}, Recommended: "go1.26.1"},
|
||||
{Name: "Java", ComponentTitle: "Java 项目环境", ComponentStatus: RuntimeComponentReady, Installed: []string{"jdk-21.0.2"}, Available: []string{"jdk-25.0.1", "jdk-21.0.2"}, Installing: []string{}, Recommended: "jdk-25.0.1"},
|
||||
}, nil
|
||||
}
|
||||
func (*Mock) InstallRuntimeComponent(context.Context, string) error { return nil }
|
||||
func (*Mock) InstallRuntimeEnvironment(context.Context, string, string) error { return nil }
|
||||
func (m *Mock) CreateSite(context.Context, SiteSpec) (int64, error) { return m.id(), nil }
|
||||
func (*Mock) ListUnmanagedSites(context.Context) ([]ExistingSite, error) {
|
||||
return []ExistingSite{}, nil
|
||||
}
|
||||
func (*Mock) AdoptSite(context.Context, int64, string, SiteSpec) error { return nil }
|
||||
func (*Mock) RollbackAdoption(context.Context, int64, string, string) error { return nil }
|
||||
func (*Mock) SetSitePath(context.Context, int64, string) error { return nil }
|
||||
func (m *Mock) SetSiteRunPath(context.Context, int64, string) error { return nil }
|
||||
func (m *Mock) MigrateRuntimeIdentity(context.Context, int64, string, bool) error { return nil }
|
||||
func (*Mock) DeleteSite(context.Context, int64, string) error { return nil }
|
||||
func (*Mock) AddDomain(context.Context, int64, string, string) error { return nil }
|
||||
func (*Mock) DeleteDomain(context.Context, int64, string, string) error { return nil }
|
||||
func (m *Mock) CreateFTP(context.Context, string, string, string, int64) (int64, error) {
|
||||
return m.id(), nil
|
||||
}
|
||||
func (*Mock) DeleteFTP(context.Context, int64, string) error { return nil }
|
||||
func (*Mock) SetFTPState(context.Context, int64, string, bool) error { return nil }
|
||||
func (m *Mock) CreateDatabase(context.Context, string, string, string, int64) (int64, error) {
|
||||
return m.id(), nil
|
||||
}
|
||||
func (*Mock) DeleteDatabase(context.Context, int64, string) error { return nil }
|
||||
func (*Mock) DatabaseSize(context.Context, int64, string) (uint64, error) { return 0, nil }
|
||||
func (*Mock) ConfigureRuntime(context.Context, RuntimeSpec) error { return nil }
|
||||
func (*Mock) RemoveRuntime(context.Context, RuntimeSpec) error { return nil }
|
||||
func (*Mock) SetRuntimeState(context.Context, RuntimeSpec, bool) error { return nil }
|
||||
func (*Mock) ConfigureProxy(context.Context, int64, string, int) error { return nil }
|
||||
func (*Mock) RequestCertificate(context.Context, int64, string, []string) error { return nil }
|
||||
func (*Mock) InstallCertificate(context.Context, int64, string, string, string) error { return nil }
|
||||
func (*Mock) DisableCertificate(context.Context, int64, string) error { return nil }
|
||||
func (*Mock) SetSiteState(context.Context, int64, string, bool) error { return nil }
|
||||
@@ -0,0 +1,134 @@
|
||||
package panel
|
||||
|
||||
import "context"
|
||||
|
||||
type SiteSpec struct {
|
||||
Name, Domain, Path, RunPath, Runtime, Version, RunUser string
|
||||
Port, ProcessLimit int
|
||||
}
|
||||
|
||||
type ExistingSite struct {
|
||||
ID int64 `json:"id"`
|
||||
Domain string `json:"domain"`
|
||||
Path string `json:"path"`
|
||||
PHPVersion string `json:"phpVersion,omitempty"`
|
||||
Status string `json:"status"`
|
||||
}
|
||||
|
||||
type RuntimeSpec struct {
|
||||
Runner bool
|
||||
ProjectName, Runtime, Version, Path, RunPath, EntryFile, Domain string
|
||||
RunUser string
|
||||
Port, ProcessLimit int
|
||||
}
|
||||
|
||||
// RuntimeCatalog uses the public runtime names accepted by project creation as
|
||||
// keys. Values are the exact version identifiers returned by aaPanel.
|
||||
type RuntimeCatalog map[string][]string
|
||||
|
||||
const (
|
||||
RuntimeAvailable = "available"
|
||||
RuntimeNotInstalled = "not_installed"
|
||||
RuntimeProbeFailed = "probe_failed"
|
||||
PolicyFreeCore = "free_core"
|
||||
PolicyFreeProject = "free_project"
|
||||
)
|
||||
|
||||
// RuntimeCapability records each language independently. A missing or broken
|
||||
// optional project route must not prevent Sea vHost itself from being installed.
|
||||
type RuntimeCapability struct {
|
||||
Status string `json:"status"`
|
||||
Versions []string `json:"versions"`
|
||||
Policy string `json:"policy"`
|
||||
Detail string `json:"detail,omitempty"`
|
||||
}
|
||||
|
||||
type RuntimeCapabilities map[string]RuntimeCapability
|
||||
|
||||
const (
|
||||
RuntimeComponentReady = "installed"
|
||||
RuntimeComponentMissing = "not_installed"
|
||||
RuntimeComponentFailed = "probe_failed"
|
||||
)
|
||||
|
||||
// RuntimeEnvironment is the administrator-facing installation inventory. The
|
||||
// install endpoints only accept versions present in Available; callers cannot
|
||||
// pass package names, URLs, shell fragments, or arbitrary panel operations.
|
||||
type RuntimeEnvironment struct {
|
||||
Name string `json:"name"`
|
||||
ComponentTitle string `json:"componentTitle"`
|
||||
ComponentStatus string `json:"componentStatus"`
|
||||
ComponentVersion string `json:"componentVersion,omitempty"`
|
||||
ComponentLatestVersion string `json:"componentLatestVersion,omitempty"`
|
||||
ComponentUpdateAvailable bool `json:"componentUpdateAvailable"`
|
||||
ComponentInstallable bool `json:"componentInstallable"`
|
||||
Installed []string `json:"installed"`
|
||||
Available []string `json:"available"`
|
||||
Installing []string `json:"installing"`
|
||||
Recommended string `json:"recommended,omitempty"`
|
||||
Detail string `json:"detail,omitempty"`
|
||||
Patches []RuntimePatch `json:"patches,omitempty"`
|
||||
}
|
||||
|
||||
type RuntimePatch struct {
|
||||
Branch string `json:"branch"`
|
||||
Installed string `json:"installed"`
|
||||
Latest string `json:"latest"`
|
||||
UpdateAvailable bool `json:"updateAvailable"`
|
||||
}
|
||||
|
||||
// RuntimeMaintenance exposes only fixed PHP updates and existing managed
|
||||
// runtime records. It is not a generic panel API proxy.
|
||||
type ManagedCertificateIssuer interface {
|
||||
IssueManagedCertificate(context.Context, int64, string, []string) (string, error)
|
||||
ClearManagedCertificateOrder(context.Context, string) error
|
||||
}
|
||||
|
||||
type RuntimeResetter interface {
|
||||
ResetManagedRuntime(context.Context, int64, string) error
|
||||
}
|
||||
|
||||
type RuntimeMaintenance interface {
|
||||
UpdatePHPRuntime(context.Context, string, string) error
|
||||
PHPRuntimeUpdatePending(context.Context, string) (bool, error)
|
||||
ManagedRuntime(context.Context, int64) (RuntimeSpec, error)
|
||||
ReplaceManagedRuntime(context.Context, int64, RuntimeSpec) error
|
||||
}
|
||||
|
||||
type Interface interface {
|
||||
Ping(context.Context) error
|
||||
RuntimeCapabilities(context.Context) (RuntimeCapabilities, error)
|
||||
RuntimeCatalog(context.Context) (RuntimeCatalog, error)
|
||||
RuntimeEnvironments(context.Context) ([]RuntimeEnvironment, error)
|
||||
InstallRuntimeComponent(context.Context, string) error
|
||||
InstallRuntimeEnvironment(context.Context, string, string) error
|
||||
CreateSite(context.Context, SiteSpec) (int64, error)
|
||||
ListUnmanagedSites(context.Context) ([]ExistingSite, error)
|
||||
AdoptSite(context.Context, int64, string, SiteSpec) error
|
||||
RollbackAdoption(context.Context, int64, string, string) error
|
||||
SetSitePath(context.Context, int64, string) error
|
||||
DeleteSite(context.Context, int64, string) error
|
||||
AddDomain(context.Context, int64, string, string) error
|
||||
DeleteDomain(context.Context, int64, string, string) error
|
||||
CreateFTP(context.Context, string, string, string, int64) (int64, error)
|
||||
DeleteFTP(context.Context, int64, string) error
|
||||
SetFTPState(context.Context, int64, string, bool) error
|
||||
CreateDatabase(context.Context, string, string, string, int64) (int64, error)
|
||||
DeleteDatabase(context.Context, int64, string) error
|
||||
DatabaseSize(context.Context, int64, string) (uint64, error)
|
||||
ConfigureRuntime(context.Context, RuntimeSpec) error
|
||||
RemoveRuntime(context.Context, RuntimeSpec) error
|
||||
SetRuntimeState(context.Context, RuntimeSpec, bool) error
|
||||
ConfigureProxy(context.Context, int64, string, int) error
|
||||
RequestCertificate(context.Context, int64, string, []string) error
|
||||
InstallCertificate(context.Context, int64, string, string, string) error
|
||||
DisableCertificate(context.Context, int64, string) error
|
||||
SetSiteState(context.Context, int64, string, bool) error
|
||||
SetSiteRunPath(context.Context, int64, string) error
|
||||
MigrateRuntimeIdentity(context.Context, int64, string, bool) error
|
||||
}
|
||||
|
||||
type CredentialManager interface {
|
||||
SetFTPPassword(context.Context, int64, string, string) error
|
||||
SetDatabasePassword(context.Context, int64, string, string) error
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
package panel
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync"
|
||||
)
|
||||
|
||||
var phpSoftwarePattern = regexp.MustCompile(`^php-[5-9]\.[0-9]$`)
|
||||
var phpPatchNumberPattern = regexp.MustCompile(`^[0-9]{1,4}$`)
|
||||
var phpPatchVersionPattern = regexp.MustCompile(`^[5-9]\.[0-9]\.[0-9]+$`)
|
||||
|
||||
func (c *Client) phpRuntimePatches(ctx context.Context, branches []string) []RuntimePatch {
|
||||
results := make([]*RuntimePatch, len(branches))
|
||||
var wg sync.WaitGroup
|
||||
for index, branch := range branches {
|
||||
if !phpSoftwarePattern.MatchString("php-" + branch) {
|
||||
continue
|
||||
}
|
||||
wg.Go(func() {
|
||||
plugin, err := c.runtimePlugin(ctx, "php-"+branch, "PHP")
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
for _, release := range plugin.Versions {
|
||||
latest := release.MVersion + "." + release.Version
|
||||
if release.MVersion != branch || release.Beta != 0 || !phpPatchVersionPattern.MatchString(latest) {
|
||||
continue
|
||||
}
|
||||
results[index] = &RuntimePatch{Branch: branch, Installed: plugin.MinVersion, Latest: latest, UpdateAvailable: plugin.MinVersion != "" && newerRuntimeVersion(latest, plugin.MinVersion)}
|
||||
break
|
||||
}
|
||||
})
|
||||
}
|
||||
wg.Wait()
|
||||
items := make([]RuntimePatch, 0, len(branches))
|
||||
for _, item := range results {
|
||||
if item != nil {
|
||||
items = append(items, *item)
|
||||
}
|
||||
}
|
||||
return items
|
||||
}
|
||||
|
||||
func newerRuntimeVersion(candidate, installed string) bool {
|
||||
return candidate != installed && sortDottedVersionsDescending([]string{candidate, installed})[0] == candidate
|
||||
}
|
||||
|
||||
func (c *Client) UpdatePHPRuntime(ctx context.Context, branch, target string) error {
|
||||
if !phpSoftwarePattern.MatchString("php-" + branch) {
|
||||
return errors.New("invalid PHP branch")
|
||||
}
|
||||
patches := c.phpRuntimePatches(ctx, []string{branch})
|
||||
if len(patches) != 1 || !patches[0].UpdateAvailable || patches[0].Latest != target {
|
||||
return errors.New("PHP target is not the advertised stable patch")
|
||||
}
|
||||
_, err := c.call(ctx, http.MethodPost, "/plugin", url.Values{"action": {"install_plugin"}, "sName": {"php-" + branch}, "version": {branch}, "min_version": {strings.TrimPrefix(target, branch+".")}, "type": {"0"}, "upgrade": {"1"}})
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *Client) PHPRuntimeUpdatePending(ctx context.Context, branch string) (bool, error) {
|
||||
if !phpSoftwarePattern.MatchString("php-" + branch) {
|
||||
return false, errors.New("invalid PHP branch")
|
||||
}
|
||||
name := "upgrade[php-" + branch + "]"
|
||||
// aaPanel searches tasks by status OR type, not by name. Fetch only
|
||||
// execution tasks, then match the exact managed PHP branch locally.
|
||||
body, err := c.request(ctx, http.MethodPost, "/data", url.Values{"action": {"getData"}, "table": {"tasks"}, "limit": {"1000"}, "p": {"1"}, "search": {"execshell"}})
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
var response struct {
|
||||
Data []struct {
|
||||
Name string `json:"name"`
|
||||
Status any `json:"status"`
|
||||
} `json:"data"`
|
||||
}
|
||||
if json.Unmarshal(body, &response) != nil || response.Data == nil {
|
||||
return false, errors.New("cannot verify PHP update queue")
|
||||
}
|
||||
if len(response.Data) >= 1000 {
|
||||
return false, errors.New("PHP update queue exceeded verification limit")
|
||||
}
|
||||
for _, task := range response.Data {
|
||||
status := fmt.Sprint(task.Status)
|
||||
if task.Name == name && (status == "0" || status == "-1") {
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
|
||||
func (c *Client) ManagedRuntime(context.Context, int64) (RuntimeSpec, error) {
|
||||
return RuntimeSpec{}, errors.New("managed runtime records require the panel broker")
|
||||
}
|
||||
func (c *Client) ReplaceManagedRuntime(context.Context, int64, RuntimeSpec) error {
|
||||
return errors.New("runtime replacement requires the panel broker")
|
||||
}
|
||||
|
||||
func (c *BrokerClient) UpdatePHPRuntime(ctx context.Context, branch, target string) error {
|
||||
_, err := c.operation(ctx, brokerRequest{Operation: "update_php_runtime", Name: branch, Version: target})
|
||||
return err
|
||||
}
|
||||
func (c *BrokerClient) PHPRuntimeUpdatePending(ctx context.Context, branch string) (bool, error) {
|
||||
r, err := c.operation(ctx, brokerRequest{Operation: "php_update_pending", Name: branch})
|
||||
return r.Pending, err
|
||||
}
|
||||
func (c *BrokerClient) ManagedRuntime(ctx context.Context, id int64) (RuntimeSpec, error) {
|
||||
r, err := c.operation(ctx, brokerRequest{Operation: "managed_runtime", SiteID: id})
|
||||
if err != nil {
|
||||
return RuntimeSpec{}, err
|
||||
}
|
||||
if r.Runtime == nil {
|
||||
return RuntimeSpec{}, errors.New("site has no deployed language project")
|
||||
}
|
||||
return *r.Runtime, nil
|
||||
}
|
||||
func (c *BrokerClient) ReplaceManagedRuntime(ctx context.Context, id int64, spec RuntimeSpec) error {
|
||||
_, err := c.operation(ctx, brokerRequest{Operation: "replace_runtime", SiteID: id, Runtime: &spec})
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *BrokerClient) ResetManagedRuntime(ctx context.Context, id int64, name string) error {
|
||||
_, err := c.operation(ctx, brokerRequest{Operation: "reset_managed_runtime", SiteID: id, Name: name})
|
||||
return err
|
||||
}
|
||||
func (c *Client) ResetManagedRuntime(context.Context, int64, string) error {
|
||||
return errors.New("runtime reset requires the panel broker")
|
||||
}
|
||||
func (c *Client) RemoveManagedProxy(ctx context.Context, domain string) error {
|
||||
exists := func() (bool, error) {
|
||||
raw, err := c.request(ctx, http.MethodPost, "/site", url.Values{"action": {"GetProxyList"}, "sitename": {domain}})
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
var rows []struct {
|
||||
Site string `json:"sitename"`
|
||||
Name string `json:"proxyname"`
|
||||
}
|
||||
if json.Unmarshal(raw, &rows) != nil {
|
||||
return false, errors.New("cannot verify managed proxy records")
|
||||
}
|
||||
for _, row := range rows {
|
||||
if row.Site == domain && row.Name == "sea-vhost-runtime" {
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
found, err := exists()
|
||||
if err != nil || !found {
|
||||
return err
|
||||
}
|
||||
if _, err = c.call(ctx, http.MethodPost, "/site", url.Values{"action": {"RemoveProxy"}, "sitename": {domain}, "proxyname": {"sea-vhost-runtime"}}); err != nil {
|
||||
return err
|
||||
}
|
||||
found, err = exists()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if found {
|
||||
return errors.New("panel did not remove the managed proxy")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,294 @@
|
||||
package panel
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestPHPPatchUpdateUsesOnlyAdvertisedFreeBranch(t *testing.T) {
|
||||
submitted := 0
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.FormValue("action") {
|
||||
case "get_soft_find":
|
||||
_ = 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 "install_plugin":
|
||||
submitted++
|
||||
if r.FormValue("sName") != "php-8.4" || r.FormValue("version") != "8.4" || r.FormValue("min_version") != "27" || r.FormValue("upgrade") != "1" {
|
||||
t.Error("PHP update parameters escaped the selected branch")
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"status": true})
|
||||
default:
|
||||
t.Errorf("unexpected request %s", r.FormValue("action"))
|
||||
}
|
||||
}))
|
||||
defer server.Close()
|
||||
client := NewClient(server.URL, "test", false, 5*time.Second)
|
||||
if err := client.UpdatePHPRuntime(context.Background(), "8.4", "8.5.0"); err == nil {
|
||||
t.Fatal("cross-branch patch target accepted")
|
||||
}
|
||||
if submitted != 0 {
|
||||
t.Fatal("invalid target mutated panel")
|
||||
}
|
||||
if err := client.UpdatePHPRuntime(context.Background(), "8.4", "8.4.27"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if submitted != 1 {
|
||||
t.Fatalf("submitted %d updates", submitted)
|
||||
}
|
||||
for _, values := range []url.Values{
|
||||
{"action": {"install_plugin"}, "sName": {"php-8.4"}, "version": {"8.5"}, "min_version": {"27"}, "type": {"0"}, "upgrade": {"1"}},
|
||||
{"action": {"install_plugin"}, "sName": {"php-8.4"}, "version": {"8.4"}, "min_version": {"27;id"}, "type": {"0"}, "upgrade": {"1"}},
|
||||
{"action": {"getData"}, "table": {"tasks"}, "search": {""}},
|
||||
} {
|
||||
route := "/plugin"
|
||||
if values.Get("table") != "" {
|
||||
route = "/data"
|
||||
}
|
||||
if validateFreePanelRequest("POST", route, values) == nil {
|
||||
t.Fatal("invalid maintenance operation passed allowlist")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPHPQueueUsesTaskTypeAndExactBranch(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
tasks string
|
||||
pending bool
|
||||
}{
|
||||
{`[{"name":"upgrade[php-8.4]","status":"0"}]`, true},
|
||||
{`[{"name":"upgrade[php-8.4]","status":-1}]`, true},
|
||||
{`[{"name":"upgrade[php-8.5]","status":"0"},{"name":"upgrade[php-8.4]","status":"1"}]`, false},
|
||||
{`[]`, false},
|
||||
} {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.FormValue("search") != "execshell" || r.FormValue("table") != "tasks" {
|
||||
t.Error("aaPanel task search must use type rather than name")
|
||||
}
|
||||
_, _ = w.Write([]byte(`{"data":` + test.tasks + `}`))
|
||||
}))
|
||||
client := NewClient(server.URL, "test", false, time.Second)
|
||||
pending, err := client.PHPRuntimeUpdatePending(context.Background(), "8.4")
|
||||
server.Close()
|
||||
if err != nil || pending != test.pending {
|
||||
t.Fatalf("queue result=%v err=%v", pending, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type runtimeReplacementPanel struct {
|
||||
Interface
|
||||
calls []RuntimeSpec
|
||||
failVersion string
|
||||
}
|
||||
|
||||
func (p *runtimeReplacementPanel) RuntimeEnvironments(context.Context) ([]RuntimeEnvironment, error) {
|
||||
return []RuntimeEnvironment{{Name: "Python", Installed: []string{"3.12.0", "3.12.15"}}}, nil
|
||||
}
|
||||
func (p *runtimeReplacementPanel) ConfigureRuntime(_ context.Context, s RuntimeSpec) error {
|
||||
p.calls = append(p.calls, s)
|
||||
if s.Version == p.failVersion {
|
||||
return errors.New("injected launch failure")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func TestBrokerRuntimeReplacementRollsBackAndRejectsPathChanges(t *testing.T) {
|
||||
direct := &runtimeReplacementPanel{Interface: NewMock(), failVersion: "3.12.15"}
|
||||
server, err := newBrokerServer(t.TempDir(), t.TempDir(), "01234567890123456789012345678901", func(BrokerCredentials) Interface { return direct })
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
server.direct = direct
|
||||
old := RuntimeSpec{ProjectName: "sv0123456789", Runtime: "Python", Version: "3.12.0", Path: filepath.Join(server.tenantRoot, "sv0123456789"), RunPath: "/", RunUser: "sv0123456789", Port: 20501, ProcessLimit: 10}
|
||||
server.registry.Sites[1] = &managedSite{Runtime: &old}
|
||||
next := old
|
||||
next.Version = "3.12.15"
|
||||
next.Path = "/etc"
|
||||
if _, err = server.execute(context.Background(), brokerRequest{Operation: "replace_runtime", SiteID: 1, Runtime: &next}); err == nil {
|
||||
t.Fatal("unmanaged path accepted")
|
||||
}
|
||||
if len(direct.calls) != 0 {
|
||||
t.Fatal("invalid runtime triggered mutation")
|
||||
}
|
||||
next.Path = old.Path
|
||||
if _, err = server.execute(context.Background(), brokerRequest{Operation: "replace_runtime", SiteID: 1, Runtime: &next}); err == nil {
|
||||
t.Fatal("injected migration failure hidden")
|
||||
}
|
||||
if !reflect.DeepEqual(direct.calls, []RuntimeSpec{next, old}) {
|
||||
t.Fatalf("rollback calls=%#v", direct.calls)
|
||||
}
|
||||
if *server.registry.Sites[1].Runtime != old {
|
||||
t.Fatal("registry lost original runtime")
|
||||
}
|
||||
direct.failVersion = ""
|
||||
if _, err = server.execute(context.Background(), brokerRequest{Operation: "replace_runtime", SiteID: 1, Runtime: &next}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if *server.registry.Sites[1].Runtime != next {
|
||||
t.Fatal("registry did not commit target runtime")
|
||||
}
|
||||
// The old patch is still installed and must remain available for rollback.
|
||||
if _, err = server.execute(context.Background(), brokerRequest{Operation: "replace_runtime", SiteID: 1, Runtime: &old}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
before := len(direct.calls)
|
||||
if _, err = server.execute(context.Background(), brokerRequest{Operation: "replace_runtime", SiteID: 1, Runtime: &old}); err != nil || len(direct.calls) != before+1 {
|
||||
t.Fatal("same registered version must still repair a missing actual project")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRuntimeRemovalStopsListenerBeforeDeletingMetadata(t *testing.T) {
|
||||
listener, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer listener.Close()
|
||||
port := listener.Addr().(*net.TCPAddr).Port
|
||||
var calls []string
|
||||
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/python/StopProject/stype":
|
||||
calls = append(calls, "stop")
|
||||
_ = listener.Close()
|
||||
case "/project/python/RemoveProject/stype":
|
||||
calls = append(calls, "remove")
|
||||
default:
|
||||
t.Errorf("unexpected route: %s", r.URL.Path)
|
||||
}
|
||||
_, _ = w.Write([]byte(`{"status":true}`))
|
||||
}))
|
||||
defer server.Close()
|
||||
client := NewClient(server.URL, "test", false, time.Second)
|
||||
if err = client.RemoveRuntime(context.Background(), RuntimeSpec{Runtime: "Python", ProjectName: "sv0123456789", Port: port}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if strings.Join(calls, ",") != "stop,remove" {
|
||||
t.Fatalf("runtime deletion order = %v", calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRuntimeRemovalPreservesMetadataWhenStopDoesNotCloseListener(t *testing.T) {
|
||||
listener, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer listener.Close()
|
||||
port := listener.Addr().(*net.TCPAddr).Port
|
||||
removed := false
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
if r.URL.Path == "/project/python/RemoveProject/stype" {
|
||||
removed = true
|
||||
}
|
||||
_, _ = w.Write([]byte(`{"status":true}`))
|
||||
}))
|
||||
defer server.Close()
|
||||
client := NewClient(server.URL, "test", false, time.Second)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 150*time.Millisecond)
|
||||
defer cancel()
|
||||
if err = client.RemoveRuntime(ctx, RuntimeSpec{Runtime: "Python", ProjectName: "sv0123456789", Port: port}); err == nil {
|
||||
t.Fatal("runtime with a residual listener was removed")
|
||||
}
|
||||
if removed {
|
||||
t.Fatal("project metadata was deleted before its listener stopped")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRuntimeRemovalRetryRequiresAbsentRecordAndClosedPort(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
present, listening, invalid bool
|
||||
wantErr bool
|
||||
}{
|
||||
{"absent", false, false, false, false}, {"residual listener", false, true, false, true}, {"record remains", true, false, false, true}, {"unverifiable", false, false, true, true},
|
||||
} {
|
||||
t.Run(test.name, func(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
|
||||
if !test.listening {
|
||||
_ = listener.Close()
|
||||
} else {
|
||||
defer listener.Close()
|
||||
}
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path == "/project/python/RemoveProject/stype" {
|
||||
_, _ = w.Write([]byte(`{"status":false,"msg":"missing project"}`))
|
||||
return
|
||||
}
|
||||
if test.invalid {
|
||||
_, _ = w.Write([]byte(`{"status":false}`))
|
||||
return
|
||||
}
|
||||
items := []map[string]any{}
|
||||
if test.present {
|
||||
items = append(items, map[string]any{"name": "sv0123456789"})
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"data": items})
|
||||
}))
|
||||
defer server.Close()
|
||||
client := NewClient(server.URL, "test", false, time.Second)
|
||||
err = client.RemoveRuntime(context.Background(), RuntimeSpec{Runtime: "Python", ProjectName: "sv0123456789", Port: port})
|
||||
if (err != nil) != test.wantErr {
|
||||
t.Fatalf("removal error=%v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
type runtimeResetTestPanel struct {
|
||||
Interface
|
||||
proxies []string
|
||||
removed int
|
||||
}
|
||||
|
||||
func (p *runtimeResetTestPanel) RemoveManagedProxy(_ context.Context, name string) error {
|
||||
p.proxies = append(p.proxies, name)
|
||||
return nil
|
||||
}
|
||||
func (p *runtimeResetTestPanel) RemoveRuntime(context.Context, RuntimeSpec) error {
|
||||
p.removed++
|
||||
return nil
|
||||
}
|
||||
func TestRuntimeResetOnlyTouchesManagedSiteAndFixedProxy(t *testing.T) {
|
||||
direct := &runtimeResetTestPanel{Interface: NewMock()}
|
||||
server, e := newBrokerServer(t.TempDir(), t.TempDir(), "01234567890123456789012345678901", func(BrokerCredentials) Interface { return direct })
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
server.direct = direct
|
||||
old := RuntimeSpec{Runtime: "Node.js", ProjectName: "sv0123456789", Port: 20050}
|
||||
server.registry.Sites[3] = &managedSite{Domain: "host.example.com", Runtime: &old, Port: 20050, ProxyReady: true}
|
||||
for _, req := range []brokerRequest{{Operation: "reset_managed_runtime", SiteID: 9, Name: "host.example.com"}, {Operation: "reset_managed_runtime", SiteID: 3, Name: "outside.example.com"}} {
|
||||
if _, e = server.execute(context.Background(), req); e == nil {
|
||||
t.Fatal("unmanaged runtime reset accepted")
|
||||
}
|
||||
}
|
||||
if direct.removed != 0 || len(direct.proxies) != 0 {
|
||||
t.Fatal("unmanaged request mutated panel")
|
||||
}
|
||||
if _, e = server.execute(context.Background(), brokerRequest{Operation: "reset_managed_runtime", SiteID: 3, Name: "host.example.com"}); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if direct.removed != 1 || !reflect.DeepEqual(direct.proxies, []string{"host.example.com"}) || server.registry.Sites[3].Runtime != nil || server.registry.Sites[3].ProxyReady {
|
||||
t.Fatal("managed reset incomplete")
|
||||
}
|
||||
if _, e = server.execute(context.Background(), brokerRequest{Operation: "reset_managed_runtime", SiteID: 3, Name: "host.example.com"}); e != nil {
|
||||
t.Fatal("reset not idempotent", e)
|
||||
}
|
||||
if direct.removed != 1 {
|
||||
t.Fatal("repeated reset removed another project")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package panel
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"sea-vhost/internal/schedulerbridge"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type SystemScheduler interface {
|
||||
EnsureSystemScheduler(context.Context) (int64, error)
|
||||
}
|
||||
|
||||
func (c *BrokerClient) EnsureSystemScheduler(ctx context.Context) (int64, error) {
|
||||
v, e := c.operation(ctx, brokerRequest{Operation: "ensure_scheduler"})
|
||||
return v.ID, e
|
||||
}
|
||||
func (Mock) EnsureSystemScheduler(context.Context) (int64, error) { return 1, nil }
|
||||
func (c *Client) EnsureSystemScheduler(ctx context.Context) (int64, error) {
|
||||
raw, e := c.request(ctx, http.MethodPost, "/crontab", url.Values{"action": {"GetCrontab"}, "search": {schedulerbridge.CronName}})
|
||||
if e != nil {
|
||||
return 0, e
|
||||
}
|
||||
type task struct {
|
||||
ID int64 `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Body string `json:"sBody"`
|
||||
Status int `json:"status"`
|
||||
Type string `json:"type"`
|
||||
Where1 json.RawMessage `json:"where1"`
|
||||
}
|
||||
var rows []task
|
||||
if json.Unmarshal(raw, &rows) != nil {
|
||||
var envelope struct {
|
||||
Data []task `json:"data"`
|
||||
}
|
||||
if json.Unmarshal(raw, &envelope) != nil || envelope.Data == nil {
|
||||
return 0, errors.New("无法读取宝塔计划任务")
|
||||
}
|
||||
rows = envelope.Data
|
||||
}
|
||||
for _, v := range rows {
|
||||
if v.Name == schedulerbridge.CronName {
|
||||
if v.Body != schedulerbridge.Command || v.Type != "minute-n" || strings.Trim(string(v.Where1), `"`) != "1" {
|
||||
return 0, errors.New("同名计划任务配置不同,请在宝塔检查")
|
||||
}
|
||||
if v.Status != 1 {
|
||||
if _, e = c.call(ctx, http.MethodPost, "/crontab", url.Values{"action": {"set_cron_status"}, "id": {strconv.FormatInt(v.ID, 10)}}); e != nil {
|
||||
return 0, e
|
||||
}
|
||||
}
|
||||
return v.ID, nil
|
||||
}
|
||||
}
|
||||
v, e := c.call(ctx, http.MethodPost, "/crontab", url.Values{"action": {"AddCrontab"}, "name": {schedulerbridge.CronName}, "type": {"minute-n"}, "where1": {"1"}, "where_hour": {"0"}, "where_minute": {"0"}, "user": {"root"}, "urladdress": {"http://"}, "save_local": {"0"}, "notice": {"0"}, "notice_channel": {""}, "sType": {"toShell"}, "sBody": {schedulerbridge.Command}, "sName": {schedulerbridge.CronName}, "save": {"0"}, "backupTo": {"localhost"}})
|
||||
if e != nil {
|
||||
return 0, e
|
||||
}
|
||||
if v.ID < 1 {
|
||||
return 0, errors.New("宝塔未返回计划任务编号")
|
||||
}
|
||||
return v.ID, nil
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package panel
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"sea-vhost/internal/schedulerbridge"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestSystemSchedulerUsesOnlyFixedFreePanelTask(t *testing.T) {
|
||||
created := false
|
||||
mutations := 0
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.FormValue("action") {
|
||||
case "GetCrontab":
|
||||
if r.FormValue("search") != schedulerbridge.CronName {
|
||||
t.Error("unbounded cron lookup")
|
||||
}
|
||||
if !created {
|
||||
fmt.Fprint(w, `[]`)
|
||||
} else {
|
||||
json.NewEncoder(w).Encode([]map[string]any{{"id": 123, "name": schedulerbridge.CronName, "sBody": schedulerbridge.Command, "type": "minute-n", "where1": 1, "status": 1}})
|
||||
}
|
||||
case "AddCrontab":
|
||||
if r.FormValue("sBody") != schedulerbridge.Command || r.FormValue("user") != "root" || r.FormValue("where1") != "1" {
|
||||
t.Error("non-fixed scheduler mutation")
|
||||
}
|
||||
mutations++
|
||||
created = true
|
||||
fmt.Fprint(w, `{"status":true,"id":123}`)
|
||||
default:
|
||||
t.Error("unexpected native operation")
|
||||
}
|
||||
}))
|
||||
defer srv.Close()
|
||||
client := NewClient(srv.URL, "test-key", false, time.Second)
|
||||
for i := 0; i < 2; i++ {
|
||||
id, e := client.EnsureSystemScheduler(context.Background())
|
||||
if e != nil || id != 123 {
|
||||
t.Fatalf("scheduler id=%d error=%v", id, e)
|
||||
}
|
||||
}
|
||||
if mutations != 1 {
|
||||
t.Fatal("duplicate native system crons created")
|
||||
}
|
||||
if validateFreePanelRequest("POST", "/crontab", url.Values{"action": {"AddCrontab"}, "name": {schedulerbridge.CronName}, "sBody": {"touch /etc/pwned"}, "type": {"minute-n"}, "where1": {"1"}, "sType": {"toShell"}, "user": {"root"}}) == nil {
|
||||
t.Fatal("arbitrary root cron accepted")
|
||||
}
|
||||
if validateFreePanelRequest("POST", "/crontab", url.Values{"action": {"GetCrontab"}}) == nil {
|
||||
t.Fatal("unbounded native cron read accepted")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
package panel
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// ScopedExecution carries the controller's resource snapshot. It is never
|
||||
// persisted by the node. Native panel state remains authoritative for paths.
|
||||
type ScopedExecution struct {
|
||||
Request json.RawMessage `json:"request"`
|
||||
Registry json.RawMessage `json:"registry"`
|
||||
}
|
||||
type ScopedResult struct {
|
||||
Response json.RawMessage `json:"response"`
|
||||
Registry json.RawMessage `json:"registry"`
|
||||
}
|
||||
|
||||
func ExecuteScoped(ctx context.Context, direct Interface, tenantRoot string, in ScopedExecution) (ScopedResult, error) {
|
||||
var request brokerRequest
|
||||
decoder := json.NewDecoder(bytes.NewReader(in.Request))
|
||||
decoder.DisallowUnknownFields()
|
||||
if decoder.Decode(&request) != nil || decoder.Decode(&struct{}{}) != io.EOF {
|
||||
return ScopedResult{}, errors.New("invalid scoped operation")
|
||||
}
|
||||
var registry brokerRegistry
|
||||
decoder = json.NewDecoder(bytes.NewReader(in.Registry))
|
||||
decoder.DisallowUnknownFields()
|
||||
if decoder.Decode(®istry) != nil || decoder.Decode(&struct{}{}) != io.EOF || registry.Version != 1 || registry.Sites == nil || registry.FTP == nil || registry.Databases == nil {
|
||||
return ScopedResult{}, errors.New("invalid controller resource snapshot")
|
||||
}
|
||||
if !filepath.IsAbs(tenantRoot) || path.Clean(tenantRoot) != tenantRoot || tenantRoot == "/" {
|
||||
return ScopedResult{}, errors.New("invalid node resource root")
|
||||
}
|
||||
server := &BrokerServer{stateless: true, tenantRoot: tenantRoot, direct: direct, registry: registry, runtimeJobs: map[string]bool{}}
|
||||
for _, site := range registry.Sites {
|
||||
if site == nil || !brokerHostPattern.MatchString(site.ResourceName) || path.Clean(site.Path) != path.Join(tenantRoot, site.ResourceName) || site.RunUser != site.ResourceName || !validRunPath(site.RunPath) {
|
||||
return ScopedResult{}, errors.New("snapshot resource is outside the node namespace")
|
||||
}
|
||||
}
|
||||
for _, name := range registry.FTP {
|
||||
if !brokerHostPattern.MatchString(name) {
|
||||
return ScopedResult{}, errors.New("invalid scoped FTP identity")
|
||||
}
|
||||
}
|
||||
for _, name := range registry.Databases {
|
||||
if !brokerHostPattern.MatchString(name) {
|
||||
return ScopedResult{}, errors.New("invalid scoped database identity")
|
||||
}
|
||||
}
|
||||
if native, ok := direct.(interface {
|
||||
VerifyScopedResources(context.Context, string, json.RawMessage, json.RawMessage) error
|
||||
}); ok {
|
||||
if err := native.VerifyScopedResources(ctx, tenantRoot, in.Request, in.Registry); err != nil {
|
||||
return ScopedResult{}, err
|
||||
}
|
||||
} else if _, ok := direct.(*Client); ok {
|
||||
return ScopedResult{}, errors.New("native resource verification is unavailable")
|
||||
}
|
||||
result, err := server.execute(ctx, request)
|
||||
if err != nil {
|
||||
return ScopedResult{}, err
|
||||
}
|
||||
response, err := json.Marshal(result)
|
||||
if err != nil {
|
||||
return ScopedResult{}, err
|
||||
}
|
||||
snapshot, err := json.Marshal(server.registry)
|
||||
if err != nil {
|
||||
return ScopedResult{}, err
|
||||
}
|
||||
return ScopedResult{Response: response, Registry: snapshot}, nil
|
||||
}
|
||||
|
||||
// Verify only the resource touched by the operation, using real panel data.
|
||||
// A forged snapshot must not turn an unrelated panel site into a managed site.
|
||||
func (c *Client) VerifyScopedResources(ctx context.Context, root string, rawRequest, rawRegistry json.RawMessage) error {
|
||||
var request brokerRequest
|
||||
var registry brokerRegistry
|
||||
if json.Unmarshal(rawRequest, &request) != nil || json.Unmarshal(rawRegistry, ®istry) != nil {
|
||||
return errors.New("invalid resource proof")
|
||||
}
|
||||
if request.Operation=="delete_ftp"||request.Operation=="set_ftp_state" {
|
||||
name,ok:=registry.FTP[request.ID];if !ok||name!=request.Username{return errOutsideManaged}
|
||||
id,err:=c.lookupResourceID(ctx,"ftps",name);if err!=nil||id!=request.ID{return errors.New("native FTP identity does not match controller scope")};return nil
|
||||
}
|
||||
if request.Operation=="delete_database"||request.Operation=="database_size" {
|
||||
name,ok:=registry.Databases[request.ID];if !ok||name!=request.Name{return errOutsideManaged}
|
||||
id,err:=c.lookupResourceID(ctx,"databases",name);if err!=nil||id!=request.ID{return errors.New("native database identity does not match controller scope")};return nil
|
||||
}
|
||||
var target *managedSite
|
||||
var id int64
|
||||
if request.SiteID != 0 {
|
||||
id = request.SiteID
|
||||
} else if registry.Sites[request.ID] != nil {
|
||||
id = request.ID
|
||||
}
|
||||
if id != 0 {
|
||||
target = registry.Sites[id]
|
||||
}
|
||||
if target == nil && request.Runtime != nil {
|
||||
for key, site := range registry.Sites {
|
||||
if site.Path == request.Runtime.Path && site.Domain == request.Runtime.Domain {
|
||||
target = site
|
||||
id = key
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if target == nil || strings.HasPrefix(request.Operation, "create_") || request.Operation == "adopt_site" || request.Operation == "rollback_adoption" {
|
||||
return nil
|
||||
}
|
||||
// FTP/database IDs may equal a site ID. They are checked by their own name
|
||||
// registry inside the broker; do not accidentally compare unrelated tables.
|
||||
if strings.Contains(request.Operation, "ftp") || strings.Contains(request.Operation, "database") {
|
||||
return nil
|
||||
}
|
||||
actual, err := c.ListUnmanagedSites(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, site := range actual {
|
||||
if site.ID == id {
|
||||
if path.Clean(site.Path) != path.Clean(target.Path) || !strings.HasPrefix(path.Clean(site.Path)+"/", root+"/") || !strings.EqualFold(site.Domain, target.Domain) {
|
||||
return errors.New("native site does not match controller resource scope")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
// A repeated delete may already have removed the native record. The broker
|
||||
// still validates the exact registered domain and never deletes by path.
|
||||
if request.Operation == "delete_site" {
|
||||
return nil
|
||||
}
|
||||
return errors.New("managed native site is missing")
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package panel
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// Stateless mode retains only local panel credentials, never a platform
|
||||
// resource registry. The network gateway cannot reconfigure credentials.
|
||||
func(s *BrokerServer) EnableStateless()error{
|
||||
if s.direct==nil{return errors.New("local panel credentials must be configured before enabling the node broker")}
|
||||
s.stateless=true;s.registry=brokerRegistry{};return nil
|
||||
}
|
||||
func(s *BrokerServer) scopedOperations(w http.ResponseWriter,r *http.Request){
|
||||
var input ScopedExecution
|
||||
if !brokerDecode(w,r,&input){return}
|
||||
s.mu.Lock();defer s.mu.Unlock()
|
||||
result,err:=ExecuteScoped(r.Context(),s.direct,s.tenantRoot,input)
|
||||
if err!=nil{brokerWriteError(w,http.StatusUnprocessableEntity,safeBrokerError("节点面板操作失败",err));return}
|
||||
w.Header().Set("Content-Type","application/json");_ = json.NewEncoder(w).Encode(result)
|
||||
}
|
||||
Reference in new issue
Block a user