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,182 @@
|
||||
// Package executor is the node-side execution surface. It intentionally has
|
||||
// no import of store/service/httpapi and cannot schedule control-plane work.
|
||||
package executor
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"sea-vhost/internal/controlwire"
|
||||
"sea-vhost/internal/nodefiles"
|
||||
"sea-vhost/internal/panel"
|
||||
)
|
||||
|
||||
type Gateway struct {
|
||||
NodeID uint64
|
||||
TenantRoot string
|
||||
BrokerSocket string
|
||||
AgentSocket string
|
||||
InternalToken string
|
||||
// Direct is reserved for in-process tests; deployment always uses the
|
||||
// independent, unprivileged credential broker over a Unix socket.
|
||||
Direct panel.Interface
|
||||
mu sync.Mutex
|
||||
fileGate sync.Mutex
|
||||
}
|
||||
|
||||
var nodeHostPattern = regexp.MustCompile(`^sv[a-f0-9]{10}$`)
|
||||
var agentRoutes = map[string]bool{
|
||||
"/v1/database/phpmyadmin":true,
|
||||
"/v1/scheduler/configure":true,
|
||||
"/v1/schedule/execute":true,
|
||||
"/v1/ftp/disconnect":true,
|
||||
"/v1/site/startup": true,
|
||||
"/v1/site/settings": true, "/v1/site/log": true,
|
||||
"/v1/runtime/backups/prune": true,
|
||||
"/v1/prepare": true, "/v1/quarantine": true, "/v1/web-protection/apply": true, "/v1/web-protection/remove": true,
|
||||
"/v1/runtime/executable": true, "/v1/runtime/panel-state": true, "/v1/runtime/python/install": true,
|
||||
"/v1/resources/runtime/terminate": true, "/v1/run-path/release": true, "/v1/trash/prepare": true,
|
||||
"/v1/ftp/identity": true, "/v1/php/identity": true, "/v1/php/identity/start": true, "/v1/php/identity/stop": true, "/v1/php/identity/remove": true,
|
||||
"/v1/resources/usage": true, "/v1/resources/processes/terminate": true, "/v1/project/freeze-writes": true, "/v1/ftp/tls": true, "/v1/nginx/network": true,
|
||||
"/v1/lifecycle/backup": true, "/v1/lifecycle/backup/delete": true, "/v1/lifecycle/project/purge": true, "/v1/import/project": true,
|
||||
"/v1/database/access": true,
|
||||
"/v1/credentials/disconnect": true,
|
||||
"/v1/resources/limits": true,
|
||||
"/v1/lifecycle/backup/verify": true,
|
||||
"/v1/runtime/probe": true, "/v1/runtime/php/maintenance": true, "/v1/runtime/python/dependencies": true,
|
||||
}
|
||||
|
||||
func (g *Gateway) Handler() http.Handler {
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("GET /v1/status", func(w http.ResponseWriter, r *http.Request) {
|
||||
controlwire.Encode(w, 200, map[string]any{"nodeId": g.NodeID, "protocol": controlwire.Version, "businessDatabase": false, "taskScheduler": false})
|
||||
})
|
||||
mux.HandleFunc("POST /v1/panel", g.panel)
|
||||
mux.HandleFunc("POST /v1/files", g.files)
|
||||
mux.HandleFunc("POST /v1/isolation/", g.isolation)
|
||||
return controlwire.Authenticated(g.NodeID, mux)
|
||||
}
|
||||
|
||||
func (g *Gateway) files(w http.ResponseWriter, r *http.Request) {
|
||||
if !g.fileGate.TryLock() {
|
||||
http.Error(w, "node file transfer busy", 429)
|
||||
return
|
||||
}
|
||||
defer g.fileGate.Unlock()
|
||||
var q nodefiles.Request
|
||||
r.Body = http.MaxBytesReader(w, r.Body, nodefiles.MaxMessageBytes)
|
||||
decoder := json.NewDecoder(r.Body)
|
||||
decoder.DisallowUnknownFields()
|
||||
if decoder.Decode(&q) != nil || decoder.Decode(&struct{}{}) != io.EOF || !nodeHostPattern.MatchString(q.HostName) {
|
||||
http.Error(w, "invalid host file request", 400)
|
||||
return
|
||||
}
|
||||
controlwire.Encode(w, 200, nodefiles.Execute(filepath.Join(g.TenantRoot, q.HostName), q))
|
||||
}
|
||||
func (g *Gateway) panel(w http.ResponseWriter, r *http.Request) {
|
||||
var input panel.ScopedExecution
|
||||
if controlwire.Decode(w, r, &input) != nil {
|
||||
http.Error(w, "invalid scoped panel request", 400)
|
||||
return
|
||||
}
|
||||
g.mu.Lock()
|
||||
defer g.mu.Unlock()
|
||||
if g.Direct != nil {
|
||||
result, err := panel.ExecuteScoped(r.Context(), g.Direct, g.TenantRoot, input)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), 422)
|
||||
return
|
||||
}
|
||||
controlwire.Encode(w, 200, result)
|
||||
return
|
||||
}
|
||||
body, err := json.Marshal(input)
|
||||
if err != nil {
|
||||
http.Error(w, "invalid request", 400)
|
||||
return
|
||||
}
|
||||
g.forward(w, r, g.BrokerSocket, "/v1/scoped-operations", body)
|
||||
}
|
||||
func (g *Gateway) isolation(w http.ResponseWriter, r *http.Request) {
|
||||
route := strings.TrimPrefix(r.URL.Path, "/v1/isolation")
|
||||
if !agentRoutes[route] {
|
||||
http.Error(w, "operation is not in the node allowlist", 403)
|
||||
return
|
||||
}
|
||||
body, err := io.ReadAll(io.LimitReader(r.Body, controlwire.MaxEnvelopeBytes+1))
|
||||
if err != nil || len(body) > controlwire.MaxEnvelopeBytes {
|
||||
http.Error(w, "invalid node payload", 413)
|
||||
return
|
||||
}
|
||||
var value any
|
||||
if json.Unmarshal(body, &value) != nil || !validHostIdentities(value) {
|
||||
http.Error(w, "invalid node host scope", 400)
|
||||
return
|
||||
}
|
||||
g.forward(w, r, g.AgentSocket, route, body)
|
||||
}
|
||||
func validHostIdentities(value any) bool {
|
||||
switch v := value.(type) {
|
||||
case map[string]any:
|
||||
for key, item := range v {
|
||||
if strings.EqualFold(key, "hostName") {
|
||||
name, ok := item.(string)
|
||||
if !ok || !nodeHostPattern.MatchString(name) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
if !validHostIdentities(item) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
case []any:
|
||||
for _, item := range v {
|
||||
if !validHostIdentities(item) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
func (g *Gateway) forward(w http.ResponseWriter, r *http.Request, socket, route string, body []byte) {
|
||||
if socket == "" || g.InternalToken == "" {
|
||||
http.Error(w, "node execution service is not configured", 503)
|
||||
return
|
||||
}
|
||||
transport := &http.Transport{DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) {
|
||||
return (&net.Dialer{Timeout: 5 * time.Second}).DialContext(ctx, "unix", socket)
|
||||
}}
|
||||
defer transport.CloseIdleConnections()
|
||||
req, err := http.NewRequestWithContext(r.Context(), "POST", "http://unix"+route, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
http.Error(w, "invalid local operation", 400)
|
||||
return
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Authorization", "Bearer "+g.InternalToken)
|
||||
response, err := (&http.Client{Transport: transport, Timeout: 2 * time.Hour, CheckRedirect: func(*http.Request, []*http.Request) error { return errors.New("redirect denied") }}).Do(req)
|
||||
if err != nil {
|
||||
http.Error(w, "node local execution service unavailable", 502)
|
||||
return
|
||||
}
|
||||
defer response.Body.Close()
|
||||
output, err := io.ReadAll(io.LimitReader(response.Body, controlwire.MaxEnvelopeBytes+1))
|
||||
if err != nil || len(output) > controlwire.MaxEnvelopeBytes {
|
||||
http.Error(w, "node execution response exceeded limit", 502)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
w.WriteHeader(response.StatusCode)
|
||||
_, _ = w.Write(output)
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
package executor_test
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sea-vhost/internal/controlwire"
|
||||
"sea-vhost/internal/executor"
|
||||
"sea-vhost/internal/nodefiles"
|
||||
"sea-vhost/internal/panel"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
type testNode struct {
|
||||
server *httptest.Server
|
||||
client *http.Client
|
||||
id uint64
|
||||
credentials controlwire.Credentials
|
||||
sequence int
|
||||
}
|
||||
|
||||
func startNode(t *testing.T, id uint64, root string) *testNode {
|
||||
t.Helper()
|
||||
g := &executor.Gateway{NodeID: id, TenantRoot: root, Direct: panel.NewMock()}
|
||||
s := httptest.NewUnstartedServer(g.Handler())
|
||||
s.Config.ErrorLog = log.New(io.Discard, "", 0)
|
||||
credentials, identity, err := controlwire.Pair(id, "https://"+s.Listener.Addr().String())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s.TLS, err = controlwire.ServerTLS(identity)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s.StartTLS()
|
||||
t.Cleanup(s.Close)
|
||||
config, err := controlwire.ClientTLS(credentials)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
client := &http.Client{Transport: &http.Transport{TLSClientConfig: config}, Timeout: 10 * time.Second}
|
||||
t.Cleanup(client.CloseIdleConnections)
|
||||
return &testNode{server: s, client: client, id: id, credentials: credentials}
|
||||
}
|
||||
func (n *testNode) request(t *testing.T, route string, body any) (int, []byte) {
|
||||
t.Helper()
|
||||
raw, err := json.Marshal(body)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
n.sequence++
|
||||
r, err := controlwire.NewRequest("POST", n.server.URL, route, n.id, fmt.Sprintf("%032x", n.sequence), raw)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
response, err := n.client.Do(r)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
out, err := io.ReadAll(response.Body)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return response.StatusCode, out
|
||||
}
|
||||
|
||||
func TestTwoNodesArePairedAndStateless(t *testing.T) {
|
||||
rootA := filepath.ToSlash(t.TempDir())
|
||||
rootB := filepath.ToSlash(t.TempDir())
|
||||
for _, root := range []string{rootA, rootB} {
|
||||
if err := os.Mkdir(filepath.Join(root, "sv0123456789"), 0750); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
a := startNode(t, 2, rootA)
|
||||
b := startNode(t, 3, rootB)
|
||||
empty := json.RawMessage(`{"version":1,"sites":{},"ftp":{},"databases":{}}`)
|
||||
create := func(n *testNode, root, domain string) panel.ScopedResult {
|
||||
t.Helper()
|
||||
request, _ := json.Marshal(map[string]any{"operation": "create_site", "site": panel.SiteSpec{Name: "sv0123456789", Domain: domain, Path: root + "/sv0123456789", RunPath: "/public", Runtime: "PHP", Version: "8.4", RunUser: "sv0123456789", Port: 20000, ProcessLimit: 10}})
|
||||
status, raw := n.request(t, "/v1/panel", panel.ScopedExecution{Request: request, Registry: empty})
|
||||
if status != 200 {
|
||||
t.Fatalf("create: %d %s", status, raw)
|
||||
}
|
||||
var out panel.ScopedResult
|
||||
if json.Unmarshal(raw, &out) != nil {
|
||||
t.Fatal("invalid scoped result")
|
||||
}
|
||||
return out
|
||||
}
|
||||
first := create(a, rootA, "sv0123456789.a.example.com")
|
||||
second := create(b, rootB, "sv0123456789.b.example.com")
|
||||
if string(first.Response) != string(second.Response) {
|
||||
t.Fatalf("expected colliding native IDs across nodes: %s %s", first.Response, second.Response)
|
||||
}
|
||||
req, _ := json.Marshal(map[string]any{"operation": "set_site_state", "id": 1001, "name": "sv0123456789.a.example.com", "enabled": false})
|
||||
status, _ := b.request(t, "/v1/panel", panel.ScopedExecution{Request: req, Registry: first.Registry})
|
||||
if status == 200 {
|
||||
t.Fatal("node B accepted node A root snapshot")
|
||||
}
|
||||
status, _ = a.request(t, "/v1/panel", panel.ScopedExecution{Request: req, Registry: empty})
|
||||
if status == 200 {
|
||||
t.Fatal("node persisted the previous request registry")
|
||||
}
|
||||
status, _ = a.request(t, "/v1/isolation/v1/shell", map[string]any{"command": "id"})
|
||||
if status != 403 {
|
||||
t.Fatalf("shell route: %d", status)
|
||||
}
|
||||
status, _ = a.request(t, "/v1/isolation/v1/prepare", map[string]any{"hostName": "root"})
|
||||
if status != 400 {
|
||||
t.Fatalf("root identity: %d", status)
|
||||
}
|
||||
r, _ := controlwire.NewRequest("GET", b.server.URL, "/v1/status", b.id, strings.Repeat("a", 32), nil)
|
||||
if response, err := a.client.Do(r); err == nil {
|
||||
response.Body.Close()
|
||||
t.Fatal("node A credentials authenticated to node B")
|
||||
}
|
||||
r, _ = controlwire.NewRequest("GET", a.server.URL, "/v1/status", b.id, strings.Repeat("b", 32), nil)
|
||||
response, err := a.client.Do(r)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
response.Body.Close()
|
||||
if response.StatusCode != 403 {
|
||||
t.Fatal("destination identity not checked")
|
||||
}
|
||||
}
|
||||
|
||||
func TestFilesStayOnTargetNodeAndRejectReplay(t *testing.T) {
|
||||
rootA := t.TempDir()
|
||||
rootB := t.TempDir()
|
||||
host := "sv0123456789"
|
||||
for _, root := range []string{rootA, rootB} {
|
||||
if err := os.Mkdir(filepath.Join(root, host), 0750); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
a := startNode(t, 2, rootA)
|
||||
b := startNode(t, 3, rootB)
|
||||
status, raw := a.request(t, "/v1/files", nodefiles.Request{HostName: host, Operation: "write", Path: "marker.txt", Data: []byte("node-A-only")})
|
||||
if status != 200 {
|
||||
t.Fatalf("write %d %s", status, raw)
|
||||
}
|
||||
status, raw = b.request(t, "/v1/files", nodefiles.Request{HostName: host, Operation: "read", Path: "marker.txt"})
|
||||
if status != 200 || !strings.Contains(string(raw), "not_found") {
|
||||
t.Fatalf("cross-node read: %d %s", status, raw)
|
||||
}
|
||||
for _, name := range []string{"../marker.txt", "/etc/passwd", "a/../../x", "x\\..\\y"} {
|
||||
_, raw = a.request(t, "/v1/files", nodefiles.Request{HostName: host, Operation: "read", Path: name})
|
||||
if !strings.Contains(string(raw), "denied") {
|
||||
t.Fatalf("unsafe path accepted %q: %s", name, raw)
|
||||
}
|
||||
}
|
||||
body, _ := json.Marshal(nodefiles.Request{HostName: host, Operation: "stat", Path: "marker.txt"})
|
||||
r, _ := controlwire.NewRequest("POST", a.server.URL, "/v1/files", 2, strings.Repeat("e", 32), body)
|
||||
response, err := a.client.Do(r)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
response.Body.Close()
|
||||
r, _ = controlwire.NewRequest("POST", a.server.URL, "/v1/files", 2, strings.Repeat("e", 32), body)
|
||||
response, err = a.client.Do(r)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
response.Body.Close()
|
||||
if response.StatusCode != 409 {
|
||||
t.Fatalf("replay accepted: %d", response.StatusCode)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user