package isolation import ( "archive/tar" "bytes" "compress/gzip" "context" "encoding/json" "errors" "io" "net/http" "net/http/httptest" "os" "path/filepath" "strings" "testing" ) func lifecycleRequest(t *testing.T, agent Agent, route string, value any) *httptest.ResponseRecorder { t.Helper() body, err := json.Marshal(value) if err != nil { t.Fatal(err) } request := httptest.NewRequest(http.MethodPost, route, bytes.NewReader(body)) response := httptest.NewRecorder() agent.Handler().ServeHTTP(response, request) return response } func TestLifecycleBackupArchivesOnlyManagedProject(t *testing.T) { root, backupRoot := t.TempDir(), t.TempDir() hostName := "sv0123456789" projectRoot := filepath.Join(root, hostName) if err := os.MkdirAll(filepath.Join(projectRoot, "public"), 0700); err != nil { t.Fatal(err) } if err := os.WriteFile(filepath.Join(projectRoot, "public", "marker.txt"), []byte("tenant-marker"), 0600); err != nil { t.Fatal(err) } response := lifecycleRequest(t, Agent{Root: root, BackupRoot: backupRoot}, "/v1/lifecycle/backup", ProjectSpec{TenantID: 42, HostName: hostName, RunPath: "/", StorageBytes: 1024, ProcessLimit: 1}) if response.Code != http.StatusOK { t.Fatalf("backup status=%d body=%s", response.Code, response.Body.String()) } var backup ProjectBackup if err := json.Unmarshal(response.Body.Bytes(), &backup); err != nil { t.Fatal(err) } file, err := os.Open(backup.ArchivePath) if err != nil { t.Fatal(err) } defer file.Close() gzipReader, err := gzip.NewReader(file) if err != nil { t.Fatal(err) } tarReader := tar.NewReader(gzipReader) found := false for { header, nextErr := tarReader.Next() if errors.Is(nextErr, io.EOF) { break } if nextErr != nil { t.Fatal(nextErr) } if header.Name == hostName+"/public/marker.txt" { found = true } if strings.Contains(header.Name, "..") || strings.HasPrefix(header.Name, "/") { t.Fatalf("unsafe archive path %q", header.Name) } } if !found { t.Fatal("managed marker was not archived") } } func TestLifecyclePurgeIsIdempotentAndRemovesIdentity(t *testing.T) { root := t.TempDir() hostName := "sv0123456789" projectRoot := filepath.Join(root, hostName) if err := os.MkdirAll(projectRoot, 0700); err != nil { t.Fatal(err) } commands := make([]string, 0, 4) agent := Agent{Root: root, runCommand: func(_ context.Context, name string, args ...string) error { commands = append(commands, name+" "+strings.Join(args, " ")) if name == "id" || name == "getent" { return nil } return nil }} spec := ProjectSpec{TenantID: 42, HostName: hostName, RunPath: "/", StorageBytes: 1024, ProcessLimit: 1} response := lifecycleRequest(t, agent, "/v1/lifecycle/project/purge", spec) if response.Code != http.StatusOK { t.Fatalf("purge status=%d body=%s", response.Code, response.Body.String()) } if _, err := os.Stat(projectRoot); !errors.Is(err, os.ErrNotExist) { t.Fatalf("project directory still exists: %v", err) } joined := strings.Join(commands, "\n") if !strings.Contains(joined, "userdel "+hostName) || !strings.Contains(joined, "groupdel "+hostName) { t.Fatalf("identity cleanup missing: %s", joined) } commands = nil agent.runCommand = func(_ context.Context, name string, args ...string) error { commands = append(commands, name+" "+strings.Join(args, " ")) return errors.New("missing") } response = lifecycleRequest(t, agent, "/v1/lifecycle/project/purge", spec) if response.Code != http.StatusOK || strings.Contains(strings.Join(commands, "\n"), "userdel") { t.Fatalf("retry was not idempotent: status=%d commands=%v", response.Code, commands) } } func TestAgentHealthCheck(t *testing.T) { request := httptest.NewRequest(http.MethodGet, "/healthz", nil) response := httptest.NewRecorder() Agent{}.Handler().ServeHTTP(response, request) if response.Code != http.StatusOK || !strings.Contains(response.Body.String(), `"status":"ok"`) { t.Fatalf("unexpected health response: %d %s", response.Code, response.Body.String()) } } func TestAgentMutationRequiresInternalToken(t *testing.T) { agent := Agent{InternalToken: strings.Repeat("i", 32)} request := httptest.NewRequest(http.MethodPost, "/v1/prepare", strings.NewReader(`{}`)) response := httptest.NewRecorder() agent.Handler().ServeHTTP(response, request) if response.Code != http.StatusUnauthorized { t.Fatalf("unauthenticated mutation status = %d, want 401", response.Code) } } func TestHostIdentityHasNoUsableHomeDirectory(t *testing.T) { commands := make([]string, 0, 2) agent := Agent{runCommand: func(_ context.Context, name string, args ...string) error { commands = append(commands, name+" "+strings.Join(args, " ")) if name == "getent" || name == "id" { return errors.New("not found") } return nil }} if err := agent.ensureHostIdentity(context.Background(), ProjectSpec{HostName: "sv0123456789"}, "/www/wwwroot/seavHost/vHost/sv0123456789"); err != nil { t.Fatal(err) } joined := strings.Join(commands, "\n") if !strings.Contains(joined, "usermod --gid sv0123456789 --groups sv0123456789 --home /nonexistent --shell /usr/sbin/nologin sv0123456789") { t.Fatalf("identity did not use the disabled home: %s", joined) } if strings.Contains(joined, "--home /www/wwwroot") { t.Fatalf("project root was used as an OS home: %s", joined) } if !strings.Contains(joined, "useradd --gid sv0123456789 --home-dir /nonexistent --no-create-home --shell /usr/sbin/nologin sv0123456789") { t.Fatalf("identity was not allocated from the normal UID range: %s", joined) } if strings.Contains(joined, "useradd --system") { t.Fatalf("identity used a system UID rejected by aaPanel Python: %s", joined) } } func TestPreparePanelRuntimeGrantsOnlyNodePIDDirectoryAccess(t *testing.T) { root := filepath.Join(t.TempDir(), "wwwroot") pidRoot := filepath.Join(t.TempDir(), "pids") hostName := "sv0123456789" if err := os.MkdirAll(filepath.Join(root, hostName), 0770); err != nil { t.Fatal(err) } if err := os.MkdirAll(pidRoot, 0755); err != nil { t.Fatal(err) } commands := make([]string, 0, 2) agent := Agent{ Root: root, NodePIDRoot: pidRoot, lookupUID: func(string) (uint64, error) { return 1001, nil }, runCommand: func(_ context.Context, name string, args ...string) error { commands = append(commands, name+" "+strings.Join(args, " ")) return nil }, } spec := PanelRuntimeSpec{Project: ProjectSpec{TenantID: 1, HostName: hostName, RunPath: "/", StorageBytes: 1024, ProcessLimit: 1}, Runtime: "Node.js"} body, _ := json.Marshal(spec) response := httptest.NewRecorder() agent.Handler().ServeHTTP(response, httptest.NewRequest(http.MethodPost, "/v1/runtime/panel-state", bytes.NewReader(body))) if response.Code != http.StatusOK { t.Fatalf("prepare status = %d, body = %s", response.Code, response.Body.String()) } joined := strings.Join(commands, "\n") if !strings.Contains(joined, "chmod +t "+pidRoot) || !strings.Contains(joined, "setfacl -m u:"+hostName+":rwx,m::rwx "+pidRoot) { t.Fatalf("unexpected Node.js compatibility commands: %s", joined) } if strings.Contains(joined, filepath.Join(root, hostName)+" ") { t.Fatalf("Node.js compatibility grant escaped the fixed PID directory: %s", joined) } } func TestPreparePanelRuntimeRejectsLegacyPythonUID(t *testing.T) { root := filepath.Join(t.TempDir(), "wwwroot") hostName := "sv0123456789" if err := os.MkdirAll(filepath.Join(root, hostName), 0770); err != nil { t.Fatal(err) } agent := Agent{Root: root, lookupUID: func(string) (uint64, error) { return 999, nil }} spec := PanelRuntimeSpec{Project: ProjectSpec{TenantID: 1, HostName: hostName, RunPath: "/", StorageBytes: 1024, ProcessLimit: 1}, Runtime: "Python", Version: "3.12.0", ProjectName: hostName} body, _ := json.Marshal(spec) response := httptest.NewRecorder() agent.Handler().ServeHTTP(response, httptest.NewRequest(http.MethodPost, "/v1/runtime/panel-state", bytes.NewReader(body))) if response.Code != http.StatusPreconditionFailed || !strings.Contains(response.Body.String(), "legacy host UID") { t.Fatalf("legacy Python UID status = %d, body = %s", response.Code, response.Body.String()) } } func TestPreparePanelRuntimeCreatesIsolatedPythonVirtualEnvironment(t *testing.T) { root := filepath.Join(t.TempDir(), "wwwroot") managerRoot := filepath.Join(t.TempDir(), "versions") hostName := "sv0123456789" projectRoot := filepath.Join(root, hostName) basePython := filepath.Join(managerRoot, "3.12.0", "bin", "python3") if err := os.MkdirAll(projectRoot, 0770); err != nil { t.Fatal(err) } if err := os.MkdirAll(filepath.Dir(basePython), 0755); err != nil { t.Fatal(err) } if err := os.WriteFile(basePython, []byte("test"), 0755); err != nil { t.Fatal(err) } commands := make([]string, 0, 3) agent := Agent{ Root: root, FileOwner: "sea-vhost", PythonManagerRoot: managerRoot, lookupUID: func(string) (uint64, error) { return 1001, nil }, runCommand: func(_ context.Context, name string, args ...string) error { commands = append(commands, name+" "+strings.Join(args, " ")) if name == "runuser" { venvPath := args[len(args)-1] if err := os.MkdirAll(filepath.Join(venvPath, "bin"), 0770); err != nil { return err } return os.WriteFile(filepath.Join(venvPath, "bin", "python3"), []byte("test"), 0755) } return nil }, } spec := PanelRuntimeSpec{Project: ProjectSpec{TenantID: 1, HostName: hostName, RunPath: "/", StorageBytes: 1024, ProcessLimit: 1}, Runtime: "Python", Version: "3.12.0", ProjectName: hostName} body, _ := json.Marshal(spec) response := httptest.NewRecorder() agent.Handler().ServeHTTP(response, httptest.NewRequest(http.MethodPost, "/v1/runtime/panel-state", bytes.NewReader(body))) if response.Code != http.StatusOK { t.Fatalf("prepare status = %d, body = %s", response.Code, response.Body.String()) } venvPath := filepath.Join(projectRoot, ".sea-runtime", "python", hostName+"-3.12.0") joined := strings.Join(commands, "\n") if !strings.Contains(joined, "runuser -u "+hostName+" -- "+basePython+" -m venv --system-site-packages "+venvPath) { t.Fatalf("Python venv command was not confined: %s", joined) } if !strings.Contains(joined, "-xdev ( -type d -o -type f ) -exec setfacl -m u:www:---") { t.Fatalf("Python ACL command did not exclude virtualenv symlinks: %s", joined) } } func TestFreezeWritesReclaimsOwnershipAndRemovesRuntimeWriteAccess(t *testing.T) { root := filepath.Join(t.TempDir(), "wwwroot") hostName := "sv0123456789" projectRoot := filepath.Join(root, hostName) if err := os.MkdirAll(projectRoot, 0770); err != nil { t.Fatal(err) } commands := make([]string, 0, 5) agent := Agent{Root: root, FileOwner: "sea-vhost", PurePWBinary: filepath.Join(t.TempDir(), "bin", "pure-pw"), runCommand: func(_ context.Context, name string, args ...string) error { commands = append(commands, name+" "+strings.Join(args, " ")) return nil }} spec := ProjectSpec{TenantID: 1, HostName: hostName, RunPath: "/", StorageBytes: 1024, ProcessLimit: 1} body, _ := json.Marshal(spec) response := httptest.NewRecorder() agent.Handler().ServeHTTP(response, httptest.NewRequest(http.MethodPost, "/v1/project/freeze-writes", bytes.NewReader(body))) if response.Code != http.StatusOK { t.Fatalf("freeze status = %d, body = %s", response.Code, response.Body.String()) } joined := strings.Join(commands, "\n") for _, expected := range []string{ "chown -h sea-vhost:" + hostName, "chmod u+rwx,g+rX,g-w,o-rwx", "chmod u+rw,g+r,g-w,o-rwx", "d:g::r-x,d:m::r-x", "u:www:r--,m::r--", } { if !strings.Contains(joined, expected) { t.Fatalf("freeze commands missing %q: %s", expected, joined) } } if !strings.Contains(joined, "! -name .user.ini") { t.Fatalf("freeze commands did not preserve immutable .user.ini: %s", joined) } } func TestFreezeWritesKeepsRuntimeDirectoryPrivate(t *testing.T) { root := filepath.Join(t.TempDir(), "wwwroot") hostName := "sv0123456789" projectRoot := filepath.Join(root, hostName) if err := os.MkdirAll(filepath.Join(projectRoot, ".sea-runtime"), 0770); err != nil { t.Fatal(err) } commands := make([]string, 0, 6) agent := Agent{Root: root, PurePWBinary: filepath.Join(t.TempDir(), "bin", "pure-pw"), runCommand: func(_ context.Context, name string, args ...string) error { commands = append(commands, name+" "+strings.Join(args, " ")) return nil }} spec := ProjectSpec{TenantID: 1, HostName: hostName, RunPath: "/", StorageBytes: 1024, ProcessLimit: 1} body, _ := json.Marshal(spec) response := httptest.NewRecorder() agent.Handler().ServeHTTP(response, httptest.NewRequest(http.MethodPost, "/v1/project/freeze-writes", bytes.NewReader(body))) if response.Code != http.StatusOK { t.Fatalf("freeze status = %d, body = %s", response.Code, response.Body.String()) } joined := strings.Join(commands, "\n") if !strings.Contains(joined, filepath.Join(projectRoot, ".sea-runtime")+" -xdev -exec setfacl -m u:www:---") { t.Fatalf("freeze did not restore the runtime privacy ACL: %s", joined) } } func TestBandwidthMeterCountsOnlyCompleteCurrentMonthLines(t *testing.T) { root := t.TempDir() logPath := filepath.Join(root, "example.test.log") initial := "127.0.0.1 - - [30/Sep/2026:23:59:59 +0800] \"GET /old HTTP/1.1\" 200 90 \"-\" \"test\"\n" + "127.0.0.1 - - [18/Oct/2026:10:00:00 +0800] \"GET / HTTP/1.1\" 200 120 \"-\" \"test\"\n" if err := os.WriteFile(logPath, []byte(initial), 0600); err != nil { t.Fatal(err) } cursor, err := measureDomainLog(logPath, trafficCursor{Month: "2026-10"}, "2026-10") if err != nil || cursor.Bytes != 120 { t.Fatalf("cursor=%+v err=%v", cursor, err) } completeOffset := cursor.Offset file, err := os.OpenFile(logPath, os.O_APPEND|os.O_WRONLY, 0600) if err != nil { t.Fatal(err) } _, _ = file.WriteString("127.0.0.1 - - [18/Oct/2026:10:00:01 +0800] \"GET /next HTTP/1.1\" 200 45") _ = file.Close() cursor, err = measureDomainLog(logPath, cursor, "2026-10") if err != nil || cursor.Bytes != 120 || cursor.Offset != completeOffset { t.Fatalf("partial cursor=%+v err=%v", cursor, err) } file, _ = os.OpenFile(logPath, os.O_APPEND|os.O_WRONLY, 0600) _, _ = file.WriteString(" \"-\" \"test\"\n") _ = file.Close() cursor, err = measureDomainLog(logPath, cursor, "2026-10") if err != nil || cursor.Bytes != 165 { t.Fatalf("completed cursor=%+v err=%v", cursor, err) } } func TestMeasureProjectStorageCountsManagedTreeWithoutFollowingSymlinks(t *testing.T) { root := t.TempDir() if err := os.MkdirAll(filepath.Join(root, "private", "nested"), 0700); err != nil { t.Fatal(err) } if err := os.WriteFile(filepath.Join(root, "index.html"), []byte("12345"), 0600); err != nil { t.Fatal(err) } if err := os.WriteFile(filepath.Join(root, "private", "nested", "data.bin"), []byte("1234567"), 0600); err != nil { t.Fatal(err) } outside := filepath.Join(t.TempDir(), "outside.bin") if err := os.WriteFile(outside, make([]byte, 1024*1024), 0600); err != nil { t.Fatal(err) } link := filepath.Join(root, "outside-link") if err := os.Symlink(outside, link); err != nil { t.Skipf("symlink creation is unavailable: %v", err) } usage, err := measureProjectStorage(root) if err != nil { t.Fatal(err) } linkInfo, err := os.Lstat(link) if err != nil { t.Fatal(err) } want := uint64(12 + linkInfo.Size()) if usage != want { t.Fatalf("usage = %d, want %d", usage, want) } } func TestMeasureProjectStorageRejectsSymlinkRoot(t *testing.T) { realRoot := t.TempDir() link := filepath.Join(t.TempDir(), "host-link") if err := os.Symlink(realRoot, link); err != nil { t.Skipf("symlink creation is unavailable: %v", err) } if _, err := measureProjectStorage(link); err == nil { t.Fatal("symlink project root was accepted") } } func TestPHPAdapterUsesPrivateSocketWithoutDuplicatingAAPanelLocation(t *testing.T) { adapter := renderPHPNginxAdapter("/run/sea-vhost-php/sv0123456789.sock") if strings.Contains(adapter, "location ~ [^/]\\.php(/|$)") { t.Fatal("adapter duplicates aaPanel's shared PHP location") } if !strings.Contains(adapter, "location ~ ^.+\\.php(?:/|$)") || !strings.Contains(adapter, "fastcgi_pass unix:/run/sea-vhost-php/sv0123456789.sock;") { t.Fatalf("adapter does not route PHP to the private socket:\n%s", adapter) } } func TestPHPConfigRunsMasterAsPreselectedHostIdentity(t *testing.T) { paths := phpIdentityPaths{ config: "/var/lib/sea-vhost-agent/php/sv0123456789.conf", pid: "/run/sea-vhost-php/sv0123456789/php-fpm.pid", socket: "/run/sea-vhost-php/sv0123456789/php-fpm.sock", } spec := PHPIdentitySpec{ Project: ProjectSpec{HostName: "sv0123456789"}, SiteName: "sv0123456789", ProcessLimit: 4, } config := renderPHPIdentityConfig(spec, "/www/wwwroot/seavHost/vHost/sv0123456789", "/www/wwwroot/seavHost/vHost/sv0123456789/.sea-runtime/php", paths) for _, forbidden := range []string{"listen.owner", "listen.group"} { if strings.Contains(config, forbidden) { t.Fatalf("non-root PHP master config contains root-only directive %q", forbidden) } } for _, required := range []string{paths.pid, paths.socket, "/.sea-runtime/php/fpm-error.log", "user = sv0123456789", "group = sv0123456789"} { if !strings.Contains(config, required) { t.Fatalf("PHP config is missing %q:\n%s", required, config) } } } func TestEnsureProjectRunDirectoryCreatesOnlyPhysicalChildren(t *testing.T) { root := t.TempDir() if err := ensureProjectRunDirectory(root, "/apps/web/public"); err != nil { t.Fatal(err) } if info, err := os.Lstat(filepath.Join(root, "apps", "web", "public")); err != nil || !info.IsDir() { t.Fatalf("run directory was not created: info=%v err=%v", info, err) } if err := os.Symlink(filepath.Join(root, "apps"), filepath.Join(root, "linked")); err == nil { if err = ensureProjectRunDirectory(root, "/linked/public"); err == nil { t.Fatal("symlinked run directory was accepted") } } for _, unsafe := range []string{"/../etc", "/public/../etc", "/has space", `C:\\Windows`} { if ensureProjectRunDirectory(root, unsafe) == nil { t.Fatalf("unsafe run path %q was accepted", unsafe) } } } func TestFindProjectUserINIFilesIncludesNestedFilesAndRejectsSymlinks(t *testing.T) { root := t.TempDir() public := filepath.Join(root, "public") if err := os.MkdirAll(public, 0750); err != nil { t.Fatal(err) } for _, name := range []string{filepath.Join(root, ".user.ini"), filepath.Join(public, ".user.ini")} { if err := os.WriteFile(name, []byte("open_basedir=/tmp"), 0644); err != nil { t.Fatal(err) } } files, err := findProjectUserINIFiles(root, 4) if err != nil || len(files) != 2 { t.Fatalf("files=%#v err=%v", files, err) } if err = os.Remove(filepath.Join(public, ".user.ini")); err != nil { t.Fatal(err) } if err = os.Symlink(filepath.Join(root, ".user.ini"), filepath.Join(public, ".user.ini")); err != nil { t.Skipf("symlink creation is unavailable: %v", err) } if _, err = findProjectUserINIFiles(root, 4); err == nil { t.Fatal("symlinked .user.ini was accepted") } } func TestReleaseRunPathRemovesOnlyExactIsolationFile(t *testing.T) { root := filepath.Join(t.TempDir(), "wwwroot") hostName := "sv0123456789" runDirectory := filepath.Join(root, hostName, "apps", "web") if err := os.MkdirAll(runDirectory, 0770); err != nil { t.Fatal(err) } userINI := filepath.Join(runDirectory, ".user.ini") source := filepath.Join(runDirectory, "index.php") if err := os.WriteFile(userINI, []byte("open_basedir=/tmp"), 0644); err != nil { t.Fatal(err) } if err := os.WriteFile(source, []byte("