Files
vHost/backend/internal/isolation/runtime_maintenance_test.go
T

177 lines
6.7 KiB
Go

package isolation
import (
"bytes"
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"time"
)
func TestRuntimeMaintenanceRejectsUntrustedInputs(t *testing.T) {
agent := Agent{InternalToken: "internal-test-token"}
for _, test := range []struct {
route, body string
status int
}{
{"/v1/runtime/php/maintenance", `{"branch":"8.4","action":"inspect"}`, 401},
{"/v1/runtime/php/maintenance", `{"branch":"../../etc","action":"restore","jobId":1}`, 400},
{"/v1/runtime/php/maintenance", `{"branch":"8.4","action":"restore","jobId":0}`, 400},
{"/v1/runtime/php/maintenance", `{"branch":"8.4","action":"shell","jobId":1}`, 400},
{"/v1/runtime/php/maintenance", `{"branch":"8.4","action":"inspect"}{}`, 400},
{"/v1/runtime/probe", `{"project":{"hostName":"root","tenantId":1,"runPath":"/"},"projectName":"sv0123456789","runtime":"PHP","version":"8.4"}`, 400},
{"/v1/runtime/python/dependencies", `{"spec":{"project":{"hostName":"sv0123456789"},"runtime":"Python","projectName":"../../etc","version":"3.12.15"},"previous":"3.12.0"}`, 400},
} {
r := httptest.NewRequest(http.MethodPost, test.route, bytes.NewBufferString(test.body))
if test.status != 401 {
r.Header.Set("Authorization", "Bearer internal-test-token")
}
w := httptest.NewRecorder()
agent.Handler().ServeHTTP(w, r)
if w.Code != test.status {
t.Fatalf("%s got %d: %s", test.route, w.Code, w.Body.String())
}
}
}
func TestDependencyExportRemainsBounded(t *testing.T) {
var buffer cappedDependencyBuffer
payload := bytes.Repeat([]byte("x"), (1<<20)+100)
n, err := buffer.Write(payload)
if err != nil || n != len(payload) || len(buffer.data) != 1<<20 || !buffer.exceeded {
t.Fatal("untrusted dependency export was not bounded")
}
_, _ = buffer.Write(payload)
if len(buffer.data) != 1<<20 {
t.Fatal("buffer grew beyond its limit")
}
}
func TestTenantMaintenanceDoesNotInheritAgentSecrets(t *testing.T) {
t.Setenv("SEA_INTERNAL_AUTH_TOKEN", "canary-not-for-tenant")
t.Setenv("SEA_PANEL_API_KEY", "canary-not-for-tenant")
cmd := tenantMaintenanceCommand(context.Background(), "sv0123456789", "/usr/bin/stat", "/proc/123/exe")
if len(cmd.Env) == 0 || strings.Contains(strings.Join(cmd.Env, "\n"), "canary") || strings.Contains(strings.Join(cmd.Env, "\n"), "SEA_") {
t.Fatal("tenant command inherited privileged environment")
}
if !strings.Contains(strings.Join(cmd.Args, " "), "-u sv0123456789 -- /usr/bin/stat") {
t.Fatal("tenant command did not drop UID")
}
}
func TestDependencyRestoreDoesNotReopenPrivilegedStdin(t *testing.T) {
cmd := pythonDependencyRestoreCommand(context.Background(), "sv0123456789", "/host/private/venv/bin/python3")
joined := strings.Join(cmd.Args, " ")
if strings.Contains(joined, "/dev/stdin") || !strings.Contains(joined, "sys.stdin.buffer.read") || !strings.Contains(joined, "0o600") || cmd.Args[len(cmd.Args)-1] != filepath.Dir(filepath.Dir("/host/private/venv/bin/python3")) {
t.Fatal("dependency restore must create an own-UID private requirements file")
}
}
func TestProjectACLProtectsNestedRuntimeDirectories(t *testing.T) {
root := t.TempDir()
paths := []string{filepath.Join(root, "public", ".sea-runtime"), filepath.Join(root, "apps", "web", ".sea-runtime")}
for _, path := range paths {
if err := os.MkdirAll(path, 0700); err != nil {
t.Fatal(err)
}
}
var commands []string
agent := Agent{runCommand: func(_ context.Context, name string, args ...string) error {
commands = append(commands, name+" "+strings.Join(args, " "))
return nil
}}
if err := agent.applyProjectACL(context.Background(), root, "sea-vhost"); err != nil {
t.Fatal(err)
}
if !strings.Contains(strings.Join(commands, "\n"), "-type f -perm /111 -exec setfacl -m u:www:r--,m::rwx,o::---") {
t.Fatal("ACL repair would revoke execution from tenant binaries")
}
for _, path := range paths {
if !strings.Contains(strings.Join(commands, "\n"), "find "+path+" -xdev ( -type d -o -type f ) -exec setfacl -m u:www:---") {
t.Fatalf("nested runtime was not protected: %s", path)
}
}
}
func TestSharedPythonModesAreReadableButNotTenantWritable(t *testing.T) {
root := t.TempDir()
var commands []string
agent := Agent{runCommand: func(_ context.Context, name string, args ...string) error {
commands = append(commands, name+" "+strings.Join(args, " "))
return nil
}}
if err := agent.normalizeSharedPythonAccess(context.Background(), root); err != nil {
t.Fatal(err)
}
joined := strings.Join(commands, "\n")
for _, expected := range []string{"chown -hR root:root " + root, "-type d -exec chmod a+rx,go-w", "-type f -exec chmod a+rX,go-w"} {
if !strings.Contains(joined, expected) {
t.Fatalf("shared interpreter access missing %s", expected)
}
}
if strings.Contains(joined, "chmod -R") || strings.Contains(joined, "find -L") {
t.Fatal("shared interpreter repair must not follow symlinks")
}
}
func TestPythonRepairDoesNotRewriteUnmanagedInstallations(t *testing.T) {
root := t.TempDir()
calls := 0
agent := Agent{runCommand: func(context.Context, string, ...string) error { calls++; return nil }}
if err := agent.repairManagedPythonAccess(context.Background(), root, "3.12.15"); err != nil || calls != 0 {
t.Fatal("unmanaged interpreter was modified")
}
if err := os.WriteFile(filepath.Join(root, ".sea-vhost-runtime"), []byte("3.12.0"), 0600); err != nil {
t.Fatal(err)
}
if err := agent.repairManagedPythonAccess(context.Background(), root, "3.12.15"); err == nil || calls != 0 {
t.Fatal("mismatched marker accepted")
}
}
func TestSnapshotExpiryPreservesUnresolvedAndRecentBackups(t *testing.T) {
base := t.TempDir()
old := time.Now().Add(-15 * 24 * time.Hour)
for _, test := range []struct {
id string
sealed, stale bool
}{{"1", true, true}, {"2", false, true}, {"3", true, false}} {
root := filepath.Join(base, "runtime", "php", "84", test.id)
if err := os.MkdirAll(root, 0700); err != nil {
t.Fatal(err)
}
manifest, _ := json.Marshal(PHPState{Version: "8.4.25", BackupPath: root})
if err := os.WriteFile(filepath.Join(root, "manifest.json"), manifest, 0600); err != nil {
t.Fatal(err)
}
if test.sealed {
marker := filepath.Join(root, "retention-start")
if err := os.WriteFile(marker, []byte("completed"), 0600); err != nil {
t.Fatal(err)
}
if test.stale {
if err := os.Chtimes(marker, old, old); err != nil {
t.Fatal(err)
}
}
}
}
ctx, cancel := context.WithCancel(context.Background())
cancel()
Agent{BackupRoot: base}.RunRuntimeBackupExpiry(ctx)
for _, test := range []struct {
id string
removed bool
}{{"1", true}, {"2", false}, {"3", false}} {
_, err := os.Stat(filepath.Join(base, "runtime", "php", "84", test.id))
if os.IsNotExist(err) != test.removed {
t.Fatalf("snapshot %s expiry mismatch: %v", test.id, err)
}
}
}