feat(nodes): add remote Xray and panel restart actions (#6970)

An operator running a master with sub-nodes could probe or update a node from the Nodes page but had to log in to the node, or SSH into it, to restart Xray or the panel (#6937).

Add Restart Xray and Restart panel to the node actions, behind a confirmation. Xray restarts through the node runtime; the panel restart is a new Remote call that the node accepts with node-admin credentials, the authority that already covers updatePanel. Both are refused for a disabled node.
This commit is contained in:
Hamed
2026-11-24 16:55:08 +03:30
committed by GitHub
parent a07ed97aa1
commit e409ed7244
40 changed files with 941 additions and 4 deletions
+3 -2
View File
@@ -49,7 +49,7 @@ func (a *APIController) checkAPIAuth(c *gin.Context) {
}
}
// Verified mTLS keeps its historical node-sync identity. Only an explicit
// node-admin bearer elevates it to software-update authority.
// node-admin bearer elevates it to panel-administration authority.
if c.Request.TLS != nil && len(c.Request.TLS.VerifiedChains) > 0 {
scope := model.ApiScopeNodeSync
if matchedScope == model.ApiScopeNodeAdmin {
@@ -127,7 +127,8 @@ var nodeSyncScopeAllow = map[string]map[string]struct{}{
}
var nodeAdminScopeAllow = map[string]map[string]struct{}{
"/server/updatePanel": {http.MethodPost: {}},
"/server/updatePanel": {http.MethodPost: {}},
"/setting/restartPanel": {http.MethodPost: {}},
}
func scopeAllows(allow map[string]map[string]struct{}, path, method string) bool {
+30
View File
@@ -41,6 +41,8 @@ func (a *NodeController) initRouter(g *gin.RouterGroup) {
g.POST("/inbounds", a.inbounds)
g.POST("/probe/:id", a.probe)
g.POST("/updatePanel", a.updatePanel)
g.POST("/restartXray/:id", a.restartXray)
g.POST("/restartPanel/:id", a.restartPanel)
g.GET("/history/:id/:metric/:bucket", a.history)
g.POST("/mtls/ca", a.mtlsCa)
g.POST("/mtls/trustCA", a.setMtlsTrustCA)
@@ -349,6 +351,34 @@ func (a *NodeController) updatePanel(c *gin.Context) {
jsonMsgObj(c, I18nWeb(c, "pages.nodes.toasts.updateStarted"), results, err)
}
func (a *NodeController) restartXray(c *gin.Context) {
id, err := strconv.Atoi(c.Param("id"))
if err != nil || id <= 0 {
jsonMsg(c, I18nWeb(c, "pages.nodes.restartXray"), fmt.Errorf("invalid node ID"))
return
}
err = a.nodeService.RestartXray(c.Request.Context(), id)
if err != nil {
jsonMsg(c, I18nWeb(c, "pages.nodes.restartXray"), err)
return
}
jsonMsg(c, I18nWeb(c, "pages.nodes.toasts.xrayRestarted"), nil)
}
func (a *NodeController) restartPanel(c *gin.Context) {
id, err := strconv.Atoi(c.Param("id"))
if err != nil || id <= 0 {
jsonMsg(c, I18nWeb(c, "pages.nodes.restartPanel"), fmt.Errorf("invalid node ID"))
return
}
err = a.nodeService.RestartPanel(c.Request.Context(), id)
if err != nil {
jsonMsg(c, I18nWeb(c, "pages.nodes.restartPanel"), err)
return
}
jsonMsg(c, I18nWeb(c, "pages.nodes.toasts.panelRestartAccepted"), nil)
}
func (a *NodeController) history(c *gin.Context) {
id, err := strconv.Atoi(c.Param("id"))
if err != nil {
@@ -0,0 +1,68 @@
package controller
import (
"crypto/tls"
"crypto/x509"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/mhsanaei/3x-ui/v3/internal/database"
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
"github.com/mhsanaei/3x-ui/v3/internal/util/crypto"
"github.com/mhsanaei/3x-ui/v3/internal/web/global"
)
func TestPanelRestartScopeAndDelayedHook(t *testing.T) {
engine, auth := newAPIAuthTestEngine(t)
NewSettingController(engine.Group("/panel/api", auth.checkAPIAuth, auth.enforceTokenScope))
restarts := make(chan time.Time, 1)
global.SetRestartHook(func() { restarts <- time.Now() })
t.Cleanup(func() { global.SetRestartHook(func() {}) })
for _, scope := range []string{model.ApiScopeAdmin, model.ApiScopeNodeAdmin, model.ApiScopeNodeSync, model.ApiScopeMonitor} {
if err := database.GetDB().Create(&model.ApiToken{Name: scope, Token: crypto.HashTokenSHA256(scope), Enabled: true, Scope: scope}).Error; err != nil {
t.Fatal(err)
}
for _, mtls := range []bool{false, true} {
t.Run(scope+map[bool]string{false: "/bearer", true: "/mtls"}[mtls], func(t *testing.T) {
req := httptest.NewRequest(http.MethodPost, "/panel/api/setting/restartPanel", nil)
req.Header.Set("Authorization", "Bearer "+scope)
if mtls {
req.TLS = &tls.ConnectionState{VerifiedChains: [][]*x509.Certificate{{{}}}}
}
w := httptest.NewRecorder()
start := time.Now()
engine.ServeHTTP(w, req)
allowed := scope == model.ApiScopeNodeAdmin || (scope == model.ApiScopeAdmin && !mtls)
if !allowed {
want := `{"msg":"this API token is not permitted to access this endpoint","success":false}`
if w.Code != http.StatusForbidden || w.Body.String() != want {
t.Fatalf("denied = %d %s", w.Code, w.Body.String())
}
return
}
var result struct {
Success bool `json:"success"`
}
if err := json.Unmarshal(w.Body.Bytes(), &result); err != nil || !result.Success || w.Code != http.StatusOK {
t.Fatalf("accepted = %d %s: %v", w.Code, w.Body.String(), err)
}
select {
case <-restarts:
t.Fatal("panel restarted before response was delivered")
default:
}
select {
case at := <-restarts:
if at.Sub(start) < 3*time.Second {
t.Fatalf("restart delay = %s, want >=3s", at.Sub(start))
}
case <-time.After(6 * time.Second):
t.Fatal("accepted request did not restart panel")
}
})
}
}
}
@@ -0,0 +1,108 @@
package controller
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"net/url"
"strconv"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/mhsanaei/3x-ui/v3/internal/database"
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
"github.com/mhsanaei/3x-ui/v3/internal/util/crypto"
"github.com/mhsanaei/3x-ui/v3/internal/web/runtime"
)
func TestNodeRestartTargetsOnlySelectedNode(t *testing.T) {
for _, action := range []struct{ name, remotePath string }{
{"restartXray", "/custom/panel/api/server/restartXrayService"},
{"restartPanel", "/custom/panel/api/setting/restartPanel"},
} {
t.Run(action.name, func(t *testing.T) {
engine, auth := newAPIAuthTestEngine(t)
group := engine.Group("/panel/api/nodes", auth.checkAPIAuth, auth.enforceTokenScope)
NewNodeController(group)
if err := database.GetDB().Create(&model.ApiToken{Name: "master", Token: crypto.HashTokenSHA256("master"), Enabled: true, Scope: model.ApiScopeAdmin}).Error; err != nil {
t.Fatal(err)
}
previous := runtime.GetManager()
runtime.SetManager(runtime.NewManager(runtime.LocalDeps{}))
t.Cleanup(func() { runtime.SetManager(previous) })
var calls atomic.Int32
var response atomic.Value
response.Store(`{"success":true,"msg":"accepted","obj":null}`)
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
calls.Add(1)
if r.URL.Path != action.remotePath || r.Method != http.MethodPost || r.Header.Get("Authorization") != "Bearer node-secret" {
t.Errorf("remote request = %s %s auth=%q", r.Method, r.URL.Path, r.Header.Get("Authorization"))
}
fmt.Fprint(w, response.Load().(string))
}))
t.Cleanup(server.Close)
u, _ := url.Parse(server.URL)
port, _ := strconv.Atoi(u.Port())
node := model.Node{Name: "selected", Scheme: "http", Address: u.Hostname(), Port: port, BasePath: "/custom/", ApiToken: "node-secret", Enable: true, Status: "offline", AllowPrivateAddress: true}
if err := database.GetDB().Create(&node).Error; err != nil {
t.Fatal(err)
}
other := node
other.Id = 0
other.Name = "untouched"
other.Port = 1
if err := database.GetDB().Create(&other).Error; err != nil {
t.Fatal(err)
}
request := func(id string, ctx context.Context) (bool, string) {
t.Helper()
r := httptest.NewRequest(http.MethodPost, "/panel/api/nodes/"+action.name+"/"+id, nil).WithContext(ctx)
r.Header.Set("Authorization", "Bearer master")
w := httptest.NewRecorder()
engine.ServeHTTP(w, r)
var result struct {
Success bool `json:"success"`
Msg string `json:"msg"`
}
if err := json.Unmarshal(w.Body.Bytes(), &result); err != nil {
t.Fatalf("decode response: status=%d body=%q: %v", w.Code, w.Body.String(), err)
}
return result.Success, result.Msg
}
id := strconv.Itoa(node.Id)
if ok, msg := request(id, context.Background()); !ok || calls.Load() != 1 {
t.Fatalf("restart = %v %q, remote calls=%d, want success and one call", ok, msg, calls.Load())
}
response.Store(`{"success":false,"msg":"maintenance lock","obj":null}`)
if ok, msg := request(id, context.Background()); ok || !strings.Contains(msg, "maintenance lock") {
t.Fatalf("node rejection = %v %q", ok, msg)
}
ctx, cancel := context.WithCancel(context.Background())
cancel()
if ok, msg := request(id, ctx); ok || !strings.Contains(msg, "context canceled") {
t.Fatalf("canceled restart = %v %q", ok, msg)
}
deadlineCtx, deadlineCancel := context.WithDeadline(context.Background(), time.Now().Add(-time.Second))
defer deadlineCancel()
if ok, msg := request(id, deadlineCtx); ok || !strings.Contains(msg, "context deadline exceeded") {
t.Fatalf("expired restart = %v %q", ok, msg)
}
before := calls.Load()
if err := database.GetDB().Model(&node).Update("enable", false).Error; err != nil {
t.Fatal(err)
}
for _, bad := range []struct{ id, message string }{{id, "node is disabled"}, {"0", "invalid node ID"}, {"-1", "invalid node ID"}, {"abc", "invalid node ID"}, {"999999", "node not found"}} {
if ok, msg := request(bad.id, context.Background()); ok || !strings.Contains(msg, bad.message) {
t.Fatalf("restart %s = %v %q, want %q", bad.id, ok, msg, bad.message)
}
}
if calls.Load() != before {
t.Fatalf("invalid requests reached node: calls %d -> %d", before, calls.Load())
}
})
}
}