feat(api): panel trust bridge and Go-owned device grouping

Stage P1 and P2 of docs/important/console-backend-strangler.md, following
the architecture question in discussion #496.

Trust bridge (P1): the console signs a short-lived HMAC-SHA256 statement
(method, path, subject, role, org, issue/expiry, nonce) with
PANEL_TRUST_SECRET. Go verifies the signature, the window, the replay nonce
and the endpoint, accepts it only from loopback or PANEL_TRUST_ALLOWED_HOSTS,
and takes the role from the database when the account still exists - so a
demoted user cannot keep an old session's role, and device/pro roles are
refused outright. With no secret the bridge is off and authentication is
exactly as before.

Panel grouping (P2): Go now owns the writes for device groups, their members
and ACL, folders, device->folder assignment and per-user device grants, and
creates the tables on SQLite it previously only read. Every write is
transactional, so the RustDesk sync reader never sees a half-applied ACL.
The console keeps its screens and response shapes through
services/panelGrouping.js. BACKEND_PANEL_GROUPING=node restores the old
writer without a redeploy; a 404/501/503 falls back automatically while a
400/403 is final and never retried through the other writer.

Both .env keys are appended by the updater when missing and never
overwritten, so existing installs keep working untouched.

Refs #496

Thanks: INSOLVE (Honorary); Marco Jakobs (@jacotec); MyNameisStitch (@MyNameisStitch); Redspin (@playerumpknow); muopc (@muopc)
This commit is contained in:
UNITRONIX
2026-11-11 15:34:39 +01:00
parent b9be0bc381
commit c1925fbdf1
21 changed files with 3358 additions and 6 deletions
+18
View File
@@ -1094,6 +1094,24 @@ func hashAPIKey(key string) string {
// Returns (username, role, ok). If ok is false, an error response has been written.
// Auth order: Bearer JWT → X-API-Key (scoped DB lookup).
func (s *Server) authenticateRequest(r *http.Request) (username, role string, ok bool) {
// 0. Panel trust bridge — a statement signed by the Node console for a
// signed-in operator. Only accepted on the loopback hop (unless the
// operator explicitly allows remote panel hosts) and only when the
// bridge has a secret; the role still comes from the database when the
// account exists, so a stale or forged claim cannot raise privileges.
if r.Header.Get(PanelTrustHeader) != "" && s.panelTrustEnabled() && s.panelTrustPeerAllowed(r) {
claim, err := s.verifyPanelTrust(r)
if err != nil {
log.Printf("[panel-trust] rejected %s %s: %v", r.Method, redactPathSegment(r.URL.Path), err)
return "", "", false
}
role := s.resolvePanelRole(claim)
if role == "" {
return "", "", false
}
return claim.Subject, role, true
}
// 1. Bearer token — opaque client session (RustDesk desktop) or JWT (panel/API)
if bearer := r.Header.Get("Authorization"); len(bearer) > 7 && strings.EqualFold(bearer[:7], "Bearer ") {
token := strings.TrimSpace(bearer[7:])
@@ -0,0 +1,573 @@
package api
// Panel grouping endpoints: device groups, their membership and ACL, folders,
// and per-user device grants.
//
// These are the write side of what the RustDesk client reads through
// /api/device-group/accessible and /api/peers/list. Until stage P2 of
// docs/important/console-backend-strangler.md the Node console owned the
// writes; Go now owns both, so the panel and the client can never disagree
// about who sees which device.
//
// Routes (mounted with requirePanelAdmin / requirePermission wrappers):
//
// GET /api/panel/device-groups list groups with ACL + count
// POST /api/panel/device-groups create or update a group
// DELETE /api/panel/device-groups/{guid} delete a group
// GET /api/panel/device-groups/{guid}/peers membership
// PUT /api/panel/device-groups/{guid}/peers replace membership
// GET /api/panel/device-groups/{guid}/acl ACL
// PUT /api/panel/device-groups/{guid}/acl replace ACL
// GET /api/panel/folders list folders
// POST /api/panel/folders create a folder
// PUT /api/panel/folders/{id} update a folder
// DELETE /api/panel/folders/{id} delete a folder
// PUT /api/panel/devices/{id}/folder assign / clear a folder
// GET /api/panel/users/{id}/grants direct device grants
// PUT /api/panel/users/{id}/grants replace direct grants
import (
"encoding/json"
"fmt"
"net/http"
"strconv"
"strings"
"github.com/unitronix/betterdesk-server/auth"
"github.com/unitronix/betterdesk-server/db"
)
// panelGroupStore returns the write store for the active database.
func (s *Server) panelGroupStore() (db.PanelGroupStore, error) {
store, ok := s.db.(db.PanelGroupStore)
if !ok {
return nil, fmt.Errorf("the selected database does not support panel grouping")
}
return store, nil
}
// requirePanelGroupStore answers 503 (not 500) when the database cannot store
// panel grouping, so the console can fall back to its own writer during a
// staged rollout instead of showing a crash.
func (s *Server) requirePanelGroupStore(w http.ResponseWriter) (db.PanelGroupStore, bool) {
store, err := s.panelGroupStore()
if err != nil {
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": err.Error()})
return nil, false
}
return store, true
}
// panelGroupView is the JSON shape the console renders.
type panelGroupView struct {
GUID string `json:"guid"`
Name string `json:"name"`
Note string `json:"note"`
TeamID string `json:"team_id"`
SourceType string `json:"source_type"`
TagFilter string `json:"tag_filter"`
MemberCount int `json:"member_count"`
AllowedUsers []string `json:"allowed_users"`
AllowedGroups []string `json:"allowed_groups"`
}
func (s *Server) handlePanelDeviceGroupsList(w http.ResponseWriter, r *http.Request) {
store, ok := s.requirePanelGroupStore(w)
if !ok {
return
}
groups, err := s.db.ListDeviceGroups()
if err != nil {
writeInternalError(w, err, "ListDeviceGroups")
return
}
out := make([]panelGroupView, 0, len(groups))
for _, g := range groups {
view := panelGroupView{
GUID: g.GUID,
Name: g.Name,
Note: g.Note,
TeamID: g.TeamID,
SourceType: g.SourceType,
TagFilter: g.TagFilter,
AllowedUsers: []string{},
AllowedGroups: []string{},
}
if peers, err := store.ListDeviceGroupPeerIDs(g.GUID); err == nil {
view.MemberCount = len(peers)
}
if acl, err := store.GetDeviceGroupACL(g.GUID); err == nil && acl != nil {
view.AllowedUsers = acl.AllowedUsers
view.AllowedGroups = acl.AllowedUserGroups
}
out = append(out, view)
}
writeJSON(w, http.StatusOK, map[string]any{"groups": out, "total": len(out)})
}
type panelGroupBody struct {
GUID string `json:"guid"`
Name string `json:"name"`
Note string `json:"note"`
TeamID string `json:"team_id"`
SourceType string `json:"source_type"`
TagFilter string `json:"tag_filter"`
AllowedUsers []string `json:"allowed_users"`
AllowedGroups []string `json:"allowed_groups"`
// The console's form also accepts a single comma-separated string.
AllowedUsersRaw string `json:"allowed_users_csv"`
AllowedGroupsRaw string `json:"allowed_groups_csv"`
}
// handlePanelDeviceGroupsSave creates or updates a group and its ACL.
func (s *Server) handlePanelDeviceGroupsSave(w http.ResponseWriter, r *http.Request) {
store, ok := s.requirePanelGroupStore(w)
if !ok {
return
}
var body panelGroupBody
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid JSON"})
return
}
body.GUID = strings.TrimSpace(body.GUID)
body.Name = strings.TrimSpace(body.Name)
if body.Name == "" {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "name is required"})
return
}
if len(body.Name) > 80 {
body.Name = body.Name[:80]
}
sourceType := "manual"
if body.SourceType == "tag" {
sourceType = "tag"
}
tagFilter := ""
if sourceType == "tag" {
tagFilter = truncStr(strings.TrimSpace(body.TagFilter), 50)
}
note := truncStr(body.Note, 512)
teamID := truncStr(strings.TrimSpace(body.TeamID), 64)
var created bool
if body.GUID == "" {
g := &db.DeviceGroup{
Name: body.Name,
Note: note,
TeamID: teamID,
SourceType: sourceType,
TagFilter: tagFilter,
}
if err := s.db.CreateDeviceGroup(g); err != nil {
writeInternalError(w, err, "CreateDeviceGroup")
return
}
body.GUID = g.GUID
created = true
} else {
existing, err := s.db.GetDeviceGroup(body.GUID)
if err != nil {
writeInternalError(w, err, "GetDeviceGroup")
return
}
if existing == nil {
writeJSON(w, http.StatusNotFound, map[string]string{"error": "group not found"})
return
}
update := &db.DeviceGroup{
GUID: body.GUID,
Name: body.Name,
Note: note,
TeamID: teamID,
SourceType: sourceType,
TagFilter: tagFilter,
}
if err := s.db.UpdateDeviceGroup(body.GUID, update); err != nil {
writeInternalError(w, err, "UpdateDeviceGroup")
return
}
}
// The form may send either arrays or one comma-separated field.
users := body.AllowedUsers
if len(users) == 0 && body.AllowedUsersRaw != "" {
users = strings.Split(body.AllowedUsersRaw, ",")
}
groups := body.AllowedGroups
if len(groups) == 0 && body.AllowedGroupsRaw != "" {
groups = strings.Split(body.AllowedGroupsRaw, ",")
}
if err := store.SetDeviceGroupACL(body.GUID, &db.DeviceGroupACL{
AllowedUsers: users,
AllowedUserGroups: groups,
}); err != nil {
writeInternalError(w, err, "SetDeviceGroupACL")
return
}
status := http.StatusOK
if created {
status = http.StatusCreated
}
writeJSON(w, status, map[string]any{
"guid": body.GUID,
"name": body.Name,
"source_type": sourceType,
"tag_filter": tagFilter,
"allowed_users": dedupe(users),
"allowed_groups": dedupe(groups),
"created": created,
})
}
func (s *Server) handlePanelDeviceGroupsDelete(w http.ResponseWriter, r *http.Request) {
guid := strings.TrimSpace(r.PathValue("guid"))
if guid == "" {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "guid is required"})
return
}
existing, err := s.db.GetDeviceGroup(guid)
if err != nil {
writeInternalError(w, err, "GetDeviceGroup")
return
}
if existing == nil {
writeJSON(w, http.StatusNotFound, map[string]string{"error": "group not found"})
return
}
if err := s.db.DeleteDeviceGroup(guid); err != nil {
writeInternalError(w, err, "DeleteDeviceGroup")
return
}
writeJSON(w, http.StatusOK, map[string]any{"guid": guid, "deleted": true})
}
func (s *Server) handlePanelDeviceGroupPeersGet(w http.ResponseWriter, r *http.Request) {
store, ok := s.requirePanelGroupStore(w)
if !ok {
return
}
guid := strings.TrimSpace(r.PathValue("guid"))
peers, err := store.ListDeviceGroupPeerIDs(guid)
if err != nil {
writeInternalError(w, err, "ListDeviceGroupPeerIDs")
return
}
if peers == nil {
peers = []string{}
}
writeJSON(w, http.StatusOK, map[string]any{"guid": guid, "peers": peers, "total": len(peers)})
}
func (s *Server) handlePanelDeviceGroupPeersPut(w http.ResponseWriter, r *http.Request) {
store, ok := s.requirePanelGroupStore(w)
if !ok {
return
}
guid := strings.TrimSpace(r.PathValue("guid"))
var body struct {
Peers []string `json:"peers"`
}
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid JSON"})
return
}
if existing, err := s.db.GetDeviceGroup(guid); err != nil {
writeInternalError(w, err, "GetDeviceGroup")
return
} else if existing == nil {
writeJSON(w, http.StatusNotFound, map[string]string{"error": "group not found"})
return
}
if err := store.SetDeviceGroupPeers(guid, body.Peers); err != nil {
writeInternalError(w, err, "SetDeviceGroupPeers")
return
}
peers, _ := store.ListDeviceGroupPeerIDs(guid)
if peers == nil {
peers = []string{}
}
writeJSON(w, http.StatusOK, map[string]any{"guid": guid, "peers": peers, "total": len(peers)})
}
func (s *Server) handlePanelDeviceGroupACLGet(w http.ResponseWriter, r *http.Request) {
store, ok := s.requirePanelGroupStore(w)
if !ok {
return
}
guid := strings.TrimSpace(r.PathValue("guid"))
acl, err := store.GetDeviceGroupACL(guid)
if err != nil {
writeInternalError(w, err, "GetDeviceGroupACL")
return
}
if acl == nil {
writeJSON(w, http.StatusNotFound, map[string]string{"error": "group not found"})
return
}
writeJSON(w, http.StatusOK, acl)
}
func (s *Server) handlePanelDeviceGroupACLPut(w http.ResponseWriter, r *http.Request) {
store, ok := s.requirePanelGroupStore(w)
if !ok {
return
}
guid := strings.TrimSpace(r.PathValue("guid"))
var body db.DeviceGroupACL
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid JSON"})
return
}
if existing, err := s.db.GetDeviceGroup(guid); err != nil {
writeInternalError(w, err, "GetDeviceGroup")
return
} else if existing == nil {
writeJSON(w, http.StatusNotFound, map[string]string{"error": "group not found"})
return
}
if err := store.SetDeviceGroupACL(guid, &body); err != nil {
writeInternalError(w, err, "SetDeviceGroupACL")
return
}
acl, err := store.GetDeviceGroupACL(guid)
if err != nil {
writeInternalError(w, err, "GetDeviceGroupACL")
return
}
writeJSON(w, http.StatusOK, acl)
}
// ── Folders ───────────────────────────────────────────────────────────
func (s *Server) handlePanelFoldersList(w http.ResponseWriter, r *http.Request) {
store, ok := s.requirePanelGroupStore(w)
if !ok {
return
}
folders, err := store.ListPanelFolders()
if err != nil {
writeInternalError(w, err, "ListPanelFolders")
return
}
if folders == nil {
folders = []*db.Folder{}
}
assignments, err := store.ListPanelDeviceFolderAssignments()
if err != nil {
writeInternalError(w, err, "ListPanelDeviceFolderAssignments")
return
}
writeJSON(w, http.StatusOK, map[string]any{
"folders": folders,
"assignments": assignments,
})
}
func (s *Server) handlePanelFoldersCreate(w http.ResponseWriter, r *http.Request) {
store, ok := s.requirePanelGroupStore(w)
if !ok {
return
}
var body db.Folder
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid JSON"})
return
}
body.Name = truncStr(strings.TrimSpace(body.Name), 80)
if body.Name == "" {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "name is required"})
return
}
if body.Color == "" {
body.Color = "#6366f1"
}
if body.Icon == "" {
body.Icon = "folder"
}
if err := store.CreatePanelFolder(&body); err != nil {
writeInternalError(w, err, "CreatePanelFolder")
return
}
writeJSON(w, http.StatusCreated, body)
}
func (s *Server) handlePanelFoldersUpdate(w http.ResponseWriter, r *http.Request) {
store, ok := s.requirePanelGroupStore(w)
if !ok {
return
}
id, ok := parsePanelID(w, r.PathValue("id"))
if !ok {
return
}
var body db.Folder
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid JSON"})
return
}
body.Name = truncStr(strings.TrimSpace(body.Name), 80)
if body.Name == "" {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "name is required"})
return
}
if err := store.UpdatePanelFolder(id, &body); err != nil {
writeInternalError(w, err, "UpdatePanelFolder")
return
}
body.ID = id
writeJSON(w, http.StatusOK, body)
}
func (s *Server) handlePanelFoldersDelete(w http.ResponseWriter, r *http.Request) {
store, ok := s.requirePanelGroupStore(w)
if !ok {
return
}
id, ok := parsePanelID(w, r.PathValue("id"))
if !ok {
return
}
if err := store.DeletePanelFolder(id); err != nil {
writeInternalError(w, err, "DeletePanelFolder")
return
}
writeJSON(w, http.StatusOK, map[string]any{"id": id, "deleted": true})
}
// handlePanelDeviceFolder assigns a device to a folder (folder_id 0 clears it).
func (s *Server) handlePanelDeviceFolder(w http.ResponseWriter, r *http.Request) {
store, ok := s.requirePanelGroupStore(w)
if !ok {
return
}
peerID := strings.TrimSpace(r.PathValue("id"))
if peerID == "" {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "device id is required"})
return
}
var body struct {
FolderID int64 `json:"folder_id"`
}
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid JSON"})
return
}
if err := store.SetDevicePanelFolder(peerID, body.FolderID); err != nil {
writeInternalError(w, err, "SetDevicePanelFolder")
return
}
writeJSON(w, http.StatusOK, map[string]any{"device_id": peerID, "folder_id": body.FolderID})
}
// ── Per-user grants ───────────────────────────────────────────────────
func (s *Server) handlePanelUserGrantsGet(w http.ResponseWriter, r *http.Request) {
store, ok := s.requirePanelGroupStore(w)
if !ok {
return
}
id, ok := parsePanelID(w, r.PathValue("id"))
if !ok {
return
}
grants, err := store.ListPanelUserPeerGrants(id)
if err != nil {
writeInternalError(w, err, "ListPanelUserPeerGrants")
return
}
if grants == nil {
grants = []string{}
}
writeJSON(w, http.StatusOK, map[string]any{"user_id": id, "peers": grants, "total": len(grants)})
}
func (s *Server) handlePanelUserGrantsPut(w http.ResponseWriter, r *http.Request) {
store, ok := s.requirePanelGroupStore(w)
if !ok {
return
}
id, ok := parsePanelID(w, r.PathValue("id"))
if !ok {
return
}
var body struct {
Peers []string `json:"peers"`
}
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid JSON"})
return
}
if err := store.SetUserPeerGrants(id, body.Peers); err != nil {
writeInternalError(w, err, "SetUserPeerGrants")
return
}
grants, _ := store.ListPanelUserPeerGrants(id)
if grants == nil {
grants = []string{}
}
writeJSON(w, http.StatusOK, map[string]any{"user_id": id, "peers": grants, "total": len(grants)})
}
// ── helpers ───────────────────────────────────────────────────────────
func parsePanelID(w http.ResponseWriter, raw string) (int64, bool) {
raw = strings.TrimSpace(raw)
id, err := strconv.ParseInt(raw, 10, 64)
if err != nil || id <= 0 {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid id"})
return 0, false
}
return id, true
}
func dedupe(values []string) []string {
seen := make(map[string]bool, len(values))
out := make([]string, 0, len(values))
for _, raw := range values {
value := strings.TrimSpace(raw)
if value == "" || seen[value] {
continue
}
seen[value] = true
out = append(out, value)
}
return out
}
// registerPanelGroupRoutes mounts the grouping endpoints. Writes need
// device.edit (groups) or user.edit (grants); reads need device.view or
// user.view, so a viewer can see the folders but not change them.
func (s *Server) registerPanelGroupRoutes(mux *http.ServeMux) {
mux.HandleFunc("GET /api/panel/device-groups",
s.requirePermission(auth.PermDeviceView, s.handlePanelDeviceGroupsList))
mux.HandleFunc("POST /api/panel/device-groups",
s.requirePermission(auth.PermDeviceEdit, s.handlePanelDeviceGroupsSave))
mux.HandleFunc("DELETE /api/panel/device-groups/{guid}",
s.requirePermission(auth.PermDeviceEdit, s.handlePanelDeviceGroupsDelete))
mux.HandleFunc("GET /api/panel/device-groups/{guid}/peers",
s.requirePermission(auth.PermDeviceView, s.handlePanelDeviceGroupPeersGet))
mux.HandleFunc("PUT /api/panel/device-groups/{guid}/peers",
s.requirePermission(auth.PermDeviceEdit, s.handlePanelDeviceGroupPeersPut))
mux.HandleFunc("GET /api/panel/device-groups/{guid}/acl",
s.requirePermission(auth.PermDeviceView, s.handlePanelDeviceGroupACLGet))
mux.HandleFunc("PUT /api/panel/device-groups/{guid}/acl",
s.requirePermission(auth.PermDeviceEdit, s.handlePanelDeviceGroupACLPut))
mux.HandleFunc("GET /api/panel/folders",
s.requirePermission(auth.PermDeviceView, s.handlePanelFoldersList))
mux.HandleFunc("POST /api/panel/folders",
s.requirePermission(auth.PermDeviceEdit, s.handlePanelFoldersCreate))
mux.HandleFunc("PUT /api/panel/folders/{id}",
s.requirePermission(auth.PermDeviceEdit, s.handlePanelFoldersUpdate))
mux.HandleFunc("DELETE /api/panel/folders/{id}",
s.requirePermission(auth.PermDeviceEdit, s.handlePanelFoldersDelete))
mux.HandleFunc("PUT /api/panel/devices/{id}/folder",
s.requirePermission(auth.PermDeviceEdit, s.handlePanelDeviceFolder))
mux.HandleFunc("GET /api/panel/users/{id}/grants",
s.requirePermission(auth.PermUserView, s.handlePanelUserGrantsGet))
mux.HandleFunc("PUT /api/panel/users/{id}/grants",
s.requirePermission(auth.PermUserEdit, s.handlePanelUserGrantsPut))
}
@@ -0,0 +1,301 @@
package api
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"testing"
"time"
"github.com/unitronix/betterdesk-server/auth"
"github.com/unitronix/betterdesk-server/config"
"github.com/unitronix/betterdesk-server/db"
"github.com/unitronix/betterdesk-server/peer"
)
// panelGroupTestServer starts a server on a free-ish port with an admin API key.
func panelGroupTestServer(t *testing.T, port int) (*Server, string) {
t.Helper()
cfg := config.DefaultConfig()
database := testSetupDB(t)
t.Cleanup(func() { database.Close() })
if err := database.CreateUser(&db.User{
Username: "operator-grp",
PasswordHash: "hash",
Role: auth.RoleOperator,
AuthProvider: db.AuthProviderLocal,
}); err != nil {
t.Fatal(err)
}
cfg.APIPort = port
srv := New(cfg, database, peer.NewMap(), nil, "1.0.0-test")
if err := srv.Start(t.Context()); err != nil {
t.Fatal(err)
}
t.Cleanup(func() { srv.Stop() })
time.Sleep(120 * time.Millisecond)
return srv, fmt.Sprintf("http://127.0.0.1:%d", port)
}
func doPanelJSON(t *testing.T, method, url string, body any) (*http.Response, map[string]any) {
t.Helper()
var reader *bytes.Reader
if body == nil {
reader = bytes.NewReader(nil)
} else {
raw, err := json.Marshal(body)
if err != nil {
t.Fatal(err)
}
reader = bytes.NewReader(raw)
}
req, err := http.NewRequest(method, url, reader)
if err != nil {
t.Fatal(err)
}
req.Header.Set("X-API-Key", testAPIKey)
req.Header.Set("Content-Type", "application/json")
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
var parsed map[string]any
_ = json.NewDecoder(resp.Body).Decode(&parsed)
return resp, parsed
}
func TestPanelGroupLifecycle(t *testing.T) {
_, base := panelGroupTestServer(t, 19896)
// Create a group with an ACL.
resp, body := doPanelJSON(t, http.MethodPost, base+"/api/panel/device-groups", map[string]any{
"name": "Support team",
"note": "created by test",
"source_type": "manual",
"allowed_users": []string{"operator-grp"},
"allowed_groups": []string{},
})
if resp.StatusCode != http.StatusCreated {
t.Fatalf("create status %d, want 201 (%v)", resp.StatusCode, body)
}
guid, _ := body["guid"].(string)
if guid == "" {
t.Fatal("create response has no guid")
}
// The list reflects it, with the ACL and member count.
resp, body = doPanelJSON(t, http.MethodGet, base+"/api/panel/device-groups", nil)
if resp.StatusCode != http.StatusOK {
t.Fatalf("list status %d", resp.StatusCode)
}
groups, _ := body["groups"].([]any)
if len(groups) != 1 {
t.Fatalf("groups = %v, want 1", groups)
}
first := groups[0].(map[string]any)
if first["name"] != "Support team" {
t.Errorf("name = %v", first["name"])
}
if users, _ := first["allowed_users"].([]any); len(users) != 1 {
t.Errorf("allowed_users = %v, want 1", first["allowed_users"])
}
// Membership: replace and read back.
resp, body = doPanelJSON(t, http.MethodPut, base+"/api/panel/device-groups/"+guid+"/peers", map[string]any{
"peers": []string{"PEER1", "PEER2", "PEER1"},
})
if resp.StatusCode != http.StatusOK {
t.Fatalf("put peers status %d (%v)", resp.StatusCode, body)
}
if total, _ := body["total"].(float64); int(total) != 2 {
t.Errorf("peer total = %v, want 2 (duplicates dropped)", body["total"])
}
resp, body = doPanelJSON(t, http.MethodGet, base+"/api/panel/device-groups/"+guid+"/peers", nil)
peers, _ := body["peers"].([]any)
if resp.StatusCode != http.StatusOK || len(peers) != 2 {
t.Fatalf("get peers status %d peers %v", resp.StatusCode, peers)
}
// ACL: replace and read back.
resp, body = doPanelJSON(t, http.MethodPut, base+"/api/panel/device-groups/"+guid+"/acl", map[string]any{
"allowed_users": []string{"operator-grp"},
"allowed_user_groups": []string{},
})
if resp.StatusCode != http.StatusOK {
t.Fatalf("put acl status %d (%v)", resp.StatusCode, body)
}
resp, body = doPanelJSON(t, http.MethodGet, base+"/api/panel/device-groups/"+guid+"/acl", nil)
if resp.StatusCode != http.StatusOK {
t.Fatalf("get acl status %d", resp.StatusCode)
}
if users, _ := body["allowed_users"].([]any); len(users) != 1 {
t.Errorf("acl users = %v", body["allowed_users"])
}
// Delete removes the group; membership and ACL go with it.
resp, body = doPanelJSON(t, http.MethodDelete, base+"/api/panel/device-groups/"+guid, nil)
if resp.StatusCode != http.StatusOK {
t.Fatalf("delete status %d (%v)", resp.StatusCode, body)
}
resp, body = doPanelJSON(t, http.MethodGet, base+"/api/panel/device-groups", nil)
if groups, _ := body["groups"].([]any); len(groups) != 0 {
t.Errorf("groups after delete = %v, want none", groups)
}
}
func TestPanelGroupRejectsInvalidInput(t *testing.T) {
_, base := panelGroupTestServer(t, 19897)
resp, _ := doPanelJSON(t, http.MethodPost, base+"/api/panel/device-groups", map[string]any{
"name": " ",
})
if resp.StatusCode != http.StatusBadRequest {
t.Fatalf("empty name status %d, want 400", resp.StatusCode)
}
resp, _ = doPanelJSON(t, http.MethodPost, base+"/api/panel/device-groups", "not-an-object")
if resp.StatusCode != http.StatusBadRequest {
t.Fatalf("invalid JSON status %d, want 400", resp.StatusCode)
}
resp, _ = doPanelJSON(t, http.MethodGet, base+"/api/panel/device-groups/missing-guid/peers", nil)
if resp.StatusCode != http.StatusOK {
t.Fatalf("unknown group peers status %d, want 200 with an empty list", resp.StatusCode)
}
resp, _ = doPanelJSON(t, http.MethodDelete, base+"/api/panel/device-groups/nope", nil)
if resp.StatusCode != http.StatusNotFound {
t.Fatalf("delete unknown status %d, want 404", resp.StatusCode)
}
}
func TestPanelFoldersLifecycle(t *testing.T) {
_, base := panelGroupTestServer(t, 19898)
resp, body := doPanelJSON(t, http.MethodPost, base+"/api/panel/folders", map[string]any{
"name": "Customers",
})
if resp.StatusCode != http.StatusCreated {
t.Fatalf("create folder status %d (%v)", resp.StatusCode, body)
}
id, _ := body["id"].(float64)
if id <= 0 {
t.Fatalf("folder id = %v", body["id"])
}
// Assign a device, then read assignments back through the list endpoint.
resp, body = doPanelJSON(t, http.MethodPut, base+"/api/panel/devices/PEER9/folder", map[string]any{
"folder_id": int64(id),
})
if resp.StatusCode != http.StatusOK {
t.Fatalf("assign status %d (%v)", resp.StatusCode, body)
}
resp, body = doPanelJSON(t, http.MethodGet, base+"/api/panel/folders", nil)
if resp.StatusCode != http.StatusOK {
t.Fatalf("list folders status %d", resp.StatusCode)
}
assignments, _ := body["assignments"].(map[string]any)
if len(assignments) != 1 {
t.Fatalf("assignments = %v, want one", assignments)
}
// Clearing the folder removes the assignment but keeps the folder.
resp, _ = doPanelJSON(t, http.MethodPut, base+"/api/panel/devices/PEER9/folder", map[string]any{"folder_id": 0})
if resp.StatusCode != http.StatusOK {
t.Fatalf("clear status %d", resp.StatusCode)
}
resp, body = doPanelJSON(t, http.MethodGet, base+"/api/panel/folders", nil)
if assignments, _ := body["assignments"].(map[string]any); len(assignments) != 0 {
t.Errorf("assignments after clear = %v", assignments)
}
// Rename, then delete.
resp, _ = doPanelJSON(t, http.MethodPut, fmt.Sprintf("%s/api/panel/folders/%d", base, int64(id)), map[string]any{
"name": "Customers 2026", "sort_order": 3,
})
if resp.StatusCode != http.StatusOK {
t.Fatalf("rename status %d", resp.StatusCode)
}
resp, _ = doPanelJSON(t, http.MethodDelete, fmt.Sprintf("%s/api/panel/folders/%d", base, int64(id)), nil)
if resp.StatusCode != http.StatusOK {
t.Fatalf("delete status %d", resp.StatusCode)
}
resp, body = doPanelJSON(t, http.MethodGet, base+"/api/panel/folders", nil)
if folders, _ := body["folders"].([]any); len(folders) != 0 {
t.Errorf("folders after delete = %v", folders)
}
}
func TestPanelUserGrants(t *testing.T) {
srv, base := panelGroupTestServer(t, 19899)
operator, err := srv.db.GetUser("operator-grp")
if err != nil || operator == nil {
t.Fatalf("GetUser: %v", err)
}
resp, body := doPanelJSON(t, http.MethodPut,
fmt.Sprintf("%s/api/panel/users/%d/grants", base, operator.ID),
map[string]any{"peers": []string{"PEER-A", "PEER-B"}})
if resp.StatusCode != http.StatusOK {
t.Fatalf("put grants status %d (%v)", resp.StatusCode, body)
}
if total, _ := body["total"].(float64); int(total) != 2 {
t.Errorf("grants total = %v", body["total"])
}
resp, body = doPanelJSON(t, http.MethodGet,
fmt.Sprintf("%s/api/panel/users/%d/grants", base, operator.ID), nil)
if resp.StatusCode != http.StatusOK {
t.Fatalf("get grants status %d", resp.StatusCode)
}
if peers, _ := body["peers"].([]any); len(peers) != 2 {
t.Errorf("grants = %v", body["peers"])
}
// An invalid id is refused, not treated as user 0.
resp, _ = doPanelJSON(t, http.MethodGet, base+"/api/panel/users/0/grants", nil)
if resp.StatusCode != http.StatusBadRequest {
t.Fatalf("invalid id status %d, want 400", resp.StatusCode)
}
}
// TestPanelGroupRoutesRequirePermission proves the endpoints are not open to a
// session without device.edit, so the new writes cannot become a privilege
// escalation path.
func TestPanelGroupRoutesRequirePermission(t *testing.T) {
srv, base := panelGroupTestServer(t, 19900)
if err := srv.db.SetRolePermission(auth.RoleOperator, auth.PermDeviceEdit, false); err != nil {
t.Fatal(err)
}
key := "operator-key-900"
if err := srv.db.CreateAPIKey(&db.APIKey{
KeyHash: hashAPIKey(key),
KeyPrefix: key[:8],
Name: "operator-900",
Role: auth.RoleOperator,
}); err != nil {
t.Fatal(err)
}
req, err := http.NewRequest(http.MethodPost, base+"/api/panel/device-groups",
bytes.NewReader([]byte(`{"name":"nope"}`)))
if err != nil {
t.Fatal(err)
}
req.Header.Set("X-API-Key", key)
req.Header.Set("Content-Type", "application/json")
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusForbidden {
t.Fatalf("status %d, want 403 without device.edit", resp.StatusCode)
}
}
+325
View File
@@ -0,0 +1,325 @@
// Package api — panel trust bridge.
//
// The console today is a Node.js process that owns the browser session (cookie,
// CSRF, idle timeout) and forwards most work to this server. Moving domains
// into Go stage by stage needs a way for Go to authorize a request that a
// signed-in operator made through the panel, without Go owning a browser
// session of its own.
//
// The bridge is deliberately narrow:
//
// - Node signs a short-lived statement with HMAC-SHA256 over
// method, path, subject, role, org, issued-at, expiry and a nonce;
// - Go verifies the signature, the time window and replays;
// - the claimed role is never trusted above the session's real role, and the
// existing permission middleware still runs afterwards;
// - the header never reaches the browser: it is added on the loopback hop.
//
// The secret lives in the installer-managed .env (appended, never overwritten
// by updates). With no secret configured the bridge is off and behaviour is
// exactly what it was before.
package api
import (
"crypto/hmac"
"crypto/sha256"
"crypto/subtle"
"encoding/base64"
"encoding/hex"
"errors"
"fmt"
"log"
"net"
"net/http"
"os"
"strings"
"sync"
"time"
"github.com/unitronix/betterdesk-server/auth"
)
const (
// PanelTrustHeader carries the signed panel identity.
PanelTrustHeader = "X-BetterDesk-Panel"
// PanelTrustSecretEnv names the shared secret in the environment.
PanelTrustSecretEnv = "PANEL_TRUST_SECRET"
// panelTrustVersion prefixes every statement so a future format can be
// rejected instead of misread.
panelTrustVersion = "v1"
// panelTrustMaxTTL bounds how long a statement may live, whatever the
// signer asks for.
panelTrustMaxTTL = 120 * time.Second
// panelTrustClockSkew allows for small clock differences between the two
// processes on the same host.
panelTrustClockSkew = 30 * time.Second
// panelTrustNonceTTL is how long a used nonce is remembered.
panelTrustNonceTTL = 150 * time.Second
)
var (
errPanelTrustMissing = errors.New("panel trust header missing")
errPanelTrustMalformed = errors.New("panel trust header malformed")
errPanelTrustSignature = errors.New("panel trust signature invalid")
errPanelTrustExpired = errors.New("panel trust statement expired")
errPanelTrustReplay = errors.New("panel trust statement replayed")
errPanelTrustNoSecret = errors.New("panel trust secret not configured")
)
// panelClaim is the verified identity of a panel-originated request.
type panelClaim struct {
Subject string
Role string
OrgID string
Issued time.Time
Expires time.Time
Nonce string
}
// statement is the canonical string that gets signed. Field order and
// separators are part of the format: both sides must produce it identically.
func (c panelClaim) statement(method, path string) string {
return strings.Join([]string{
panelTrustVersion,
strings.ToUpper(method),
path,
c.Subject,
c.Role,
c.OrgID,
fmt.Sprintf("%d", c.Issued.Unix()),
fmt.Sprintf("%d", c.Expires.Unix()),
c.Nonce,
}, "\n")
}
// signFor is the only signing entry point: the signature always covers the
// method and path, so a statement captured for one endpoint cannot be replayed
// against another.
func (c panelClaim) signFor(secret []byte, method, path string) string {
stmt := c.statement(method, path)
mac := hmac.New(sha256.New, secret)
mac.Write([]byte(stmt))
payload := base64.RawURLEncoding.EncodeToString([]byte(stmt))
return payload + "." + hex.EncodeToString(mac.Sum(nil))
}
// parsePanelClaim decodes and verifies the header value for this request.
func parsePanelClaim(headerValue string, secret []byte, method, path string, now time.Time) (panelClaim, error) {
var claim panelClaim
if secret == nil || len(secret) == 0 {
return claim, errPanelTrustNoSecret
}
value := strings.TrimSpace(headerValue)
if value == "" {
return claim, errPanelTrustMissing
}
dot := strings.LastIndexByte(value, '.')
if dot <= 0 || dot == len(value)-1 {
return claim, errPanelTrustMalformed
}
stmtBytes, err := base64.RawURLEncoding.DecodeString(value[:dot])
if err != nil {
return claim, errPanelTrustMalformed
}
sig, err := hex.DecodeString(value[dot+1:])
if err != nil || len(sig) != sha256.Size {
return claim, errPanelTrustMalformed
}
stmt := string(stmtBytes)
mac := hmac.New(sha256.New, secret)
mac.Write([]byte(stmt))
if subtle.ConstantTimeCompare(mac.Sum(nil), sig) != 1 {
return claim, errPanelTrustSignature
}
parts := strings.Split(stmt, "\n")
if len(parts) != 9 || parts[0] != panelTrustVersion {
return claim, errPanelTrustMalformed
}
if !strings.EqualFold(parts[1], strings.ToUpper(method)) || parts[2] != path {
// The statement was signed for another method or endpoint.
return claim, errPanelTrustSignature
}
claim.Subject = parts[3]
claim.Role = parts[4]
claim.OrgID = parts[5]
if claim.Subject == "" || claim.Role == "" {
return claim, errPanelTrustMalformed
}
issuedUnix, err := parseInt64Strict(parts[6])
if err != nil {
return claim, errPanelTrustMalformed
}
expiresUnix, err := parseInt64Strict(parts[7])
if err != nil {
return claim, errPanelTrustMalformed
}
claim.Issued = time.Unix(issuedUnix, 0)
claim.Expires = time.Unix(expiresUnix, 0)
claim.Nonce = parts[8]
if claim.Nonce == "" {
return claim, errPanelTrustMalformed
}
if claim.Expires.Sub(claim.Issued) > panelTrustMaxTTL {
return claim, errPanelTrustMalformed
}
if now.Add(panelTrustClockSkew).Before(claim.Issued) {
return claim, errPanelTrustExpired
}
if now.After(claim.Expires) {
return claim, errPanelTrustExpired
}
return claim, nil
}
func parseInt64Strict(s string) (int64, error) {
if s == "" || len(s) > 20 {
return 0, errPanelTrustMalformed
}
var out int64
for _, ch := range s {
if ch < '0' || ch > '9' {
return 0, errPanelTrustMalformed
}
out = out*10 + int64(ch-'0')
}
return out, nil
}
// panelNonceCache remembers nonces for the statement window, so a captured
// header cannot be replayed while it is still inside its TTL.
type panelNonceCache struct {
mu sync.Mutex
seen map[string]time.Time
lastS time.Time
}
func newPanelNonceCache() *panelNonceCache {
return &panelNonceCache{seen: make(map[string]time.Time)}
}
// use records a nonce. It returns false when the nonce was already used.
func (c *panelNonceCache) use(nonce string, now time.Time) bool {
c.mu.Lock()
defer c.mu.Unlock()
if c.seen == nil {
c.seen = make(map[string]time.Time)
}
if now.Sub(c.lastS) > panelTrustNonceTTL {
for key, at := range c.seen {
if now.Sub(at) > panelTrustNonceTTL {
delete(c.seen, key)
}
}
c.lastS = now
}
if _, dup := c.seen[nonce]; dup {
return false
}
c.seen[nonce] = now
return true
}
// SetPanelTrustSecret enables the bridge. An empty secret leaves it disabled.
func (s *Server) SetPanelTrustSecret(secret string) {
trimmed := strings.TrimSpace(secret)
if trimmed == "" {
s.panelTrustSecret = nil
return
}
s.panelTrustSecret = []byte(trimmed)
}
// panelTrustEnabled reports whether the bridge can verify statements.
func (s *Server) panelTrustEnabled() bool {
return len(s.panelTrustSecret) > 0
}
// panelTrustPeerAllowed limits the bridge to the hop from the console process.
// The console always talks to Go over loopback (both on the same host, or
// through the container network where the panel container's address is in the
// operator's allowlist). Anything else must be listed in
// PANEL_TRUST_ALLOWED_HOSTS — a statement from an arbitrary client is refused
// before the signature is even checked.
func (s *Server) panelTrustPeerAllowed(r *http.Request) bool {
host, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
host = r.RemoteAddr
}
ip := net.ParseIP(strings.TrimSpace(host))
if ip == nil {
return false
}
if ip.IsLoopback() {
return true
}
allowed := strings.TrimSpace(os.Getenv("PANEL_TRUST_ALLOWED_HOSTS"))
if allowed == "" {
return false
}
for _, entry := range strings.Split(allowed, ",") {
candidate := strings.TrimSpace(entry)
if candidate == "" {
continue
}
if parsed := net.ParseIP(candidate); parsed != nil && parsed.Equal(ip) {
return true
}
if _, network, err := net.ParseCIDR(candidate); err == nil && network.Contains(ip) {
return true
}
}
return false
}
// resolvePanelRole returns the role a panel statement may act with.
//
// The claim is a hint, not authority: when the account still exists, its role
// in the database wins, so a demoted or deleted user cannot keep the role their
// session was created with. When the account does not exist, the claim is used
// only for a known role — never a device or pro role, which exist for other
// transports.
func (s *Server) resolvePanelRole(claim panelClaim) string {
if s.db != nil {
if user, err := s.db.GetUser(claim.Subject); err == nil && user != nil {
if user.Role != "" && user.Role != claim.Role {
log.Printf("[panel-trust] role for %s updated %q -> %q", claim.Subject, claim.Role, user.Role)
}
if !auth.ValidRole(user.Role) {
return ""
}
return user.Role
}
}
if !auth.ValidRole(claim.Role) || auth.IsDeviceRole(claim.Role) || auth.IsProRole(claim.Role) {
return ""
}
return claim.Role
}
// verifyPanelTrust reads and verifies the panel statement for this request.
func (s *Server) verifyPanelTrust(r *http.Request) (panelClaim, error) {
var claim panelClaim
if !s.panelTrustEnabled() {
return claim, errPanelTrustNoSecret
}
claim, err := parsePanelClaim(
r.Header.Get(PanelTrustHeader),
s.panelTrustSecret,
r.Method,
r.URL.EscapedPath(),
time.Now(),
)
if err != nil {
return claim, err
}
if s.panelNonces == nil {
s.panelNonces = newPanelNonceCache()
}
if !s.panelNonces.use(claim.Nonce, time.Now()) {
return claim, errPanelTrustReplay
}
return claim, nil
}
@@ -0,0 +1,146 @@
package api
import (
"bytes"
"encoding/json"
"net/http"
"testing"
"time"
"github.com/unitronix/betterdesk-server/auth"
"github.com/unitronix/betterdesk-server/db"
)
// panelTrustRequest builds a panel-originated request: the panel API key plus a
// signed statement for the operator's own identity.
func panelTrustRequest(t *testing.T, method, url, path, subject, role, nonce string, body []byte) *http.Request {
t.Helper()
claim := newClaim(time.Now())
claim.Subject = subject
claim.Role = role
claim.Nonce = nonce
header := claim.signFor([]byte(testPanelSecret), method, path)
req, err := http.NewRequest(method, url, bytes.NewReader(body))
if err != nil {
t.Fatal(err)
}
req.Header.Set("X-API-Key", testAPIKey)
req.Header.Set(PanelTrustHeader, header)
req.Header.Set("Content-Type", "application/json")
return req
}
// TestPanelTrustEnforcesOperatorRole is the end-to-end proof that the bridge
// does what it is for: a viewer's session cannot write a device group even
// though the HTTP call arrives with the panel's administrator API key.
//
// Without the statement the same call would be authorized as an administrator,
// which is exactly the privilege escalation the bridge exists to prevent.
func TestPanelTrustEnforcesOperatorRole(t *testing.T) {
srv, base := panelGroupTestServer(t, 19920)
srv.SetPanelTrustSecret(testPanelSecret)
if err := srv.db.CreateUser(&db.User{
Username: "viewer-trust",
PasswordHash: "hash",
Role: auth.RoleViewer,
AuthProvider: db.AuthProviderLocal,
}); err != nil {
t.Fatal(err)
}
path := "/api/panel/device-groups"
req := panelTrustRequest(t, http.MethodPost, base+path, path,
"viewer-trust", auth.RoleViewer, "nonce-viewer-1", []byte(`{"name":"viewer group"}`))
req.RemoteAddr = "127.0.0.1:5000"
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusForbidden {
t.Fatalf("viewer status %d, want 403 — the trust statement must not raise the role",
resp.StatusCode)
}
}
// TestPanelTrustAllowsOperatorWrite proves the same call succeeds for a role
// that may edit devices, so the previous test is not passing merely because the
// route is broken.
func TestPanelTrustAllowsOperatorWrite(t *testing.T) {
srv, base := panelGroupTestServer(t, 19921)
srv.SetPanelTrustSecret(testPanelSecret)
path := "/api/panel/device-groups"
// operator-grp is created by panelGroupTestServer with the operator role.
req := panelTrustRequest(t, http.MethodPost, base+path, path,
"operator-grp", auth.RoleOperator, "nonce-operator-1", []byte(`{"name":"operator group"}`))
req.RemoteAddr = "127.0.0.1:5000"
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusCreated {
var body map[string]any
_ = json.NewDecoder(resp.Body).Decode(&body)
t.Fatalf("operator status %d, want 201 (%v)", resp.StatusCode, body)
}
}
// TestPanelTrustRoleComesFromTheDatabase proves a stale claim cannot keep
// privileges: the session was created when the account was an administrator,
// the account is now a viewer, and the write is refused.
func TestPanelTrustRoleComesFromTheDatabase(t *testing.T) {
srv, base := panelGroupTestServer(t, 19923)
srv.SetPanelTrustSecret(testPanelSecret)
user, err := srv.db.GetUser("operator-grp")
if err != nil || user == nil {
t.Fatalf("GetUser: %v", err)
}
user.Role = auth.RoleViewer
if err := srv.db.UpdateUser(user); err != nil {
t.Fatal(err)
}
path := "/api/panel/device-groups"
// The statement still claims operator — the server must not honour it.
req := panelTrustRequest(t, http.MethodPost, base+path, path,
"operator-grp", auth.RoleOperator, "nonce-demoted-1", []byte(`{"name":"demoted group"}`))
req.RemoteAddr = "127.0.0.1:5000"
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusForbidden {
t.Fatalf("demoted status %d, want 403 — the database role must win",
resp.StatusCode)
}
}
// TestPanelTrustRejectsForgedHeaderWithoutTheSecret proves that a statement is
// useless without the shared secret, even from loopback with a valid API key.
func TestPanelTrustRejectsForgedHeaderWithoutTheSecret(t *testing.T) {
srv, base := panelGroupTestServer(t, 19924)
srv.SetPanelTrustSecret("a-completely-different-secret-value")
path := "/api/panel/device-groups"
req := panelTrustRequest(t, http.MethodPost, base+path, path,
"operator-grp", auth.RoleOperator, "nonce-forged-1", []byte(`{"name":"forged group"}`))
req.RemoteAddr = "127.0.0.1:5000"
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusUnauthorized {
t.Fatalf("forged status %d, want 401", resp.StatusCode)
}
}
+203
View File
@@ -0,0 +1,203 @@
package api
import (
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
)
const testPanelSecret = "0123456789abcdef0123456789abcdef"
func newClaim(now time.Time) panelClaim {
return panelClaim{
Subject: "operator1",
Role: "operator",
OrgID: "",
Issued: now,
Expires: now.Add(60 * time.Second),
Nonce: "nonce-1",
}
}
func TestPanelTrustRejectsMissingHeader(t *testing.T) {
_, err := parsePanelClaim("", []byte(testPanelSecret), http.MethodGet, "/api/peers", time.Now())
if err != errPanelTrustMissing {
t.Fatalf("want errPanelTrustMissing, got %v", err)
}
}
func TestPanelTrustRejectsWithoutSecret(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "/api/peers", nil)
req.Header.Set(PanelTrustHeader, "anything")
s := &Server{}
if _, err := s.verifyPanelTrust(req); err != errPanelTrustNoSecret {
t.Fatalf("want errPanelTrustNoSecret, got %v", err)
}
}
func TestPanelTrustAcceptsValidStatement(t *testing.T) {
now := time.Now()
claim := newClaim(now)
header := claim.signFor([]byte(testPanelSecret), http.MethodGet, "/api/peers")
parsed, err := parsePanelClaim(header, []byte(testPanelSecret), http.MethodGet, "/api/peers", now)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if parsed.Subject != claim.Subject || parsed.Role != claim.Role || parsed.Nonce != claim.Nonce {
t.Fatalf("parsed claim does not match: %+v", parsed)
}
}
func TestPanelTrustRejectsWrongSecret(t *testing.T) {
now := time.Now()
claim := newClaim(now)
header := claim.signFor([]byte(testPanelSecret), http.MethodGet, "/api/peers")
if _, err := parsePanelClaim(header, []byte("ffffffffffffffffffffffffffffffff"), http.MethodGet, "/api/peers", now); err != errPanelTrustSignature {
t.Fatalf("want errPanelTrustSignature, got %v", err)
}
}
func TestPanelTrustRejectsTamperedStatement(t *testing.T) {
now := time.Now()
claim := newClaim(now)
claim.Role = "viewer"
header := claim.signFor([]byte(testPanelSecret), http.MethodGet, "/api/peers")
// Same signature, different statement (role raised by editing the payload).
parts := strings.SplitN(header, ".", 2)
raised := newClaim(now)
raised.Role = "super_admin"
tamperedPayload := strings.SplitN(raised.signFor([]byte(testPanelSecret), http.MethodGet, "/api/peers"), ".", 2)[0]
forged := tamperedPayload + "." + parts[1]
if _, err := parsePanelClaim(forged, []byte(testPanelSecret), http.MethodGet, "/api/peers", now); err != errPanelTrustSignature {
t.Fatalf("want errPanelTrustSignature, got %v", err)
}
}
func TestPanelTrustRejectsExpiredStatement(t *testing.T) {
now := time.Now()
claim := newClaim(now.Add(-10 * time.Minute))
header := claim.signFor([]byte(testPanelSecret), http.MethodGet, "/api/peers")
if _, err := parsePanelClaim(header, []byte(testPanelSecret), http.MethodGet, "/api/peers", now); err != errPanelTrustExpired {
t.Fatalf("want errPanelTrustExpired, got %v", err)
}
}
func TestPanelTrustRejectsStatementFromTheFuture(t *testing.T) {
now := time.Now()
claim := newClaim(now.Add(10 * time.Minute))
header := claim.signFor([]byte(testPanelSecret), http.MethodGet, "/api/peers")
if _, err := parsePanelClaim(header, []byte(testPanelSecret), http.MethodGet, "/api/peers", now); err != errPanelTrustExpired {
t.Fatalf("want errPanelTrustExpired, got %v", err)
}
}
func TestPanelTrustRejectsOverlongTTL(t *testing.T) {
now := time.Now()
claim := newClaim(now)
claim.Expires = now.Add(30 * time.Minute)
header := claim.signFor([]byte(testPanelSecret), http.MethodGet, "/api/peers")
if _, err := parsePanelClaim(header, []byte(testPanelSecret), http.MethodGet, "/api/peers", now); err != errPanelTrustMalformed {
t.Fatalf("want errPanelTrustMalformed for an overlong TTL, got %v", err)
}
}
func TestPanelTrustRejectsReuseOnAnotherEndpoint(t *testing.T) {
now := time.Now()
claim := newClaim(now)
header := claim.signFor([]byte(testPanelSecret), http.MethodGet, "/api/peers")
// Same header, a different path: the statement no longer matches.
if _, err := parsePanelClaim(header, []byte(testPanelSecret), http.MethodGet, "/api/users", now); err != errPanelTrustSignature {
t.Fatalf("want errPanelTrustSignature for a cross-endpoint replay, got %v", err)
}
// Same header, a different method (a write): refused.
if _, err := parsePanelClaim(header, []byte(testPanelSecret), http.MethodPost, "/api/peers", now); err != errPanelTrustSignature {
t.Fatalf("want errPanelTrustSignature for a cross-method replay, got %v", err)
}
}
func TestPanelTrustRejectsReplay(t *testing.T) {
now := time.Now()
claim := newClaim(now)
header := claim.signFor([]byte(testPanelSecret), http.MethodGet, "/api/peers")
s := &Server{}
s.SetPanelTrustSecret(testPanelSecret)
first := httptest.NewRequest(http.MethodGet, "/api/peers", nil)
first.Header.Set(PanelTrustHeader, header)
first.RemoteAddr = "127.0.0.1:5555"
if _, err := s.verifyPanelTrust(first); err != nil {
t.Fatalf("first use should pass, got %v", err)
}
second := httptest.NewRequest(http.MethodGet, "/api/peers", nil)
second.Header.Set(PanelTrustHeader, header)
second.RemoteAddr = "127.0.0.1:5556"
if _, err := s.verifyPanelTrust(second); err != errPanelTrustReplay {
t.Fatalf("want errPanelTrustReplay, got %v", err)
}
}
func TestPanelTrustOnlyFromAllowedPeer(t *testing.T) {
t.Setenv("PANEL_TRUST_ALLOWED_HOSTS", "")
s := &Server{}
local := httptest.NewRequest(http.MethodGet, "/api/peers", nil)
local.RemoteAddr = "127.0.0.1:5000"
if !s.panelTrustPeerAllowed(local) {
t.Fatal("loopback should be allowed")
}
remote := httptest.NewRequest(http.MethodGet, "/api/peers", nil)
remote.RemoteAddr = "203.0.113.7:5000"
if s.panelTrustPeerAllowed(remote) {
t.Fatal("a public address must not be allowed by default")
}
t.Setenv("PANEL_TRUST_ALLOWED_HOSTS", "172.18.0.0/16")
docker := httptest.NewRequest(http.MethodGet, "/api/peers", nil)
docker.RemoteAddr = "172.18.0.4:5000"
if !s.panelTrustPeerAllowed(docker) {
t.Fatal("an allowlisted container network should be allowed")
}
}
func TestPanelTrustDoesNotRaiseRole(t *testing.T) {
// No database: the claim is used, but only for a role that may act on the
// API at all. Device and pro roles exist for other transports.
s := &Server{}
if got := s.resolvePanelRole(panelClaim{Subject: "x", Role: "device"}); got != "" {
t.Fatalf("device role must not be accepted, got %q", got)
}
if got := s.resolvePanelRole(panelClaim{Subject: "x", Role: "pro"}); got != "" {
t.Fatalf("pro role must not be accepted, got %q", got)
}
if got := s.resolvePanelRole(panelClaim{Subject: "x", Role: "not-a-role"}); got != "" {
t.Fatalf("unknown role must not be accepted, got %q", got)
}
if got := s.resolvePanelRole(panelClaim{Subject: "x", Role: "operator"}); got != "operator" {
t.Fatalf("a known operator role should pass, got %q", got)
}
}
func TestPanelTrustDisabledKeepsLegacyAuth(t *testing.T) {
s := &Server{}
if s.panelTrustEnabled() {
t.Fatal("bridge must be off without a secret")
}
req := httptest.NewRequest(http.MethodGet, "/api/peers", nil)
// No credentials at all: the usual 401 path, not a trust decision.
if _, _, ok := s.authenticateRequest(req); ok {
t.Fatal("an unauthenticated request must not pass")
}
}
+13
View File
@@ -89,6 +89,8 @@ type Server struct {
oidcProvider *auth.OIDCProvider // OIDC/OAuth2 auth provider (nil if not configured)
clientTFASessions *tfaSessionStore
panelStore db.PanelSyncStore // device groups, folders, ACL (PostgreSQL or legacy auth.db)
panelTrustSecret []byte // HMAC key for panel-originated requests (nil = bridge off)
panelNonces *panelNonceCache // replay window for verified panel statements
timeSync *timesync.Service
billing *billing.Service
peerVault *peervault.Vault // AES-GCM for org peer credentials (#367)
@@ -125,6 +127,7 @@ func New(cfg *config.Config, database db.Database, peerMap *peer.Map, relaySrv *
pairingLimiter: ratelimit.NewIPLimiter(10, 1*time.Minute, 5*time.Minute),
clientTFASessions: newTFASessionStore(),
secureClientKeys: make(map[string][32]byte),
panelNonces: newPanelNonceCache(),
}
}
@@ -520,6 +523,16 @@ func (s *Server) Start(ctx context.Context) error {
mux.HandleFunc("POST /api/help/requests/{id}/acknowledge", s.requirePermission(auth.PermChatAccess, s.handleAcknowledgeHelpRequest))
mux.HandleFunc("POST /api/help/requests/{id}/resolve", s.requirePermission(auth.PermChatAccess, s.handleResolveHelpRequest))
// Panel grouping — device groups, their members and ACL, folders, grants.
// Go owns these writes (strangler stage P2); the RustDesk client reads the
// same tables through /api/device-group/accessible and /api/peers/list.
s.registerPanelGroupRoutes(mux)
// Panel authorization catalog — the console's single source of section and
// role-default definitions (strangler stage P3). Every signed-in principal
// may read it: each role needs it to render its own navigation.
mux.HandleFunc("GET /api/panel/catalog", s.handlePanelCatalog)
// Time sync / billing (commercialization)
mux.HandleFunc("GET /api/timesync/status", s.requirePermission(auth.PermBillingView, s.handleTimeSyncStatus))
mux.HandleFunc("POST /api/timesync/check", s.requirePermission(auth.PermServerConfig, s.handleTimeSyncCheck))
+34 -1
View File
@@ -209,9 +209,15 @@ func TestMigrationBackwardCompatible(t *testing.T) {
db := newTestDB(t)
// Simulate an existing instance: drop the new tables, then re-run Migrate.
// Dependents go first — group members and ACL reference device_groups and
// user_groups, so SQLite refuses to drop a parent while they exist.
for _, tbl := range []string{
"audit_connections", "audit_files", "audit_alarms",
"user_groups", "device_groups", "strategies",
"device_group_user_access", "device_group_user_group_access",
"device_group_members", "user_group_members",
"device_folder_assignments", "user_peer_grants",
"folders",
"strategies", "device_groups", "user_groups",
} {
if _, err := db.db.Exec("DROP TABLE IF EXISTS " + tbl); err != nil {
t.Fatalf("drop %s: %v", tbl, err)
@@ -232,6 +238,33 @@ func TestMigrationBackwardCompatible(t *testing.T) {
t.Fatalf("InsertAuditConnection after re-migrate: %v", err)
}
// Panel grouping tables are part of the migration too (strangler stage P2):
// Go owns these writes, so an upgraded instance must get them.
if err := db.CreatePanelFolder(&Folder{Name: "Upgraded"}); err != nil {
t.Fatalf("CreatePanelFolder after re-migrate: %v", err)
}
folders, err := db.ListPanelFolders()
if err != nil {
t.Fatalf("ListPanelFolders: %v", err)
}
if len(folders) != 1 || folders[0].Name != "Upgraded" {
t.Errorf("folders = %+v, want the created one", folders)
}
group := &DeviceGroup{Name: "Upgraded group"}
if err := db.CreateDeviceGroup(group); err != nil {
t.Fatalf("CreateDeviceGroup: %v", err)
}
if err := db.SetDeviceGroupPeers(group.GUID, []string{"KEEP1", "PEER2"}); err != nil {
t.Fatalf("SetDeviceGroupPeers: %v", err)
}
peers, err := db.ListDeviceGroupPeerIDs(group.GUID)
if err != nil {
t.Fatalf("ListDeviceGroupPeerIDs: %v", err)
}
if len(peers) != 2 {
t.Errorf("group members = %v, want 2", peers)
}
// Pre-existing data must still be present.
p, err := db.GetPeer("KEEP1")
if err != nil {
+63
View File
@@ -0,0 +1,63 @@
package db
// Panel-owned device grouping: members, ACL and folders.
//
// The Node console used to write these tables and Go only read them
// (db/panel_sync.go, db/console_auth.go). Go now owns the writes as well
// (docs/important/console-backend-strangler.md, stage P2), so the reading and
// writing paths share one implementation and one set of SQL statements.
//
// A group is identified by its GUID on the wire and by its numeric id in the
// tables; helpers below resolve one to the other so handlers never have to.
//
// The method names carry a "Panel" prefix where the read-only PanelSyncStore
// already used the shorter name with a different return type — the two
// interfaces coexist on purpose while the RustDesk sync path is unchanged.
// Folder is a panel folder chip (the device list's left rail).
type Folder struct {
ID int64 `json:"id"`
Name string `json:"name"`
Color string `json:"color"`
Icon string `json:"icon"`
SortOrder int `json:"sort_order"`
CreatedAt string `json:"created_at"`
}
// DeviceGroupACL is who may see the devices of a group. An empty ACL means
// "everyone who may view devices", matching the console's behaviour.
type DeviceGroupACL struct {
AllowedUsers []string `json:"allowed_users"` // usernames
AllowedUserGroups []string `json:"allowed_user_groups"` // user group GUIDs
}
// PanelGroupStore is the write side of panel device grouping. Implemented by
// both database engines; kept separate from Database so the interface stays
// readable.
type PanelGroupStore interface {
// Membership: peer IDs in a device group.
ListDeviceGroupPeerIDs(groupGUID string) ([]string, error)
SetDeviceGroupPeers(groupGUID string, peerIDs []string) error
// ACL: usernames and user-group GUIDs allowed to see the group's devices.
GetDeviceGroupACL(groupGUID string) (*DeviceGroupACL, error)
SetDeviceGroupACL(groupGUID string, acl *DeviceGroupACL) error
// Folders.
ListPanelFolders() ([]*Folder, error)
CreatePanelFolder(f *Folder) error
UpdatePanelFolder(id int64, f *Folder) error
DeletePanelFolder(id int64) error
SetDevicePanelFolder(peerID string, folderID int64) error // folderID 0 unassigns
ListPanelDeviceFolderAssignments() (map[string]int64, error)
// Per-user device grants (the console's "allow this person this device").
ListPanelUserPeerGrants(userID int64) ([]string, error)
SetUserPeerGrants(userID int64, peerIDs []string) error
}
// Compile-time checks: both engines must satisfy the store.
var (
_ PanelGroupStore = (*SQLiteDB)(nil)
_ PanelGroupStore = (*PostgresDB)(nil)
)
@@ -0,0 +1,322 @@
package db
import (
"context"
"errors"
"strings"
"github.com/jackc/pgx/v5"
)
// PostgreSQL implementation of PanelGroupStore (see panel_groups.go).
// Statements mirror the SQLite ones; only placeholders and the
// "no such table" guard differ.
func (pg *PostgresDB) deviceGroupIDPostgres(guid string) (int64, error) {
var id int64
err := pg.pool.QueryRow(pg.ctx,
`SELECT id FROM device_groups WHERE guid = $1`, strings.TrimSpace(guid)).Scan(&id)
return id, err
}
// ListDeviceGroupPeerIDs returns the peer IDs assigned to a device group.
func (pg *PostgresDB) ListDeviceGroupPeerIDs(groupGUID string) ([]string, error) {
if !pg.pgHasTable("device_group_members") {
return nil, nil
}
id, err := pg.deviceGroupIDPostgres(groupGUID)
if errors.Is(err, pgx.ErrNoRows) {
return nil, nil
}
if err != nil {
return nil, err
}
rows, err := pg.pool.Query(pg.ctx,
`SELECT peer_id FROM device_group_members WHERE device_group_id = $1 ORDER BY peer_id ASC`, id)
if err != nil {
return nil, err
}
defer rows.Close()
var out []string
for rows.Next() {
var peerID string
if err := rows.Scan(&peerID); err != nil {
return nil, err
}
if peerID = strings.TrimSpace(peerID); peerID != "" {
out = append(out, peerID)
}
}
return out, rows.Err()
}
// SetDeviceGroupPeers replaces the group's membership in one transaction.
func (pg *PostgresDB) SetDeviceGroupPeers(groupGUID string, peerIDs []string) error {
id, err := pg.deviceGroupIDPostgres(groupGUID)
if err != nil {
return err
}
ctx, cancel := pg.withTimeout()
defer cancel()
tx, err := pg.pool.Begin(ctx)
if err != nil {
return err
}
defer func() { _ = tx.Rollback(ctx) }()
if _, err := tx.Exec(ctx, `DELETE FROM device_group_members WHERE device_group_id = $1`, id); err != nil {
return err
}
for _, peerID := range dedupeStrings(peerIDs) {
if _, err := tx.Exec(ctx,
`INSERT INTO device_group_members (device_group_id, peer_id) VALUES ($1, $2)`, id, peerID); err != nil {
return err
}
}
return tx.Commit(ctx)
}
// GetDeviceGroupACL reads the usernames and user-group GUIDs allowed to see
// the group's devices.
func (pg *PostgresDB) GetDeviceGroupACL(groupGUID string) (*DeviceGroupACL, error) {
acl := &DeviceGroupACL{AllowedUsers: []string{}, AllowedUserGroups: []string{}}
id, err := pg.deviceGroupIDPostgres(groupGUID)
if errors.Is(err, pgx.ErrNoRows) {
return nil, nil
}
if err != nil {
return nil, err
}
if pg.pgHasTable("device_group_user_access") {
rows, err := pg.pool.Query(pg.ctx, `
SELECT u.username FROM device_group_user_access a
INNER JOIN users u ON u.id = a.user_id
WHERE a.device_group_id = $1
ORDER BY u.username ASC`, id)
if err != nil {
return nil, err
}
users, err := scanStrings(rows)
if err != nil {
return nil, err
}
acl.AllowedUsers = users
}
if pg.pgHasTable("device_group_user_group_access") {
rows, err := pg.pool.Query(pg.ctx, `
SELECT ug.guid FROM device_group_user_group_access a
INNER JOIN user_groups ug ON ug.id = a.user_group_id
WHERE a.device_group_id = $1
ORDER BY ug.name ASC`, id)
if err != nil {
return nil, err
}
guids, err := scanStrings(rows)
if err != nil {
return nil, err
}
acl.AllowedUserGroups = guids
}
return acl, nil
}
// SetDeviceGroupACL replaces the group's ACL in one transaction.
func (pg *PostgresDB) SetDeviceGroupACL(groupGUID string, acl *DeviceGroupACL) error {
id, err := pg.deviceGroupIDPostgres(groupGUID)
if err != nil {
return err
}
ctx, cancel := pg.withTimeout()
defer cancel()
tx, err := pg.pool.Begin(ctx)
if err != nil {
return err
}
defer func() { _ = tx.Rollback(ctx) }()
if _, err := tx.Exec(ctx, `DELETE FROM device_group_user_access WHERE device_group_id = $1`, id); err != nil {
return err
}
if _, err := tx.Exec(ctx, `DELETE FROM device_group_user_group_access WHERE device_group_id = $1`, id); err != nil {
return err
}
if acl != nil {
for _, username := range dedupeStrings(acl.AllowedUsers) {
if _, err := tx.Exec(ctx, `
INSERT INTO device_group_user_access (device_group_id, user_id)
SELECT $1, id FROM users WHERE username = $2
ON CONFLICT DO NOTHING`, id, username); err != nil {
return err
}
}
for _, guid := range dedupeStrings(acl.AllowedUserGroups) {
if _, err := tx.Exec(ctx, `
INSERT INTO device_group_user_group_access (device_group_id, user_group_id)
SELECT $1, id FROM user_groups WHERE guid = $2
ON CONFLICT DO NOTHING`, id, guid); err != nil {
return err
}
}
}
return tx.Commit(ctx)
}
// ── Folders ───────────────────────────────────────────────────────────
// ListFolders returns every panel folder.
func (pg *PostgresDB) ListPanelFolders() ([]*Folder, error) {
if !pg.pgHasTable("folders") {
return nil, nil
}
rows, err := pg.pool.Query(pg.ctx, `
SELECT id, name, COALESCE(color,''), COALESCE(icon,''), COALESCE(sort_order,0), COALESCE(created_at::text,'')
FROM folders ORDER BY sort_order ASC, name ASC`)
if err != nil {
return nil, err
}
defer rows.Close()
var out []*Folder
for rows.Next() {
f := &Folder{}
if err := rows.Scan(&f.ID, &f.Name, &f.Color, &f.Icon, &f.SortOrder, &f.CreatedAt); err != nil {
return nil, err
}
out = append(out, f)
}
return out, rows.Err()
}
// CreateFolder inserts a folder and reports the new id.
func (pg *PostgresDB) CreatePanelFolder(f *Folder) error {
return pg.pool.QueryRow(pg.ctx,
`INSERT INTO folders (name, color, icon, sort_order) VALUES ($1, $2, $3, $4) RETURNING id`,
strings.TrimSpace(f.Name), f.Color, f.Icon, f.SortOrder).Scan(&f.ID)
}
// UpdateFolder changes a folder's name and presentation.
func (pg *PostgresDB) UpdatePanelFolder(id int64, f *Folder) error {
_, err := pg.pool.Exec(pg.ctx,
`UPDATE folders SET name = $1, color = $2, icon = $3, sort_order = $4 WHERE id = $5`,
strings.TrimSpace(f.Name), f.Color, f.Icon, f.SortOrder, id)
return err
}
// DeleteFolder removes a folder and its assignments.
func (pg *PostgresDB) DeletePanelFolder(id int64) error {
ctx, cancel := pg.withTimeout()
defer cancel()
tx, err := pg.pool.Begin(ctx)
if err != nil {
return err
}
defer func() { _ = tx.Rollback(ctx) }()
if _, err := tx.Exec(ctx, `DELETE FROM device_folder_assignments WHERE folder_id = $1`, id); err != nil {
return err
}
if _, err := tx.Exec(ctx, `DELETE FROM folders WHERE id = $1`, id); err != nil {
return err
}
return tx.Commit(ctx)
}
// SetDeviceFolder assigns a device to a folder, or clears it when folderID is 0.
func (pg *PostgresDB) SetDevicePanelFolder(peerID string, folderID int64) error {
peerID = strings.TrimSpace(peerID)
if peerID == "" {
return errors.New("device id is required")
}
if folderID <= 0 {
_, err := pg.pool.Exec(pg.ctx,
`DELETE FROM device_folder_assignments WHERE device_id = $1`, peerID)
return err
}
_, err := pg.pool.Exec(pg.ctx, `
INSERT INTO device_folder_assignments (device_id, folder_id) VALUES ($1, $2)
ON CONFLICT (device_id) DO UPDATE SET folder_id = EXCLUDED.folder_id`, peerID, folderID)
return err
}
// ListDeviceFolderAssignments returns device id → folder id.
func (pg *PostgresDB) ListPanelDeviceFolderAssignments() (map[string]int64, error) {
out := make(map[string]int64)
if !pg.pgHasTable("device_folder_assignments") {
return out, nil
}
rows, err := pg.pool.Query(pg.ctx, `SELECT device_id, folder_id FROM device_folder_assignments`)
if err != nil {
return nil, err
}
defer rows.Close()
for rows.Next() {
var deviceID string
var folderID int64
if err := rows.Scan(&deviceID, &folderID); err != nil {
return nil, err
}
if deviceID = strings.TrimSpace(deviceID); deviceID != "" {
out[deviceID] = folderID
}
}
return out, rows.Err()
}
// ── Per-user device grants ────────────────────────────────────────────
// ListUserPeerGrants returns the peer IDs granted directly to one user.
func (pg *PostgresDB) ListPanelUserPeerGrants(userID int64) ([]string, error) {
if userID <= 0 || !pg.pgHasTable("user_peer_grants") {
return nil, nil
}
rows, err := pg.pool.Query(pg.ctx,
`SELECT peer_id FROM user_peer_grants WHERE user_id = $1 ORDER BY peer_id ASC`, userID)
if err != nil {
return nil, err
}
return scanStrings(rows)
}
// SetUserPeerGrants replaces one user's direct device grants.
func (pg *PostgresDB) SetUserPeerGrants(userID int64, peerIDs []string) error {
if userID <= 0 {
return errors.New("user id is required")
}
ctx, cancel := pg.withTimeout()
defer cancel()
tx, err := pg.pool.Begin(ctx)
if err != nil {
return err
}
defer func() { _ = tx.Rollback(ctx) }()
if _, err := tx.Exec(ctx, `DELETE FROM user_peer_grants WHERE user_id = $1`, userID); err != nil {
return err
}
for _, peerID := range dedupeStrings(peerIDs) {
if _, err := tx.Exec(ctx,
`INSERT INTO user_peer_grants (user_id, peer_id) VALUES ($1, $2)`, userID, peerID); err != nil {
return err
}
}
return tx.Commit(ctx)
}
// withTimeout derives a context for a multi-statement write.
func (pg *PostgresDB) withTimeout() (context.Context, context.CancelFunc) {
if pg.queryTimeout <= 0 {
return context.WithCancel(pg.ctx)
}
return context.WithTimeout(pg.ctx, pg.queryTimeout)
}
// scanStrings drains a single-column text result.
func scanStrings(rows pgx.Rows) ([]string, error) {
defer rows.Close()
out := []string{}
for rows.Next() {
var value string
if err := rows.Scan(&value); err != nil {
return nil, err
}
if value = strings.TrimSpace(value); value != "" {
out = append(out, value)
}
}
return out, rows.Err()
}
+388
View File
@@ -0,0 +1,388 @@
package db
import (
"database/sql"
"strings"
)
// SQLite implementation of PanelGroupStore (see panel_groups.go).
//
// Every statement touches only the panel-owned tables, and every write is
// scoped to one group / folder inside a transaction, so a half-applied ACL can
// never be observed by the RustDesk sync reader in this process.
func (s *SQLiteDB) deviceGroupID(guid string) (int64, error) {
var id int64
err := s.db.QueryRow(`SELECT id FROM device_groups WHERE guid = ?`, strings.TrimSpace(guid)).Scan(&id)
return id, err
}
// ListDeviceGroupPeerIDs returns the peer IDs assigned to a device group.
func (s *SQLiteDB) ListDeviceGroupPeerIDs(groupGUID string) ([]string, error) {
s.mu.RLock()
defer s.mu.RUnlock()
id, err := s.deviceGroupID(groupGUID)
if err == sql.ErrNoRows {
return nil, nil
}
if err != nil {
return nil, err
}
rows, err := s.db.Query(
`SELECT peer_id FROM device_group_members WHERE device_group_id = ? ORDER BY peer_id ASC`, id)
if err != nil {
if strings.Contains(err.Error(), "no such table") {
return nil, nil
}
return nil, err
}
defer rows.Close()
var out []string
for rows.Next() {
var peerID string
if err := rows.Scan(&peerID); err != nil {
return nil, err
}
if peerID = strings.TrimSpace(peerID); peerID != "" {
out = append(out, peerID)
}
}
return out, rows.Err()
}
// SetDeviceGroupPeers replaces the group's membership in one transaction.
func (s *SQLiteDB) SetDeviceGroupPeers(groupGUID string, peerIDs []string) error {
s.mu.Lock()
defer s.mu.Unlock()
id, err := s.deviceGroupID(groupGUID)
if err != nil {
return err
}
tx, err := s.db.Begin()
if err != nil {
return err
}
defer func() { _ = tx.Rollback() }()
if _, err := tx.Exec(`DELETE FROM device_group_members WHERE device_group_id = ?`, id); err != nil {
return err
}
seen := make(map[string]bool, len(peerIDs))
for _, raw := range peerIDs {
peerID := strings.TrimSpace(raw)
if peerID == "" || seen[peerID] {
continue
}
seen[peerID] = true
if _, err := tx.Exec(
`INSERT INTO device_group_members (device_group_id, peer_id) VALUES (?, ?)`, id, peerID); err != nil {
return err
}
}
return tx.Commit()
}
// GetDeviceGroupACL reads the usernames and user-group GUIDs allowed to see
// the group's devices.
func (s *SQLiteDB) GetDeviceGroupACL(groupGUID string) (*DeviceGroupACL, error) {
s.mu.RLock()
defer s.mu.RUnlock()
acl := &DeviceGroupACL{AllowedUsers: []string{}, AllowedUserGroups: []string{}}
id, err := s.deviceGroupID(groupGUID)
if err == sql.ErrNoRows {
return nil, nil
}
if err != nil {
return nil, err
}
users, err := s.aclUsernames(id)
if err != nil {
return nil, err
}
groups, err := s.aclUserGroupGUIDs(id)
if err != nil {
return nil, err
}
acl.AllowedUsers = users
acl.AllowedUserGroups = groups
return acl, nil
}
func (s *SQLiteDB) aclUsernames(groupID int64) ([]string, error) {
rows, err := s.db.Query(`
SELECT u.username FROM device_group_user_access a
INNER JOIN users u ON u.id = a.user_id
WHERE a.device_group_id = ?
ORDER BY u.username ASC`, groupID)
if err != nil {
if strings.Contains(err.Error(), "no such table") {
return []string{}, nil
}
return nil, err
}
defer rows.Close()
out := []string{}
for rows.Next() {
var name string
if err := rows.Scan(&name); err != nil {
return nil, err
}
if name = strings.TrimSpace(name); name != "" {
out = append(out, name)
}
}
return out, rows.Err()
}
func (s *SQLiteDB) aclUserGroupGUIDs(groupID int64) ([]string, error) {
rows, err := s.db.Query(`
SELECT ug.guid FROM device_group_user_group_access a
INNER JOIN user_groups ug ON ug.id = a.user_group_id
WHERE a.device_group_id = ?
ORDER BY ug.name ASC`, groupID)
if err != nil {
if strings.Contains(err.Error(), "no such table") {
return []string{}, nil
}
return nil, err
}
defer rows.Close()
out := []string{}
for rows.Next() {
var guid string
if err := rows.Scan(&guid); err != nil {
return nil, err
}
if guid = strings.TrimSpace(guid); guid != "" {
out = append(out, guid)
}
}
return out, rows.Err()
}
// SetDeviceGroupACL replaces the group's ACL in one transaction. Usernames that
// no longer exist are ignored rather than failing the whole write, so a stale
// entry in a form does not block saving the rest.
func (s *SQLiteDB) SetDeviceGroupACL(groupGUID string, acl *DeviceGroupACL) error {
s.mu.Lock()
defer s.mu.Unlock()
id, err := s.deviceGroupID(groupGUID)
if err != nil {
return err
}
tx, err := s.db.Begin()
if err != nil {
return err
}
defer func() { _ = tx.Rollback() }()
if _, err := tx.Exec(`DELETE FROM device_group_user_access WHERE device_group_id = ?`, id); err != nil {
return err
}
if _, err := tx.Exec(`DELETE FROM device_group_user_group_access WHERE device_group_id = ?`, id); err != nil {
return err
}
if acl != nil {
for _, username := range dedupeStrings(acl.AllowedUsers) {
if _, err := tx.Exec(`
INSERT OR IGNORE INTO device_group_user_access (device_group_id, user_id)
SELECT ?, id FROM users WHERE username = ?`, id, username); err != nil {
return err
}
}
for _, guid := range dedupeStrings(acl.AllowedUserGroups) {
if _, err := tx.Exec(`
INSERT OR IGNORE INTO device_group_user_group_access (device_group_id, user_group_id)
SELECT ?, id FROM user_groups WHERE guid = ?`, id, guid); err != nil {
return err
}
}
}
return tx.Commit()
}
// ── Folders ───────────────────────────────────────────────────────────
// ListFolders returns every panel folder.
func (s *SQLiteDB) ListPanelFolders() ([]*Folder, error) {
s.mu.RLock()
defer s.mu.RUnlock()
rows, err := s.db.Query(
`SELECT id, name, COALESCE(color,''), COALESCE(icon,''), COALESCE(sort_order,0), COALESCE(created_at,'')
FROM folders ORDER BY sort_order ASC, name ASC`)
if err != nil {
if strings.Contains(err.Error(), "no such table") {
return nil, nil
}
return nil, err
}
defer rows.Close()
var out []*Folder
for rows.Next() {
f := &Folder{}
if err := rows.Scan(&f.ID, &f.Name, &f.Color, &f.Icon, &f.SortOrder, &f.CreatedAt); err != nil {
return nil, err
}
out = append(out, f)
}
return out, rows.Err()
}
// CreateFolder inserts a folder and reports the new id.
func (s *SQLiteDB) CreatePanelFolder(f *Folder) error {
s.mu.Lock()
defer s.mu.Unlock()
res, err := s.db.Exec(
`INSERT INTO folders (name, color, icon, sort_order) VALUES (?, ?, ?, ?)`,
strings.TrimSpace(f.Name), f.Color, f.Icon, f.SortOrder)
if err != nil {
return err
}
if id, err := res.LastInsertId(); err == nil {
f.ID = id
}
return nil
}
// UpdateFolder changes a folder's name and presentation.
func (s *SQLiteDB) UpdatePanelFolder(id int64, f *Folder) error {
s.mu.Lock()
defer s.mu.Unlock()
_, err := s.db.Exec(
`UPDATE folders SET name = ?, color = ?, icon = ?, sort_order = ? WHERE id = ?`,
strings.TrimSpace(f.Name), f.Color, f.Icon, f.SortOrder, id)
return err
}
// DeleteFolder removes a folder; assignments go with it (foreign key).
func (s *SQLiteDB) DeletePanelFolder(id int64) error {
s.mu.Lock()
defer s.mu.Unlock()
tx, err := s.db.Begin()
if err != nil {
return err
}
defer func() { _ = tx.Rollback() }()
if _, err := tx.Exec(`DELETE FROM device_folder_assignments WHERE folder_id = ?`, id); err != nil {
return err
}
if _, err := tx.Exec(`DELETE FROM folders WHERE id = ?`, id); err != nil {
return err
}
return tx.Commit()
}
// SetDeviceFolder assigns a device to a folder, or clears it when folderID is 0.
func (s *SQLiteDB) SetDevicePanelFolder(peerID string, folderID int64) error {
s.mu.Lock()
defer s.mu.Unlock()
peerID = strings.TrimSpace(peerID)
if peerID == "" {
return sql.ErrNoRows
}
if folderID <= 0 {
_, err := s.db.Exec(`DELETE FROM device_folder_assignments WHERE device_id = ?`, peerID)
return err
}
_, err := s.db.Exec(
`INSERT INTO device_folder_assignments (device_id, folder_id) VALUES (?, ?)
ON CONFLICT(device_id) DO UPDATE SET folder_id = excluded.folder_id`, peerID, folderID)
return err
}
// ListDeviceFolderAssignments returns device id → folder id.
func (s *SQLiteDB) ListPanelDeviceFolderAssignments() (map[string]int64, error) {
s.mu.RLock()
defer s.mu.RUnlock()
out := make(map[string]int64)
rows, err := s.db.Query(`SELECT device_id, folder_id FROM device_folder_assignments`)
if err != nil {
if strings.Contains(err.Error(), "no such table") {
return out, nil
}
return nil, err
}
defer rows.Close()
for rows.Next() {
var deviceID string
var folderID int64
if err := rows.Scan(&deviceID, &folderID); err != nil {
return nil, err
}
if deviceID = strings.TrimSpace(deviceID); deviceID != "" {
out[deviceID] = folderID
}
}
return out, rows.Err()
}
// ── Per-user device grants ────────────────────────────────────────────
// ListUserPeerGrants returns the peer IDs granted directly to one user.
func (s *SQLiteDB) ListPanelUserPeerGrants(userID int64) ([]string, error) {
s.mu.RLock()
defer s.mu.RUnlock()
if userID <= 0 {
return nil, nil
}
rows, err := s.db.Query(
`SELECT peer_id FROM user_peer_grants WHERE user_id = ? ORDER BY peer_id ASC`, userID)
if err != nil {
if strings.Contains(err.Error(), "no such table") {
return nil, nil
}
return nil, err
}
defer rows.Close()
var out []string
for rows.Next() {
var peerID string
if err := rows.Scan(&peerID); err != nil {
return nil, err
}
if peerID = strings.TrimSpace(peerID); peerID != "" {
out = append(out, peerID)
}
}
return out, rows.Err()
}
// SetUserPeerGrants replaces one user's direct device grants.
func (s *SQLiteDB) SetUserPeerGrants(userID int64, peerIDs []string) error {
s.mu.Lock()
defer s.mu.Unlock()
if userID <= 0 {
return sql.ErrNoRows
}
tx, err := s.db.Begin()
if err != nil {
return err
}
defer func() { _ = tx.Rollback() }()
if _, err := tx.Exec(`DELETE FROM user_peer_grants WHERE user_id = ?`, userID); err != nil {
return err
}
for _, raw := range dedupeStrings(peerIDs) {
if _, err := tx.Exec(
`INSERT INTO user_peer_grants (user_id, peer_id) VALUES (?, ?)`, userID, raw); err != nil {
return err
}
}
return tx.Commit()
}
// dedupeStrings trims, drops empties and removes duplicates while keeping order.
func dedupeStrings(values []string) []string {
if len(values) == 0 {
return nil
}
seen := make(map[string]bool, len(values))
out := make([]string, 0, len(values))
for _, raw := range values {
value := strings.TrimSpace(raw)
if value == "" || seen[value] {
continue
}
seen[value] = true
out = append(out, value)
}
return out
}
+58
View File
@@ -590,6 +590,64 @@ func (s *SQLiteDB) Migrate() error {
tag_filter TEXT DEFAULT '',
created_at TEXT DEFAULT (datetime('now'))
)`,
// Group membership and ACL. These tables used to be created only by the
// Node console (services/dbAdapter.js); Go now owns the writes for
// device groups, folders and ACL, so it creates them as well. Columns
// match the Node schema so an existing database keeps working.
`CREATE TABLE IF NOT EXISTS device_group_members (
device_group_id INTEGER NOT NULL,
peer_id TEXT NOT NULL,
created_at TEXT DEFAULT (datetime('now')),
PRIMARY KEY (device_group_id, peer_id),
FOREIGN KEY (device_group_id) REFERENCES device_groups(id) ON DELETE CASCADE
)`,
`CREATE INDEX IF NOT EXISTS idx_device_group_members_peer ON device_group_members (peer_id)`,
`CREATE TABLE IF NOT EXISTS user_group_members (
user_group_id INTEGER NOT NULL,
user_id INTEGER NOT NULL,
created_at TEXT DEFAULT (datetime('now')),
PRIMARY KEY (user_group_id, user_id),
FOREIGN KEY (user_group_id) REFERENCES user_groups(id) ON DELETE CASCADE,
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
)`,
`CREATE TABLE IF NOT EXISTS device_group_user_access (
device_group_id INTEGER NOT NULL,
user_id INTEGER NOT NULL,
created_at TEXT DEFAULT (datetime('now')),
PRIMARY KEY (device_group_id, user_id),
FOREIGN KEY (device_group_id) REFERENCES device_groups(id) ON DELETE CASCADE,
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
)`,
`CREATE TABLE IF NOT EXISTS device_group_user_group_access (
device_group_id INTEGER NOT NULL,
user_group_id INTEGER NOT NULL,
created_at TEXT DEFAULT (datetime('now')),
PRIMARY KEY (device_group_id, user_group_id),
FOREIGN KEY (device_group_id) REFERENCES device_groups(id) ON DELETE CASCADE,
FOREIGN KEY (user_group_id) REFERENCES user_groups(id) ON DELETE CASCADE
)`,
`CREATE TABLE IF NOT EXISTS folders (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
color TEXT DEFAULT '#6366f1',
icon TEXT DEFAULT 'folder',
sort_order INTEGER DEFAULT 0,
created_at TEXT DEFAULT (datetime('now'))
)`,
`CREATE TABLE IF NOT EXISTS device_folder_assignments (
device_id TEXT PRIMARY KEY NOT NULL,
folder_id INTEGER NOT NULL,
assigned_at TEXT DEFAULT (datetime('now')),
FOREIGN KEY (folder_id) REFERENCES folders(id) ON DELETE CASCADE
)`,
`CREATE TABLE IF NOT EXISTS user_peer_grants (
user_id INTEGER NOT NULL,
peer_id TEXT NOT NULL,
granted_at TEXT DEFAULT (datetime('now')),
PRIMARY KEY (user_id, peer_id),
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
)`,
`CREATE INDEX IF NOT EXISTS idx_user_peer_grants_user ON user_peer_grants (user_id)`,
`CREATE TABLE IF NOT EXISTS strategies (
id INTEGER PRIMARY KEY AUTOINCREMENT,
guid TEXT UNIQUE NOT NULL,
+19
View File
@@ -508,6 +508,7 @@ func main() {
apiSrv := api.New(cfg, database, sig.PeerMap(), relaySrv, Version)
defer attachPanelSync(apiSrv, billingSvc, database, cfg.DBPath, cfg.AuthDBPath)()
attachPanelTrust(apiSrv)
apiSrv.SetBlocklist(blocklist)
apiSrv.SetBandwidthLimiter(bwLimiter)
apiSrv.SetAuditLogger(auditLogger)
@@ -626,6 +627,7 @@ func main() {
apiSrv := api.New(cfg, database, sig.PeerMap(), nil, Version)
defer attachPanelSync(apiSrv, billingSvc, database, cfg.DBPath, cfg.AuthDBPath)()
attachPanelTrust(apiSrv)
apiSrv.SetBlocklist(blocklist)
apiSrv.SetBandwidthLimiter(bwLimiter)
apiSrv.SetAuditLogger(auditLogger)
@@ -997,6 +999,23 @@ func resolveAuthDBPath(explicit, dbPath string) string {
return explicit
}
// attachPanelTrust wires the panel trust bridge (see api/panel_trust.go).
// The secret is optional: without it the bridge stays off and Go only accepts
// its usual JWT / API-key credentials. It is read from the installer-managed
// .env, which the panel updater appends to and never overwrites.
func attachPanelTrust(apiSrv *api.Server) {
secret := strings.TrimSpace(os.Getenv(api.PanelTrustSecretEnv))
if secret == "" {
log.Printf("[panel-trust] disabled (no %s) — panel requests use API key auth only", api.PanelTrustSecretEnv)
return
}
if len(secret) < 32 {
log.Printf("[panel-trust] WARN: %s is shorter than 32 characters; use a generated value", api.PanelTrustSecretEnv)
}
apiSrv.SetPanelTrustSecret(secret)
log.Printf("[panel-trust] enabled for panel-originated requests")
}
// attachPanelSync wires RustDesk group/folder sync to PostgreSQL, the
// consolidated SQLite store, or a legacy auth.db during the migration window.
func attachPanelSync(apiSrv *api.Server, billingSvc *billing.Service, database db.Database, primaryDBPath, authDBPath string) func() {
+16
View File
@@ -60,6 +60,22 @@ GO_API_PORT=__GO_API_PORT__
HBBS_API_URL=__HBBS_API_URL__
BETTERDESK_API_URL=__BETTERDESK_API_URL__
# Panel trust bridge (docs/important/console-backend-strangler.md, stage P1).
# Shared HMAC secret that lets the Go server authorize requests the Node console
# forwards for a signed-in operator, without Go owning a browser session.
# Leave empty to keep the bridge off (API-key auth only). Generate with:
# node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"
# The installer/updater appends this key when missing and never overwrites it.
PANEL_TRUST_SECRET=
# Optional: non-loopback hosts allowed to present a panel statement (container
# networks). Loopback is always allowed. Comma-separated IPs or CIDRs.
PANEL_TRUST_ALLOWED_HOSTS=
# Panel grouping owner (docs/important/console-backend-strangler.md, stage P2).
# go — the Go server owns device groups, ACL, folders and per-user grants;
# node — the console keeps its own writer (rollback switch, no redeploy).
BACKEND_PANEL_GROUPING=go
# SMTP (optional — can also be configured in Settings → Email)
SMTP_HOST=
SMTP_PORT=587
+5
View File
@@ -178,6 +178,11 @@ module.exports = {
// Device visibility for non-admin roles: open (legacy overlay ACL) or restricted (default-deny).
deviceScopeDefault: (process.env.DEVICE_SCOPE_DEFAULT || 'open').toLowerCase(),
// Panel grouping owner (docs/important/console-backend-strangler.md, stage P2).
// 'go' — the Go server owns device groups, ACL, folders and per-user grants;
// 'node' — the console keeps its own writer (rollback switch).
backendPanelGrouping: (process.env.BACKEND_PANEL_GROUPING || 'go').toLowerCase(),
// HTTPS / SSL
httpsEnabled: (process.env.HTTPS_ENABLED || 'false').toLowerCase() === 'true',
httpsPort: parseInt(process.env.HTTPS_PORT, 10) || 5443,
+81 -3
View File
@@ -9,6 +9,7 @@ const serverBackend = require('../services/serverBackend');
const betterdeskApi = require('../services/betterdeskApi');
const addressBookSync = require('../services/rustdeskAddressBookSync');
const deviceGroupService = require('../services/deviceGroupService');
const panelGrouping = require('../services/panelGrouping');
const tagManagementService = require('../services/tagManagementService');
const { requireAuth, requirePermission, requestHasPermission } = require('../middleware/auth');
const { bodyInt, bodyString, bodyBool, plainBodyObject } = require('../lib/bodyScalars');
@@ -449,6 +450,30 @@ router.post('/api/device-groups', requireAuth, requirePermission('device.edit'),
if (deviceGroupService.folderIdFromGroupGuid(payload.guid) !== null) {
return res.status(400).json({ success: false, error: req.t('devices.folder_group_readonly') });
}
}
// Stage P2: Go owns these writes. The console keeps its own writer as the
// documented rollback (BACKEND_PANEL_GROUPING=node) and as the fallback
// while an older server binary is still deployed.
if (panelGrouping.writesGoToGo()) {
const saved = await panelGrouping.saveGroupToGo({
guid: payload.guid,
name: payload.name,
note: payload.note,
team_id: payload.team_id,
source_type: payload.source_type,
tag_filter: payload.tag_filter,
allowed_users: payload.allowed_users,
allowed_groups: payload.allowed_groups,
}, req);
if (saved) {
await db.logAction(req.session.userId, 'device_group_saved',
`Device group ${saved.name} saved`, req.ip);
return res.json({ success: true, data: saved });
}
}
if (payload.guid) {
group = await db.updateDeviceGroup(
payload.guid,
deviceGroupService.buildDeviceGroupUpdateFields(payload)
@@ -470,6 +495,9 @@ router.post('/api/device-groups', requireAuth, requirePermission('device.edit'),
await db.logAction(req.session.userId, 'device_group_saved', `Device group ${group.name} saved`, req.ip);
res.json({ success: true, data: group });
} catch (err) {
if (err && err.fromGo) {
return res.status(err.status || 502).json({ success: false, error: err.message });
}
console.error('Save device group error:', err);
res.status(500).json({ success: false, error: req.t('errors.server_error') });
}
@@ -491,10 +519,25 @@ router.delete('/api/device-groups/:guid', requireAuth, requirePermission('device
if (deviceGroupService.folderIdFromGroupGuid(guid) !== null) {
return res.status(400).json({ success: false, error: req.t('devices.folder_group_readonly') });
}
// Stage P2: Go owns the delete. Fall through to the panel's own writer
// when the switch says so or the endpoint is not deployed yet.
if (panelGrouping.writesGoToGo()) {
const deleted = await panelGrouping.deleteGroupFromGo(guid, req);
if (deleted) {
await db.logAction(req.session.userId, 'device_group_deleted',
`Device group ${group.name} deleted`, req.ip);
return res.json({ success: true });
}
}
await db.deleteDeviceGroup(guid);
await db.logAction(req.session.userId, 'device_group_deleted', `Device group ${group.name} deleted`, req.ip);
res.json({ success: true });
} catch (err) {
if (err && err.fromGo) {
return res.status(err.status || 502).json({ success: false, error: err.message });
}
console.error('Delete device group error:', err);
res.status(500).json({ success: false, error: req.t('errors.server_error') });
}
@@ -559,14 +602,49 @@ router.put('/api/devices/:id/groups', requireAuth, requirePermission('device.edi
}
const selected = selectedAll.slice(0, 1);
for (const group of manualGroups) {
if (selected.includes(group.guid)) await db.addDeviceToGroup(group.guid, deviceId);
else await db.removeDeviceFromGroup(group.guid, deviceId);
// Stage P2: Go owns membership. Read each group's current peers from Go,
// apply the same "at most one manual group" rule, and write the result
// back; fall through to the panel's own writer when Go is unavailable.
let membershipSaved = false;
if (panelGrouping.writesGoToGo()) {
const updates = [];
let goAvailable = true;
for (const group of manualGroups) {
const peers = await panelGrouping.getGroupPeersFromGo(group.guid, req);
if (!peers) {
goAvailable = false;
break;
}
const next = new Set(peers);
if (selected.includes(group.guid)) next.add(deviceId);
else next.delete(deviceId);
updates.push({ guid: group.guid, peers: Array.from(next) });
}
if (goAvailable) {
for (const update of updates) {
const saved = await panelGrouping.setGroupPeersInGo(update.guid, update.peers, req);
if (!saved) {
goAvailable = false;
break;
}
}
}
membershipSaved = goAvailable;
}
if (!membershipSaved) {
for (const group of manualGroups) {
if (selected.includes(group.guid)) await db.addDeviceToGroup(group.guid, deviceId);
else await db.removeDeviceFromGroup(group.guid, deviceId);
}
}
await db.logAction(req.session.userId, 'device_group_membership_updated', `Device ${deviceId} groups set to [${selected.join(', ')}]`, req.ip);
res.json({ success: true, data: { groupGuids: selected } });
} catch (err) {
if (err && err.fromGo) {
return res.status(err.status || 502).json({ success: false, error: err.message });
}
console.error('Update device memberships error:', err);
res.status(500).json({ success: false, error: req.t('errors.server_error') });
}
+219 -2
View File
@@ -705,6 +705,208 @@ async function syncOnlineStatus(/* db */) {
return { synced: 0, skipped: true, reason: 'betterdesk_manages_state' };
}
// ===================== Panel grouping and catalog (strangler P2/P3) ==========
//
// Go owns the writes for device groups, their members and ACL, folders and
// per-user device grants, and it owns the panel catalog definition
// (docs/important/console-backend-strangler.md). The console keeps its screens
// and its response shapes; these helpers are the only place it talks to those
// endpoints.
//
// Every call carries the panel trust statement (services/panelTrust.js) when the
// bridge is configured. Without it Go would authorize these requests as the
// API key's role, which is an administrator — a viewer's session could then
// write a group. With it, Go enforces the operator's own role and permissions.
const panelTrust = require('./panelTrust');
/**
* Request options for a panel-originated call: the trust statement for this
* exact method and path, plus the JSON content type the API key client sets.
* Returns undefined headers when the bridge is off, so axios keeps its own.
*/
function panelCallConfig(method, path, req) {
const identity = req ? panelTrust.identityFromRequest(req) : null;
if (!identity) return undefined;
const headers = panelTrust.panelTrustHeaders(identity, method, path);
return Object.keys(headers).length ? { headers } : undefined;
}
/** Panel section catalog, permission vocabulary and role defaults (stage P3). */
async function getPanelCatalog(config) {
try {
const { data } = await apiClient.get('/panel/catalog', config);
return wrap(data);
} catch (e) {
return { success: false, error: e.message };
}
}
/** List device groups with ACL and member counts. */
async function listPanelDeviceGroups(config) {
try {
const { data } = await apiClient.get('/panel/device-groups', config);
return wrap(data);
} catch (e) {
return { success: false, error: e.message };
}
}
/** Create or update a device group (and its ACL) in one call. */
async function savePanelDeviceGroup(payload, config) {
try {
const { data } = await apiClient.post('/panel/device-groups', payload, config);
return wrap(data);
} catch (e) {
return { success: false, error: e.message, status: e.response?.status };
}
}
/** Delete a device group. */
async function deletePanelDeviceGroup(guid, config) {
try {
const safeGuid = assertSafeApiId(guid, 'guid');
const { data } = await apiClient.delete(`/panel/device-groups/${encodeURIComponent(safeGuid)}`, config);
return wrap(data);
} catch (e) {
return { success: false, error: e.message, status: e.response?.status };
}
}
/** Read a group's membership. */
async function getPanelDeviceGroupPeers(guid, config) {
try {
const safeGuid = assertSafeApiId(guid, 'guid');
const { data } = await apiClient.get(
`/panel/device-groups/${encodeURIComponent(safeGuid)}/peers`, config,
);
return wrap(data);
} catch (e) {
return { success: false, error: e.message };
}
}
/** Replace a group's membership. */
async function setPanelDeviceGroupPeers(guid, peers, config) {
try {
const safeGuid = assertSafeApiId(guid, 'guid');
const { data } = await apiClient.put(
`/panel/device-groups/${encodeURIComponent(safeGuid)}/peers`,
{ peers: Array.isArray(peers) ? peers : [] },
config,
);
return wrap(data);
} catch (e) {
return { success: false, error: e.message, status: e.response?.status };
}
}
/** Read a group's ACL. */
async function getPanelDeviceGroupAcl(guid, config) {
try {
const safeGuid = assertSafeApiId(guid, 'guid');
const { data } = await apiClient.get(
`/panel/device-groups/${encodeURIComponent(safeGuid)}/acl`, config,
);
return wrap(data);
} catch (e) {
return { success: false, error: e.message };
}
}
/** Replace a group's ACL. */
async function setPanelDeviceGroupAcl(guid, acl, config) {
try {
const safeGuid = assertSafeApiId(guid, 'guid');
const { data } = await apiClient.put(
`/panel/device-groups/${encodeURIComponent(safeGuid)}/acl`,
{
allowed_users: Array.isArray(acl?.allowed_users) ? acl.allowed_users : [],
allowed_user_groups: Array.isArray(acl?.allowed_user_groups) ? acl.allowed_user_groups : [],
},
config,
);
return wrap(data);
} catch (e) {
return { success: false, error: e.message, status: e.response?.status };
}
}
/** List folders plus the device → folder assignments. */
async function listPanelFolders(config) {
try {
const { data } = await apiClient.get('/panel/folders', config);
return wrap(data);
} catch (e) {
return { success: false, error: e.message };
}
}
async function createPanelFolder(folder, config) {
try {
const { data } = await apiClient.post('/panel/folders', folder, config);
return wrap(data);
} catch (e) {
return { success: false, error: e.message, status: e.response?.status };
}
}
async function updatePanelFolder(id, folder, config) {
try {
const { data } = await apiClient.put(`/panel/folders/${Number(id)}`, folder, config);
return wrap(data);
} catch (e) {
return { success: false, error: e.message, status: e.response?.status };
}
}
async function deletePanelFolder(id, config) {
try {
const { data } = await apiClient.delete(`/panel/folders/${Number(id)}`, config);
return wrap(data);
} catch (e) {
return { success: false, error: e.message, status: e.response?.status };
}
}
/** Assign a device to a folder (folderId 0 clears the assignment). */
async function setPanelDeviceFolder(deviceId, folderId, config) {
try {
const safeId = assertSafeApiId(deviceId, 'device id');
const { data } = await apiClient.put(
`/panel/devices/${encodeURIComponent(safeId)}/folder`,
{ folder_id: Number(folderId) || 0 },
config,
);
return wrap(data);
} catch (e) {
return { success: false, error: e.message, status: e.response?.status };
}
}
/** Direct device grants for one user. */
async function listPanelUserGrants(userId, config) {
try {
const { data } = await apiClient.get(`/panel/users/${Number(userId)}/grants`, config);
return wrap(data);
} catch (e) {
return { success: false, error: e.message };
}
}
async function setPanelUserGrants(userId, peers, config) {
try {
const { data } = await apiClient.put(
`/panel/users/${Number(userId)}/grants`,
{ peers: Array.isArray(peers) ? peers : [] },
config,
);
return wrap(data);
} catch (e) {
return { success: false, error: e.message, status: e.response?.status };
}
}
// ========================== Helpers ==========================================
/**
@@ -1228,8 +1430,7 @@ async function getRolePermissions(role) {
/**
* List all custom permission overrides from the DB.
*/
async function listRolePermissionOverrides(role) {
try {
async function listRolePermissionOverrides(role) { try {
const url = role ? `/role-permissions?role=${encodeURIComponent(role)}` : '/role-permissions';
const { data } = await apiClient.get(url);
return wrap(data);
@@ -1705,6 +1906,22 @@ module.exports = {
listHelpRequests,
acknowledgeHelpRequest,
resolveHelpRequest,
// Panel catalog and grouping (strangler P2/P3)
getPanelCatalog,
listPanelDeviceGroups,
savePanelDeviceGroup,
deletePanelDeviceGroup,
getPanelDeviceGroupPeers,
setPanelDeviceGroupPeers,
getPanelDeviceGroupAcl,
setPanelDeviceGroupAcl,
listPanelFolders,
createPanelFolder,
updatePanelFolder,
deletePanelFolder,
setPanelDeviceFolder,
listPanelUserGrants,
setPanelUserGrants,
// Helpers
normalisePeer,
// Raw axios client (for services that need direct API access)
+245
View File
@@ -0,0 +1,245 @@
'use strict';
/**
* BetterDesk Console — panel grouping owner switch.
*
* Stage P2 of docs/important/console-backend-strangler.md moves the writes for
* device groups, their members/ACL, folders and per-user device grants into the
* Go server. The console keeps its screens, routes and response shapes; only
* the writer changes.
*
* `BACKEND_PANEL_GROUPING=go` (default) sends writes to Go. Setting it to
* `node` puts the old writer back without redeploying, which is the rollback
* described in the strangler document. Reads always come from Go first, because
* Go already owned the reader the RustDesk client uses — a split would let the
* panel and the client disagree.
*/
const config = require('../config/config');
const betterdeskApi = require('./betterdeskApi');
const panelTrust = require('./panelTrust');
const OWNER_GO = 'go';
const OWNER_NODE = 'node';
/** Which process owns the panel grouping writes for this deployment. */
function panelGroupingOwner() {
const raw = String(process.env.BACKEND_PANEL_GROUPING || config.backendPanelGrouping || OWNER_GO)
.trim()
.toLowerCase();
return raw === OWNER_NODE ? OWNER_NODE : OWNER_GO;
}
/** True when the console must send grouping writes to Go. */
function writesGoToGo() {
return panelGroupingOwner() === OWNER_GO;
}
/**
* A Go call failed in a way that means the endpoint is not deployed yet
* (404/501/503) — during a staged rollout the console should fall back rather
* than break the screen. A 400/403 is a real answer and must not be retried
* through the other writer.
*/
function isUnavailable(result) {
const status = result && result.status;
if (status === 404 || status === 501 || status === 503) return true;
const error = String(result && result.error || '');
return /ECONNREFUSED|ENOTFOUND|timeout|socket hang up/i.test(error);
}
/**
* Request config for one panel call: the trust statement that carries the
* operator's own identity, so Go enforces their role instead of the API key's.
* `path` is the API path without the /api prefix, matching what betterdeskApi
* appends to its base URL.
*/
function panelConfig(method, path, req) {
if (!req || !panelTrust.panelTrustEnabled()) return undefined;
const identity = panelTrust.identityFromRequest(req);
if (!identity) return undefined;
const headers = panelTrust.panelTrustHeaders(identity, method, `/api${path}`);
return Object.keys(headers).length ? { headers } : undefined;
}
/**
* Call one Go helper defensively. A console running against an older server
* binary — or a test double that only stubs the endpoints it needs — must fall
* back to its own writer instead of throwing.
*/
async function callGo(name, ...args) {
const fn = betterdeskApi[name];
if (typeof fn !== 'function') return null;
try {
return await fn(...args);
} catch (err) {
return { success: false, error: err.message };
}
}
// ---------------------------------------------------------------------------
// Device groups
// ---------------------------------------------------------------------------
/**
* List groups from Go. Returns null when Go cannot answer, so the caller keeps
* its own reading path (which is what the panel does today).
*/
async function listGroupsFromGo(req) {
const result = await callGo('listPanelDeviceGroups', panelConfig('GET', '/panel/device-groups', req));
if (result && result.success && result.data && Array.isArray(result.data.groups)) return result.data.groups;
return null;
}
/** Save a group through Go; returns the saved group or null when unavailable. */
async function saveGroupToGo(payload, req) {
const result = await callGo('savePanelDeviceGroup', payload, panelConfig('POST', '/panel/device-groups', req));
if (!result) return null;
if (result.success) return result.data;
if (isUnavailable(result)) return null;
const error = new Error(result.error || 'Could not save the device group');
error.status = result.status || 502;
error.fromGo = true;
throw error;
}
/** Delete a group through Go. Returns true/false, or null when unavailable. */
async function deleteGroupFromGo(guid, req) {
const result = await callGo('deletePanelDeviceGroup', guid, panelConfig('DELETE', '/panel/device-groups/' + guid, req));
if (!result) return null;
if (result.success) return true;
if (isUnavailable(result)) return null;
const error = new Error(result.error || 'Could not delete the device group');
error.status = result.status || 502;
error.fromGo = true;
throw error;
}
/** Replace group membership through Go. */
async function setGroupPeersInGo(guid, peers, req) {
const result = await callGo('setPanelDeviceGroupPeers', guid, peers, panelConfig('PUT', '/panel/device-groups/' + guid + '/peers', req));
if (!result) return null;
if (result.success) return result.data;
if (isUnavailable(result)) return null;
const error = new Error(result.error || 'Could not save group members');
error.status = result.status || 502;
error.fromGo = true;
throw error;
}
/** Read a group's membership from Go; null when unavailable. */
async function getGroupPeersFromGo(guid, req) {
const result = await callGo('getPanelDeviceGroupPeers', guid, panelConfig('GET', '/panel/device-groups/' + guid + '/peers', req));
if (!result) return null;
if (result.success && result.data && Array.isArray(result.data.peers)) return result.data.peers;
return null;
}
/** Replace a group's ACL through Go. */
async function setGroupAclInGo(guid, acl, req) {
const result = await callGo('setPanelDeviceGroupAcl', guid, acl, panelConfig('PUT', '/panel/device-groups/' + guid + '/acl', req));
if (!result) return null;
if (result.success) return result.data;
if (isUnavailable(result)) return null;
const error = new Error(result.error || 'Could not save group access');
error.status = result.status || 502;
error.fromGo = true;
throw error;
}
// ---------------------------------------------------------------------------
// Folders
// ---------------------------------------------------------------------------
/** List folders (and assignments) from Go, or null when unavailable. */
async function listFoldersFromGo(req) {
const result = await callGo('listPanelFolders', panelConfig('GET', '/panel/folders', req));
if (result && result.success && result.data) return result.data;
return null;
}
async function createFolderInGo(folder, req) {
const result = await callGo('createPanelFolder', folder, panelConfig('POST', '/panel/folders', req));
if (!result) return null;
if (result.success) return result.data;
if (isUnavailable(result)) return null;
const error = new Error(result.error || 'Could not create the folder');
error.status = result.status || 502;
error.fromGo = true;
throw error;
}
async function updateFolderInGo(id, folder, req) {
const result = await callGo('updatePanelFolder', id, folder, panelConfig('PUT', '/panel/folders/' + Number(id), req));
if (!result) return null;
if (result.success) return result.data;
if (isUnavailable(result)) return null;
const error = new Error(result.error || 'Could not update the folder');
error.status = result.status || 502;
error.fromGo = true;
throw error;
}
async function deleteFolderInGo(id, req) {
const result = await callGo('deletePanelFolder', id, panelConfig('DELETE', '/panel/folders/' + Number(id), req));
if (!result) return null;
if (result.success) return true;
if (isUnavailable(result)) return null;
const error = new Error(result.error || 'Could not delete the folder');
error.status = result.status || 502;
error.fromGo = true;
throw error;
}
async function setDeviceFolderInGo(deviceId, folderId, req) {
const result = await callGo('setPanelDeviceFolder', deviceId, folderId, panelConfig('PUT', '/panel/devices/' + deviceId + '/folder', req));
if (!result) return null;
if (result.success) return result.data;
if (isUnavailable(result)) return null;
const error = new Error(result.error || 'Could not move the device');
error.status = result.status || 502;
error.fromGo = true;
throw error;
}
// ---------------------------------------------------------------------------
// Per-user grants
// ---------------------------------------------------------------------------
async function listUserGrantsFromGo(userId, req) {
const result = await callGo('listPanelUserGrants', userId, panelConfig('GET', '/panel/users/' + userId + '/grants', req));
if (result && result.success && result.data) return result.data;
return null;
}
async function setUserGrantsInGo(userId, peers, req) {
const result = await callGo('setPanelUserGrants', userId, peers, panelConfig('PUT', '/panel/users/' + userId + '/grants', req));
if (!result) return null;
if (result.success) return result.data;
if (isUnavailable(result)) return null;
const error = new Error(result.error || 'Could not save device access');
error.status = result.status || 502;
error.fromGo = true;
throw error;
}
module.exports = {
OWNER_GO,
OWNER_NODE,
panelGroupingOwner,
writesGoToGo,
isUnavailable,
listGroupsFromGo,
saveGroupToGo,
deleteGroupFromGo,
setGroupPeersInGo,
getGroupPeersFromGo,
setGroupAclInGo,
listFoldersFromGo,
createFolderInGo,
updateFolderInGo,
deleteFolderInGo,
setDeviceFolderInGo,
listUserGrantsFromGo,
setUserGrantsInGo,
};
+104
View File
@@ -0,0 +1,104 @@
'use strict';
/**
* BetterDesk Console — panel trust bridge (signing side).
*
* Stage P1 of docs/important/console-backend-strangler.md. The Go server can
* authorize a request on behalf of a signed-in operator without owning a
* browser session; this module produces the statement it verifies.
*
* Why it matters for the new `/api/panel/*` endpoints: those calls go out with
* the panel's API key, which carries the admin role. Without this statement the
* server would authorize every panel call as an administrator and a viewer's
* session could write a device group. With it, the role in the statement (and
* the role the server reads back from the database) is the operator's own.
*
* Format — must stay byte-identical to betterdesk-server/api/panel_trust.go:
*
* statement = v1 \n METHOD \n path \n subject \n role \n org \n issued \n expires \n nonce
* header = base64url(statement) "." hex(hmac_sha256(secret, statement))
*
* The statement covers the method and path, so a header captured for one request
* cannot be replayed against another. It lives 60 seconds and is single-use.
*/
const crypto = require('crypto');
const HEADER = 'X-BetterDesk-Panel';
const VERSION = 'v1';
const TTL_SECONDS = 60;
/** The shared secret, or '' when the bridge is not configured. */
function panelTrustSecret() {
return String(process.env.PANEL_TRUST_SECRET || '').trim();
}
/** True when this console can sign statements. */
function panelTrustEnabled() {
return panelTrustSecret().length > 0;
}
/**
* Build the header value for one request.
*
* @param {object} identity { username, role, orgId }
* @param {string} method HTTP method (any case)
* @param {string} path Request path as the server will see it, e.g. /api/panel/folders
* @returns {string|null} header value, or null when the bridge is off
*/
function signPanelStatement(identity, method, path, now = Date.now()) {
const secret = panelTrustSecret();
if (!secret) return null;
const subject = String(identity?.username || '').trim();
const role = String(identity?.role || '').trim();
if (!subject || !role) return null;
if (typeof path !== 'string' || !path.startsWith('/')) return null;
const issued = Math.floor(now / 1000);
const expires = issued + TTL_SECONDS;
const statement = [
VERSION,
String(method || 'GET').toUpperCase(),
path,
subject,
role,
String(identity?.orgId || ''),
String(issued),
String(expires),
crypto.randomBytes(16).toString('hex'),
].join('\n');
const mac = crypto.createHmac('sha256', secret).update(statement, 'utf8').digest('hex');
const payload = Buffer.from(statement, 'utf8').toString('base64url');
return `${payload}.${mac}`;
}
/**
* Headers to add to a panel-originated request. Returns an empty object when the
* bridge is off, so callers can spread it unconditionally.
*/
function panelTrustHeaders(identity, method, path) {
const value = signPanelStatement(identity, method, path);
return value ? { [HEADER]: value } : {};
}
/** Identity shape a route can pass down from the session. */
function identityFromRequest(req) {
const user = req?.session?.user;
if (!user) return null;
return {
username: user.username,
role: user.role,
orgId: user.orgId || user.organizationId || '',
};
}
module.exports = {
HEADER,
TTL_SECONDS,
panelTrustSecret,
panelTrustEnabled,
signPanelStatement,
panelTrustHeaders,
identityFromRequest,
};
+114
View File
@@ -0,0 +1,114 @@
'use strict';
/**
* Panel grouping owner switch (strangler stage P2).
*
* The console may only ever have one writer for device groups, ACL, folders and
* grants. These tests pin the switch itself, the fallback rules that keep an
* older server binary working, and — most importantly — that a refusal from Go
* is never silently retried through the panel's own writer.
*/
const mockApi = {
listPanelDeviceGroups: jest.fn(),
savePanelDeviceGroup: jest.fn(),
deletePanelDeviceGroup: jest.fn(),
getPanelDeviceGroupPeers: jest.fn(),
setPanelDeviceGroupPeers: jest.fn(),
getPanelDeviceGroupAcl: jest.fn(),
setPanelDeviceGroupAcl: jest.fn(),
listPanelFolders: jest.fn(),
createPanelFolder: jest.fn(),
updatePanelFolder: jest.fn(),
deletePanelFolder: jest.fn(),
setPanelDeviceFolder: jest.fn(),
listPanelUserGrants: jest.fn(),
setPanelUserGrants: jest.fn(),
};
jest.mock('../services/betterdeskApi', () => mockApi);
const panelGrouping = require('../services/panelGrouping');
describe('panel grouping owner', () => {
const original = process.env.BACKEND_PANEL_GROUPING;
afterEach(() => {
jest.clearAllMocks();
if (original === undefined) delete process.env.BACKEND_PANEL_GROUPING;
else process.env.BACKEND_PANEL_GROUPING = original;
});
it('defaults to Go and honours the documented rollback value', () => {
delete process.env.BACKEND_PANEL_GROUPING;
expect(panelGrouping.panelGroupingOwner()).toBe('go');
expect(panelGrouping.writesGoToGo()).toBe(true);
process.env.BACKEND_PANEL_GROUPING = 'node';
expect(panelGrouping.panelGroupingOwner()).toBe('node');
expect(panelGrouping.writesGoToGo()).toBe(false);
});
it('treats an unknown value as Go rather than a third mode', () => {
process.env.BACKEND_PANEL_GROUPING = 'sqlite';
expect(panelGrouping.panelGroupingOwner()).toBe('go');
});
});
describe('availability rules', () => {
it('falls back only when the endpoint is not there', () => {
[404, 501, 503].forEach((status) => {
expect(panelGrouping.isUnavailable({ status })).toBe(true);
});
expect(panelGrouping.isUnavailable({ error: 'connect ECONNREFUSED 127.0.0.1:21114' })).toBe(true);
expect(panelGrouping.isUnavailable({ error: 'timeout of 5000ms exceeded' })).toBe(true);
});
it('treats a real answer as final', () => {
// A 400/403 is Go saying no — the console must not rewrite through its
// own path, or the refusal would be bypassed.
[400, 401, 403, 409, 422].forEach((status) => {
expect(panelGrouping.isUnavailable({ status })).toBe(false);
});
expect(panelGrouping.isUnavailable({ error: 'name is required' })).toBe(false);
});
});
describe('Go fallback behaviour', () => {
it('returns null when the helper is missing entirely', async () => {
const saved = await panelGrouping.saveGroupToGo({ name: 'x' });
expect(saved).toBeNull();
});
it('returns null when the endpoint is not deployed', async () => {
mockApi.savePanelDeviceGroup.mockResolvedValue({ success: false, error: 'not found', status: 404 });
expect(await panelGrouping.saveGroupToGo({ name: 'x' })).toBeNull();
});
it('surfaces a refusal instead of hiding it', async () => {
mockApi.savePanelDeviceGroup.mockResolvedValue({ success: false, error: 'name is required', status: 400 });
await expect(panelGrouping.saveGroupToGo({ name: '' })).rejects.toMatchObject({
message: 'name is required',
status: 400,
fromGo: true,
});
});
it('returns the saved group on success', async () => {
mockApi.savePanelDeviceGroup.mockResolvedValue({ success: true, data: { guid: 'g1', name: 'Team' } });
expect(await panelGrouping.saveGroupToGo({ name: 'Team' })).toEqual({ guid: 'g1', name: 'Team' });
});
it('reads membership as a list, or null when unavailable', async () => {
mockApi.getPanelDeviceGroupPeers.mockResolvedValueOnce({ success: true, data: { peers: ['A', 'B'] } });
expect(await panelGrouping.getGroupPeersFromGo('g1')).toEqual(['A', 'B']);
mockApi.getPanelDeviceGroupPeers.mockResolvedValueOnce({ success: false, error: 'not found', status: 404 });
expect(await panelGrouping.getGroupPeersFromGo('g1')).toBeNull();
});
it('never throws when the API module itself fails', async () => {
mockApi.setPanelDeviceGroupPeers.mockRejectedValue(new Error('socket hang up'));
expect(await panelGrouping.setGroupPeersInGo('g1', ['A'])).toBeNull();
});
});
+111
View File
@@ -0,0 +1,111 @@
'use strict';
/**
* Panel trust bridge — signing side (strangler stage P1).
*
* The Go server authorizes panel-originated calls from a signed statement. What
* matters on this side is that the statement carries the operator's real role
* (not the panel API key's administrator role), covers the exact method and
* path, expires quickly, and never appears when the bridge is not configured.
*
* The cross-language contract itself is pinned from the Go side
* (betterdesk-server/api/panel_trust_test.go) plus the parity test for the
* catalog; here we test what this process produces.
*/
const crypto = require('crypto');
const panelTrust = require('../services/panelTrust');
const SECRET = '0123456789abcdef0123456789abcdef';
/** Recompute what Go does: verify and decode the statement. */
function decodeStatement(header, secret) {
const dot = header.lastIndexOf('.');
const statement = Buffer.from(header.slice(0, dot), 'base64url').toString('utf8');
const mac = crypto.createHmac('sha256', secret).update(statement, 'utf8').digest('hex');
return { statement, signature: header.slice(dot + 1), expected: mac, parts: statement.split('\n') };
}
describe('panel trust signing', () => {
const original = process.env.PANEL_TRUST_SECRET;
afterEach(() => {
if (original === undefined) delete process.env.PANEL_TRUST_SECRET;
else process.env.PANEL_TRUST_SECRET = original;
});
it('is off when no secret is configured', () => {
delete process.env.PANEL_TRUST_SECRET;
expect(panelTrust.panelTrustEnabled()).toBe(false);
expect(panelTrust.signPanelStatement({ username: 'a', role: 'operator' }, 'GET', '/api/panel/folders')).toBeNull();
expect(panelTrust.panelTrustHeaders({ username: 'a', role: 'operator' }, 'GET', '/api/panel/folders')).toEqual({});
});
it('produces a statement Go can verify byte for byte', () => {
process.env.PANEL_TRUST_SECRET = SECRET;
const now = 1_800_000_000_000; // fixed clock so the assertion is exact
const header = panelTrust.signPanelStatement(
{ username: 'operator1', role: 'operator', orgId: 'org-7' }, 'put', '/api/panel/device-groups/g1/acl', now,
);
expect(header).toBeTruthy();
const { statement, signature, expected, parts } = decodeStatement(header, SECRET);
// Byte-identical HMAC — this is the cross-language contract.
expect(signature).toBe(expected);
expect(parts[0]).toBe('v1');
expect(parts[1]).toBe('PUT'); // method normalised, matching Go
expect(parts[2]).toBe('/api/panel/device-groups/g1/acl');
expect(parts[3]).toBe('operator1');
expect(parts[4]).toBe('operator'); // the operator's role, not the API key's
expect(parts[5]).toBe('org-7');
expect(Number(parts[6])).toBe(1_800_000_000);
expect(Number(parts[7]) - Number(parts[6])).toBe(panelTrust.TTL_SECONDS);
expect(parts[8]).toMatch(/^[0-9a-f]{32}$/); // nonce
});
it('never reuses a nonce', () => {
process.env.PANEL_TRUST_SECRET = SECRET;
const identity = { username: 'operator1', role: 'operator' };
const first = decodeStatement(panelTrust.signPanelStatement(identity, 'GET', '/api/panel/folders'), SECRET);
const second = decodeStatement(panelTrust.signPanelStatement(identity, 'GET', '/api/panel/folders'), SECRET);
expect(first.parts[8]).not.toBe(second.parts[8]);
});
it('binds the statement to the method and path', () => {
process.env.PANEL_TRUST_SECRET = SECRET;
const identity = { username: 'operator1', role: 'operator' };
const get = panelTrust.signPanelStatement(identity, 'GET', '/api/panel/folders');
const post = panelTrust.signPanelStatement(identity, 'POST', '/api/panel/folders');
expect(decodeStatement(get, SECRET).parts[1]).toBe('GET');
// A GET statement's signature does not validate a POST statement.
const forged = decodeStatement(post, SECRET).parts;
forged[1] = 'GET';
const tamperedMac = crypto.createHmac('sha256', SECRET).update(forged.join('\n'), 'utf8').digest('hex');
expect(tamperedMac).not.toBe(decodeStatement(get, SECRET).signature);
});
it('refuses to sign without a username, a role or an absolute path', () => {
process.env.PANEL_TRUST_SECRET = SECRET;
expect(panelTrust.signPanelStatement({ role: 'operator' }, 'GET', '/api/panel/folders')).toBeNull();
expect(panelTrust.signPanelStatement({ username: 'x' }, 'GET', '/api/panel/folders')).toBeNull();
expect(panelTrust.signPanelStatement({ username: 'x', role: 'operator' }, 'GET', 'panel/folders')).toBeNull();
});
it('takes the identity from the panel session', () => {
const identity = panelTrust.identityFromRequest({
session: { user: { username: 'op', role: 'operator', orgId: 'o-1' } },
});
expect(identity).toEqual({ username: 'op', role: 'operator', orgId: 'o-1' });
expect(panelTrust.identityFromRequest({ session: {} })).toBeNull();
expect(panelTrust.identityFromRequest(null)).toBeNull();
});
it('is rejected by Go when the secret differs', () => {
process.env.PANEL_TRUST_SECRET = SECRET;
const header = panelTrust.signPanelStatement({ username: 'op', role: 'operator' }, 'GET', '/api/panel/folders');
const { expected } = decodeStatement(header, SECRET);
const otherExpected = crypto.createHmac('sha256', 'a-different-secret-value-here!!')
.update(decodeStatement(header, SECRET).statement, 'utf8').digest('hex');
expect(otherExpected).not.toBe(expected);
});
});