392 lines
13 KiB
Go
392 lines
13 KiB
Go
package main
|
|
|
|
import (
|
|
"bytes"
|
|
"crypto/hmac"
|
|
"crypto/sha256"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"fmt"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"os"
|
|
"path/filepath"
|
|
"strconv"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
)
|
|
|
|
func TestUpdateConfigTokensInYAML(t *testing.T) {
|
|
inputYAML := `debug: false
|
|
uuid: a3c102c7-7e61-460d-85fa-dae77864ffcb
|
|
token_id: tid_xyz123
|
|
token: old_plain_token_12345678901234567890
|
|
auth:
|
|
token_id: tid_xyz123
|
|
token: old_plain_token_12345678901234567890
|
|
api:
|
|
host: 0.0.0.0
|
|
port: 8080
|
|
system:
|
|
data: /var/lib/node
|
|
`
|
|
newToken := "adpnt_abcdef1234567890abcdef1234567890"
|
|
updated := updateConfigTokensInYAML(inputYAML, newToken)
|
|
|
|
parsed, err := parseYAMLSubset(updated)
|
|
if err != nil {
|
|
t.Fatalf("parseYAMLSubset failed on updated YAML: %v\nYAML content:\n%s", err, updated)
|
|
}
|
|
cfg := Config{Raw: parsed}
|
|
|
|
if got := cfg.String("token"); got != newToken {
|
|
t.Fatalf("expected top-level token %q, got %q", newToken, got)
|
|
}
|
|
if got := cfg.String("auth", "token"); got != newToken {
|
|
t.Fatalf("expected auth.token %q, got %q", newToken, got)
|
|
}
|
|
if got := cfg.String("token_id"); got != "tid_xyz123" {
|
|
t.Fatalf("expected token_id preserved as %q, got %q", "tid_xyz123", got)
|
|
}
|
|
if got := cfg.String("auth", "token_id"); got != "tid_xyz123" {
|
|
t.Fatalf("expected auth.token_id preserved as %q, got %q", "tid_xyz123", got)
|
|
}
|
|
|
|
// Test append when token missing
|
|
minimalYAML := `debug: false
|
|
uuid: test-uuid
|
|
`
|
|
updatedMin := updateConfigTokensInYAML(minimalYAML, newToken)
|
|
parsedMin, err := parseYAMLSubset(updatedMin)
|
|
if err != nil {
|
|
t.Fatalf("parseYAMLSubset failed on appended YAML: %v", err)
|
|
}
|
|
cfgMin := Config{Raw: parsedMin}
|
|
if got := cfgMin.String("token"); got != newToken {
|
|
t.Fatalf("expected appended token %q, got %q", newToken, got)
|
|
}
|
|
}
|
|
|
|
func TestHandleTokenRotate_SuccessAndGraceWindow(t *testing.T) {
|
|
tempDir := t.TempDir()
|
|
cfgPath := filepath.Join(tempDir, "config.yml")
|
|
initialYAML := `debug: false
|
|
uuid: node-uuid-test
|
|
token_id: tid-test-1
|
|
token: adpnt_oldoldold1234567890123456789012
|
|
auth:
|
|
token_id: tid-test-1
|
|
token: adpnt_oldoldold1234567890123456789012
|
|
`
|
|
if err := os.WriteFile(cfgPath, []byte(initialYAML), 0o600); err != nil {
|
|
t.Fatalf("failed to write test config: %v", err)
|
|
}
|
|
|
|
agent := &Agent{
|
|
dataRoot: tempDir,
|
|
volumesDir: filepath.Join(tempDir, "servers"),
|
|
cfgPath: cfgPath,
|
|
token: "adpnt_oldoldold1234567890123456789012",
|
|
tokenID: "tid-test-1",
|
|
uuid: "node-uuid-test",
|
|
}
|
|
|
|
newToken := "adpnt_newnewnew1234567890123456789012"
|
|
reqBody, _ := json.Marshal(map[string]string{"token": newToken})
|
|
req := httptest.NewRequest("POST", "/v1/token/rotate", bytes.NewReader(reqBody))
|
|
req.Header.Set("Content-Type", "application/json")
|
|
w := httptest.NewRecorder()
|
|
|
|
agent.handleTokenRotate(w, req)
|
|
|
|
res := w.Result()
|
|
if res.StatusCode != 200 {
|
|
t.Fatalf("expected status 200, got %d (body: %s)", res.StatusCode, w.Body.String())
|
|
}
|
|
|
|
var respBody map[string]any
|
|
if err := json.Unmarshal(w.Body.Bytes(), &respBody); err != nil {
|
|
t.Fatalf("failed to parse json response: %v", err)
|
|
}
|
|
if okVal, ok := respBody["ok"].(bool); !ok || !okVal {
|
|
t.Fatalf("expected {ok: true}, got %v", respBody)
|
|
}
|
|
if graceVal, ok := respBody["graceSeconds"].(float64); !ok || graceVal < 600 {
|
|
t.Fatalf("expected graceSeconds >= 600, got %v", respBody["graceSeconds"])
|
|
}
|
|
|
|
// Verify in-memory state
|
|
agent.tokenMu.Lock()
|
|
curToken := agent.token
|
|
oldToken := agent.oldToken
|
|
oldExp := agent.oldTokenExp
|
|
agent.tokenMu.Unlock()
|
|
|
|
if curToken != newToken {
|
|
t.Fatalf("expected agent.token = %q, got %q", newToken, curToken)
|
|
}
|
|
if oldToken != "adpnt_oldoldold1234567890123456789012" {
|
|
t.Fatalf("expected agent.oldToken = old value, got %q", oldToken)
|
|
}
|
|
if time.Until(oldExp) < 9*time.Minute {
|
|
t.Fatalf("expected grace expiry ~10 min in future, got %v", oldExp)
|
|
}
|
|
|
|
// Verify on-disk config file
|
|
diskContent, err := os.ReadFile(cfgPath)
|
|
if err != nil {
|
|
t.Fatalf("failed to read persisted config: %v", err)
|
|
}
|
|
parsedDisk, err := parseYAMLSubset(string(diskContent))
|
|
if err != nil {
|
|
t.Fatalf("persisted config is not valid YAML: %v", err)
|
|
}
|
|
diskCfg := Config{Raw: parsedDisk}
|
|
if got := diskCfg.String("token"); got != newToken {
|
|
t.Fatalf("expected disk config top-level token %q, got %q", newToken, got)
|
|
}
|
|
if got := diskCfg.String("auth", "token"); got != newToken {
|
|
t.Fatalf("expected disk config auth.token %q, got %q", newToken, got)
|
|
}
|
|
|
|
// Check file mode
|
|
info, err := os.Stat(cfgPath)
|
|
if err != nil {
|
|
t.Fatalf("stat config file: %v", err)
|
|
}
|
|
if perm := info.Mode().Perm(); perm != 0o600 {
|
|
t.Fatalf("expected mode 0600, got %o", perm)
|
|
}
|
|
|
|
// Verify authOK behavior with both new token and old token within grace window
|
|
reqNew := httptest.NewRequest("GET", "/v1/info", nil)
|
|
reqNew.Header.Set("Authorization", "Bearer "+newToken)
|
|
if !agent.authOK(reqNew) {
|
|
t.Fatalf("authOK rejected new rotated token")
|
|
}
|
|
|
|
reqOld := httptest.NewRequest("GET", "/v1/info", nil)
|
|
reqOld.Header.Set("Authorization", "Bearer adpnt_oldoldold1234567890123456789012")
|
|
if !agent.authOK(reqOld) {
|
|
t.Fatalf("authOK rejected old token within grace window")
|
|
}
|
|
|
|
reqBad := httptest.NewRequest("GET", "/v1/info", nil)
|
|
reqBad.Header.Set("Authorization", "Bearer adpnt_invalidtoken1234567890123456")
|
|
if agent.authOK(reqBad) {
|
|
t.Fatalf("authOK accepted completely invalid token")
|
|
}
|
|
|
|
// Expire the old token and verify it is now rejected
|
|
agent.tokenMu.Lock()
|
|
agent.oldTokenExp = time.Now().Add(-1 * time.Minute)
|
|
agent.tokenMu.Unlock()
|
|
|
|
if agent.authOK(reqOld) {
|
|
t.Fatalf("authOK accepted old token AFTER grace window expired")
|
|
}
|
|
}
|
|
|
|
func TestHandleTokenRotate_SymlinkConfig(t *testing.T) {
|
|
tempDir := t.TempDir()
|
|
realCfgPath := filepath.Join(tempDir, "real_config.yml")
|
|
symlinkCfgPath := filepath.Join(tempDir, "config.yml")
|
|
|
|
initialYAML := "token: adpnt_symlinkold12345678901234567890\n"
|
|
if err := os.WriteFile(realCfgPath, []byte(initialYAML), 0o600); err != nil {
|
|
t.Fatalf("failed to write real config: %v", err)
|
|
}
|
|
if err := os.Symlink(realCfgPath, symlinkCfgPath); err != nil {
|
|
t.Fatalf("failed to create symlink: %v", err)
|
|
}
|
|
|
|
agent := &Agent{
|
|
cfgPath: symlinkCfgPath,
|
|
token: "adpnt_symlinkold12345678901234567890",
|
|
}
|
|
|
|
newToken := "adpnt_symlinknew12345678901234567890"
|
|
reqBody, _ := json.Marshal(map[string]string{"token": newToken})
|
|
req := httptest.NewRequest("POST", "/v1/token/rotate", bytes.NewReader(reqBody))
|
|
w := httptest.NewRecorder()
|
|
|
|
agent.handleTokenRotate(w, req)
|
|
if w.Code != 200 {
|
|
t.Fatalf("expected status 200, got %d", w.Code)
|
|
}
|
|
|
|
// Verify real file updated
|
|
realContent, err := os.ReadFile(realCfgPath)
|
|
if err != nil {
|
|
t.Fatalf("failed to read real config: %v", err)
|
|
}
|
|
if !strings.Contains(string(realContent), newToken) {
|
|
t.Fatalf("real config does not contain new token: %s", string(realContent))
|
|
}
|
|
}
|
|
|
|
func TestVerifyNodeAdminRequest_RejectsBearerTokenHMACFallback(t *testing.T) {
|
|
// F3 regression guard: the node bearer token (current or old-token grace)
|
|
// must NEVER be accepted as the HMAC signing secret for panel-signed admin
|
|
// requests. Without the dedicated panel HMAC secret configured, signed
|
|
// admin endpoints must fail closed with "hmac-not-configured", otherwise
|
|
// anyone holding the bearer token could forge the panel's admin signature
|
|
// and the second authentication factor would vanish.
|
|
oldToken := "adpnt_oldadmintoken12345678901234567890"
|
|
newToken := "adpnt_newadmintoken12345678901234567890"
|
|
|
|
agent := &Agent{
|
|
uuid: "node-test-uuid",
|
|
token: newToken,
|
|
oldToken: oldToken,
|
|
oldTokenExp: time.Now().Add(10 * time.Minute),
|
|
panelHMAC: "",
|
|
}
|
|
|
|
action := "disk-add"
|
|
subject := "/mnt/data"
|
|
role := "admin"
|
|
ts := strconv.FormatInt(time.Now().UnixMilli(), 10)
|
|
base := fmt.Sprintf("%s|%s|%s|%s|%s", agent.uuid, action, subject, role, ts)
|
|
|
|
tokenSigned := func(secret string) *http.Request {
|
|
m := hmac.New(sha256.New, []byte(secret))
|
|
_, _ = m.Write([]byte(base))
|
|
req := httptest.NewRequest("POST", "/v1/disks", nil)
|
|
req.Header.Set("x-panel-role", "admin")
|
|
req.Header.Set("x-panel-ts", ts)
|
|
req.Header.Set("x-panel-sign", hex.EncodeToString(m.Sum(nil)))
|
|
return req
|
|
}
|
|
|
|
// Current bearer token must not verify as an HMAC secret.
|
|
ok, reason := agent.verifyNodeAdminRequest(tokenSigned(newToken), action, subject)
|
|
if ok || reason != "hmac-not-configured" {
|
|
t.Fatalf("current-token signed request accepted without PANEL_HMAC_SECRET: ok=%v reason=%q", ok, reason)
|
|
}
|
|
|
|
// Old bearer token must not verify even inside its rotation grace window.
|
|
ok, reason = agent.verifyNodeAdminRequest(tokenSigned(oldToken), action, subject)
|
|
if ok || reason != "hmac-not-configured" {
|
|
t.Fatalf("old-token signed request accepted during grace window without PANEL_HMAC_SECRET: ok=%v reason=%q", ok, reason)
|
|
}
|
|
|
|
// Expire the old token and confirm the request is still rejected.
|
|
agent.tokenMu.Lock()
|
|
agent.oldTokenExp = time.Now().Add(-1 * time.Minute)
|
|
agent.tokenMu.Unlock()
|
|
|
|
if okExp, _ := agent.verifyNodeAdminRequest(tokenSigned(oldToken), action, subject); okExp {
|
|
t.Fatalf("old-token signed request accepted after grace expiry")
|
|
}
|
|
}
|
|
|
|
func TestHandleTokenRotate_Validation(t *testing.T) {
|
|
tempDir := t.TempDir()
|
|
cfgPath := filepath.Join(tempDir, "config.yml")
|
|
_ = os.WriteFile(cfgPath, []byte("token: adpnt_initialtoken12345678901234\n"), 0o600)
|
|
|
|
agent := &Agent{
|
|
cfgPath: cfgPath,
|
|
token: "adpnt_initialtoken12345678901234",
|
|
}
|
|
|
|
// Too short (< 32 chars)
|
|
reqShort := httptest.NewRequest("POST", "/v1/token/rotate", strings.NewReader(`{"token":"adpnt_short"}`))
|
|
wShort := httptest.NewRecorder()
|
|
agent.handleTokenRotate(wShort, reqShort)
|
|
if wShort.Code != 400 {
|
|
t.Fatalf("expected 400 for short token, got %d", wShort.Code)
|
|
}
|
|
|
|
// Missing prefix
|
|
reqNoPrefix := httptest.NewRequest("POST", "/v1/token/rotate", strings.NewReader(`{"token":"secret_without_prefix_1234567890123456"}`))
|
|
wNoPrefix := httptest.NewRecorder()
|
|
agent.handleTokenRotate(wNoPrefix, reqNoPrefix)
|
|
if wNoPrefix.Code != 400 {
|
|
t.Fatalf("expected 400 for missing adpnt_ prefix, got %d", wNoPrefix.Code)
|
|
}
|
|
|
|
// Empty token
|
|
reqEmpty := httptest.NewRequest("POST", "/v1/token/rotate", strings.NewReader(`{"token":""}`))
|
|
wEmpty := httptest.NewRecorder()
|
|
agent.handleTokenRotate(wEmpty, reqEmpty)
|
|
if wEmpty.Code != 400 {
|
|
t.Fatalf("expected 400 for empty token, got %d", wEmpty.Code)
|
|
}
|
|
|
|
// Invalid JSON
|
|
reqBadJSON := httptest.NewRequest("POST", "/v1/token/rotate", strings.NewReader(`{invalid json`))
|
|
wBadJSON := httptest.NewRecorder()
|
|
agent.handleTokenRotate(wBadJSON, reqBadJSON)
|
|
if wBadJSON.Code != 400 {
|
|
t.Fatalf("expected 400 for invalid json, got %d", wBadJSON.Code)
|
|
}
|
|
}
|
|
|
|
func TestAuthOK_TokenIDValidation(t *testing.T) {
|
|
agent := &Agent{
|
|
token: "adpnt_testtoken1234567890123456789012",
|
|
tokenID: "node-tid-correct",
|
|
}
|
|
|
|
// Matching token and matching token ID
|
|
reqValid := httptest.NewRequest("GET", "/v1/info", nil)
|
|
reqValid.Header.Set("X-Node-Token", "adpnt_testtoken1234567890123456789012")
|
|
reqValid.Header.Set("X-Node-Token-Id", "node-tid-correct")
|
|
if !agent.authOK(reqValid) {
|
|
t.Fatalf("expected authOK to pass with matching token and token ID")
|
|
}
|
|
|
|
// Matching token but wrong token ID
|
|
reqWrongTID := httptest.NewRequest("GET", "/v1/info", nil)
|
|
reqWrongTID.Header.Set("X-Node-Token", "adpnt_testtoken1234567890123456789012")
|
|
reqWrongTID.Header.Set("X-Node-Token-Id", "node-tid-WRONG")
|
|
if agent.authOK(reqWrongTID) {
|
|
t.Fatalf("expected authOK to fail with mismatched token ID")
|
|
}
|
|
|
|
// Matching token without token ID header (optional header back-compat)
|
|
reqNoTID := httptest.NewRequest("GET", "/v1/info", nil)
|
|
reqNoTID.Header.Set("X-Node-Token", "adpnt_testtoken1234567890123456789012")
|
|
if !agent.authOK(reqNoTID) {
|
|
t.Fatalf("expected authOK to pass when token ID header is omitted")
|
|
}
|
|
}
|
|
|
|
func TestFSAnomalyTracker_ThresholdAndAlert(t *testing.T) {
|
|
tracker := newFSAnomalyTracker(time.Minute, 5)
|
|
|
|
clientIP := "192.168.1.100"
|
|
path := "/v1/fs/read"
|
|
method := "POST"
|
|
|
|
// First 5 requests should not trip
|
|
for i := 1; i <= 5; i++ {
|
|
tripped := tracker.record(clientIP, path, method, 1024)
|
|
if tripped {
|
|
t.Fatalf("request %d tripped anomaly alert unexpectedly", i)
|
|
}
|
|
}
|
|
|
|
// 6th request (> threshold of 5) should trip
|
|
tripped6 := tracker.record(clientIP, path, method, 1024)
|
|
if !tripped6 {
|
|
t.Fatalf("request 6 should have tripped anomaly alert")
|
|
}
|
|
|
|
// 7th request in same window should not re-trip (deduplication within window)
|
|
tripped7 := tracker.record(clientIP, path, method, 1024)
|
|
if tripped7 {
|
|
t.Fatalf("request 7 should not re-trip alert in same window")
|
|
}
|
|
|
|
// Different IP should have its own separate count
|
|
otherIP := "10.0.0.50"
|
|
trippedOther := tracker.record(otherIP, path, method, 1024)
|
|
if trippedOther {
|
|
t.Fatalf("other IP should not trip on first request")
|
|
}
|
|
}
|