Files
Kelx/panel_hmac_rotation_test.go
2026-11-30 16:32:37 +00:00

380 lines
14 KiB
Go

package main
import (
"bytes"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strconv"
"strings"
"testing"
"time"
)
const testPanelHMACInitial = "0123456789abcdef0123456789abcdef"
const testPanelHMACNext = "fedcba9876543210fedcba987654321098765432"
const testConfigWithPanelSection = `debug: false
uuid: 4ca2b14f-a96e-4f29-843a-97a8e6cacb1d
token: AAABnXzheQ5O3im27HTAsQrc3K46tM1ElEpcf2uZ9qtSw9b-LtvO7g
api:
host: 0.0.0.0
port: 8080
panel:
url: http://100.67.67.67
node_id: 4ca2b14f-a96e-4f29-843a-97a8e6cacb1d
`
func TestUpdateConfigHMACInYAML(t *testing.T) {
t.Run("replaces existing entry", func(t *testing.T) {
src := testConfigWithPanelSection + " hmac_secret: \"0123456789abcdef0123456789abcdef\"\n"
updated := updateConfigHMACInYAML(src, testPanelHMACNext)
if strings.Count(updated, "hmac_secret:") != 1 {
t.Fatalf("expected exactly one hmac_secret entry:\n%s", updated)
}
if !strings.Contains(updated, "hmac_secret: \""+testPanelHMACNext+"\"") {
t.Fatalf("secret not replaced:\n%s", updated)
}
if !strings.Contains(updated, " url: http://100.67.67.67") {
t.Fatalf("sibling panel keys must survive:\n%s", updated)
}
if _, err := parseYAMLSubset(updated); err != nil {
t.Fatalf("updated YAML no longer parses: %v\n%s", err, updated)
}
parsed, _ := parseYAMLSubset(updated)
panel, _ := parsed["panel"].(map[string]any)
if panel == nil || panel["hmac_secret"] != testPanelHMACNext {
t.Fatalf("panel.hmac_secret not readable after replace:\n%s", updated)
}
})
t.Run("inserts under panel section when missing", func(t *testing.T) {
updated := updateConfigHMACInYAML(testConfigWithPanelSection, testPanelHMACNext)
if !strings.Contains(updated, " hmac_secret: \""+testPanelHMACNext+"\"") {
t.Fatalf("secret not inserted under panel section:\n%s", updated)
}
parsed, err := parseYAMLSubset(updated)
if err != nil {
t.Fatalf("updated YAML no longer parses: %v\n%s", err, updated)
}
panel, _ := parsed["panel"].(map[string]any)
if panel == nil || panel["hmac_secret"] != testPanelHMACNext {
t.Fatalf("panel.hmac_secret not readable after insert:\n%s", updated)
}
// Sibling keys in the panel section must survive and stay readable.
if panel["url"] != "http://100.67.67.67" || panel["node_id"] == nil {
t.Fatalf("panel sibling keys lost after insert:\n%s", updated)
}
if parsed["token"] == nil {
t.Fatalf("top-level keys must survive:\n%s", updated)
}
})
t.Run("appends panel block when absent", func(t *testing.T) {
src := "debug: false\nuuid: node-1\ntoken: t\n"
updated := updateConfigHMACInYAML(src, testPanelHMACNext)
parsed, err := parseYAMLSubset(updated)
if err != nil {
t.Fatalf("updated YAML no longer parses: %v\n%s", err, updated)
}
panel, _ := parsed["panel"].(map[string]any)
if panel == nil || panel["hmac_secret"] != testPanelHMACNext {
t.Fatalf("panel block not appended:\n%s", updated)
}
})
t.Run("replaces tab-indented entry at same mapping depth", func(t *testing.T) {
src := strings.ReplaceAll(testConfigWithPanelSection+" \thmac_secret: \"old-old-old-old-old-old-old-old\"\n", " url:", "\turl:")
updated := updateConfigHMACInYAML(src, testPanelHMACNext)
parsed, err := parseYAMLSubset(updated)
if err != nil {
t.Fatalf("updated YAML no longer parses: %v\n%s", err, updated)
}
panel, _ := parsed["panel"].(map[string]any)
if panel == nil || panel["hmac_secret"] != testPanelHMACNext {
t.Fatalf("tab-indented secret not replaced:\n%s", updated)
}
if strings.Count(updated, "hmac_secret:") != 1 {
t.Fatalf("expected exactly one hmac_secret entry:\n%s", updated)
}
})
}
// signedPanelHMACRequest builds an admin-signed rotation request exactly the
// way the panel does: the subject is the SHA-256 fingerprint of the new
// secret, and the envelope is HMAC-signed with the node's current secret.
func signedPanelHMACRequest(t *testing.T, agent *Agent, signingSecret, newSecret, nonce string, useNonce bool) *http.Request {
t.Helper()
fingerprint := sha256.Sum256([]byte(newSecret))
subject := hex.EncodeToString(fingerprint[:])
ts := strconv.FormatInt(time.Now().UnixMilli(), 10)
base := strings.Join([]string{agent.uuid, "panel-hmac-set", subject, "admin", ts}, "|")
if useNonce {
base += "|" + nonce
}
body, _ := json.Marshal(map[string]string{"secret": newSecret})
r := httptest.NewRequest("POST", "/v1/panel/hmac-secret", bytes.NewReader(body))
r.Header.Set("Content-Type", "application/json")
r.Header.Set("x-panel-role", "admin")
r.Header.Set("x-panel-ts", ts)
r.Header.Set("x-panel-sign", hmacHex(signingSecret, base))
if useNonce {
r.Header.Set("x-panel-nonce", nonce)
}
return r
}
func newPanelHMACTestAgent(t *testing.T) (*Agent, string) {
t.Helper()
dir := t.TempDir()
cfgPath := filepath.Join(dir, "config.yml")
if err := os.WriteFile(cfgPath, []byte(testConfigWithPanelSection), 0o600); err != nil {
t.Fatalf("write config: %v", err)
}
agent := &Agent{
cfgPath: cfgPath,
uuid: "4ca2b14f-a96e-4f29-843a-97a8e6cacb1d",
panelHMAC: testPanelHMACInitial,
}
return agent, cfgPath
}
func TestHandlePanelHMACSet_RotatesSecretAndGrantsGrace(t *testing.T) {
agent, cfgPath := newPanelHMACTestAgent(t)
w := httptest.NewRecorder()
agent.handlePanelHMACSet(w, signedPanelHMACRequest(t, agent, testPanelHMACInitial, testPanelHMACNext, "nonceAAArotation0001", true))
if w.Code != 200 {
t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())
}
// The new secret must be persisted before the swap.
persisted, err := os.ReadFile(cfgPath)
if err != nil {
t.Fatalf("read config: %v", err)
}
if !strings.Contains(string(persisted), "hmac_secret: \""+testPanelHMACNext+"\"") {
t.Fatalf("new secret not persisted:\n%s", string(persisted))
}
parsed, err := parseYAMLSubset(string(persisted))
if err != nil {
t.Fatalf("persisted config no longer parses: %v\n%s", err, string(persisted))
}
panel, _ := parsed["panel"].(map[string]any)
if panel == nil || panel["hmac_secret"] != testPanelHMACNext {
t.Fatalf("persisted panel.hmac_secret wrong:\n%s", string(persisted))
}
// New secret verifies immediately...
if ok, why := agent.verifyNodeAdminRequest(signedPanelHMACRequest(t, agent, testPanelHMACNext, testPanelHMACNext, "nonceAAArotation0002", true), "panel-hmac-set", mustFingerprint(t, testPanelHMACNext)); !ok {
t.Fatalf("new secret rejected after rotation: %s", why)
}
// ...and the outgoing secret still verifies inside the grace window.
if ok, why := agent.verifyNodeAdminRequest(signedPanelHMACRequest(t, agent, testPanelHMACInitial, testPanelHMACNext, "nonceAAArotation0003", true), "panel-hmac-set", mustFingerprint(t, testPanelHMACNext)); !ok {
t.Fatalf("old secret rejected during grace window: %s", why)
}
// Rotation again with the (now current) new secret succeeds.
w2 := httptest.NewRecorder()
agent.handlePanelHMACSet(w2, signedPanelHMACRequest(t, agent, testPanelHMACNext, testPanelHMACInitial, "nonceAAArotation0004", true))
if w2.Code != 200 {
t.Fatalf("second rotation failed: %d %s", w2.Code, w2.Body.String())
}
}
func mustFingerprint(t *testing.T, secret string) string {
t.Helper()
sum := sha256.Sum256([]byte(secret))
return hex.EncodeToString(sum[:])
}
func TestHandlePanelHMACSet_RejectsSubjectMismatch(t *testing.T) {
agent, cfgPath := newPanelHMACTestAgent(t)
// Valid envelope, but the signed subject is the fingerprint of a
// different secret than the one in the body: the request must be
// rejected, otherwise a captured request could be redirected to install
// an attacker-chosen secret.
fingerprintOther := sha256.Sum256([]byte("some-other-secret-0123456789abcdef"))
subject := hex.EncodeToString(fingerprintOther[:])
ts := strconv.FormatInt(time.Now().UnixMilli(), 10)
nonce := "nonceAAAmismatch0001"
base := strings.Join([]string{agent.uuid, "panel-hmac-set", subject, "admin", ts, nonce}, "|")
body, _ := json.Marshal(map[string]string{"secret": testPanelHMACNext})
r := httptest.NewRequest("POST", "/v1/panel/hmac-secret", bytes.NewReader(body))
r.Header.Set("Content-Type", "application/json")
r.Header.Set("x-panel-role", "admin")
r.Header.Set("x-panel-ts", ts)
r.Header.Set("x-panel-nonce", nonce)
r.Header.Set("x-panel-sign", hmacHex(testPanelHMACInitial, base))
w := httptest.NewRecorder()
agent.handlePanelHMACSet(w, r)
if w.Code == 200 {
t.Fatalf("subject/body mismatch accepted: %s", w.Body.String())
}
persisted, _ := os.ReadFile(cfgPath)
if strings.Contains(string(persisted), testPanelHMACNext) {
t.Fatalf("config modified by rejected request:\n%s", string(persisted))
}
}
func TestHandlePanelHMACSet_RejectsInvalidSecretFormat(t *testing.T) {
agent, _ := newPanelHMACTestAgent(t)
for _, bad := range []string{
"short",
strings.Repeat("x", 300),
"has spaces in the secret value 0123456789",
"pipe|injection-0123456789abcdef012345",
"newline-0123456789abcdef0123456789\nalert(1)",
} {
w := httptest.NewRecorder()
agent.handlePanelHMACSet(w, signedPanelHMACRequest(t, agent, testPanelHMACInitial, bad, "nonceAAAformat0001", true))
if w.Code != 400 {
t.Fatalf("invalid secret %q: expected 400, got %d: %s", bad, w.Code, w.Body.String())
}
}
// The plaintext injection attempt must never reach config.yml.
cfg, _ := os.ReadFile(filepath.Join(filepath.Dir(agent.cfgPath), "config.yml"))
if strings.Contains(string(cfg), "alert(1)") || strings.Contains(string(cfg), "injection") {
t.Fatalf("invalid secret leaked into config:\n%s", string(cfg))
}
}
func TestHandlePanelHMACSet_UnchangedSecretIsNoOp(t *testing.T) {
agent, cfgPath := newPanelHMACTestAgent(t)
before, _ := os.ReadFile(cfgPath)
w := httptest.NewRecorder()
agent.handlePanelHMACSet(w, signedPanelHMACRequest(t, agent, testPanelHMACInitial, testPanelHMACInitial, "nonceAAAunchanged001", true))
if w.Code != 403 {
t.Fatalf("expected 403 for unchanged secret, got %d: %s", w.Code, w.Body.String())
}
var resp map[string]any
_ = json.Unmarshal(w.Body.Bytes(), &resp)
if resp["error"] != "unchanged-secret" {
t.Fatalf("expected unchanged-secret error, got: %s", w.Body.String())
}
after, _ := os.ReadFile(cfgPath)
if string(before) != string(after) {
t.Fatalf("config modified on no-op rotation")
}
}
func TestHandlePanelHMACSet_EnvOverrideIsNoOp(t *testing.T) {
t.Setenv("PANEL_HMAC_SECRET", "env-pinned-secret-0123456789abcdef")
agent, cfgPath := newPanelHMACTestAgent(t)
before, _ := os.ReadFile(cfgPath)
w := httptest.NewRecorder()
agent.handlePanelHMACSet(w, signedPanelHMACRequest(t, agent, testPanelHMACInitial, testPanelHMACNext, "nonceAAAenvovr0001", true))
if w.Code != 200 {
t.Fatalf("expected 200 with envOverride, got %d: %s", w.Code, w.Body.String())
}
var resp map[string]any
_ = json.Unmarshal(w.Body.Bytes(), &resp)
if resp["envOverride"] != true {
t.Fatalf("expected envOverride flag, got: %s", w.Body.String())
}
after, _ := os.ReadFile(cfgPath)
if string(before) != string(after) {
t.Fatalf("config modified while env override is active")
}
if current, _, _ := agent.panelHMACSecrets(); current != testPanelHMACInitial {
t.Fatalf("in-memory secret swapped despite env override")
}
}
func TestPanelHMACGraceExpires(t *testing.T) {
agent, _ := newPanelHMACTestAgent(t)
agent.setPanelHMAC(testPanelHMACNext, -1*time.Minute) // already-expired grace
current, prev, prevLive := agent.panelHMACSecrets()
if current != testPanelHMACNext || prev != testPanelHMACInitial || prevLive {
t.Fatalf("unexpected secret state: current=%q prevLive=%v", current, prevLive)
}
ts := strconv.FormatInt(time.Now().UnixMilli(), 10)
base := agent.uuid + "|disk-add|/mnt/x|admin|" + ts
oldSigned := httptest.NewRequest("POST", "/v1/disks", nil)
oldSigned.Header.Set("x-panel-role", "admin")
oldSigned.Header.Set("x-panel-ts", ts)
oldSigned.Header.Set("x-panel-sign", hmacHex(testPanelHMACInitial, base))
if ok, why := agent.verifyNodeAdminRequest(oldSigned, "disk-add", "/mnt/x"); ok {
t.Fatalf("outgoing secret accepted after grace expiry")
} else if why != "bad-signature" {
t.Fatalf("expected bad-signature, got %q", why)
}
newSigned := httptest.NewRequest("POST", "/v1/disks", nil)
newSigned.Header.Set("x-panel-role", "admin")
newSigned.Header.Set("x-panel-ts", ts)
newSigned.Header.Set("x-panel-sign", hmacHex(testPanelHMACNext, base))
if ok, why := agent.verifyNodeAdminRequest(newSigned, "disk-add", "/mnt/x"); !ok {
t.Fatalf("current secret rejected: %s", why)
}
}
// TestPerNodeSecretIsolation is the F1 regression guard: the signing secret
// provisioned for one node must not authenticate admin requests against any
// other node, and a node holding only its per-node secret cannot produce
// signatures valid on a peer.
func TestPerNodeSecretIsolation(t *testing.T) {
nodeA := &Agent{uuid: "uuid-node-a", panelHMAC: "derived-secret-for-node-a-0123456789"}
nodeB := &Agent{uuid: "uuid-node-b", panelHMAC: "derived-secret-for-node-b-0123456789"}
ts := strconv.FormatInt(time.Now().UnixMilli(), 10)
// Base string for an admin action on node B, signed with node A's secret:
// exactly what a compromised node A would send to take over node B.
base := nodeB.uuid + "|node-update-install|v9.9.9|admin|" + ts
req := httptest.NewRequest("POST", "/v1/update/install", nil)
req.Header.Set("x-panel-role", "admin")
req.Header.Set("x-panel-ts", ts)
req.Header.Set("x-panel-sign", hmacHex(nodeA.panelHMAC, base))
if ok, why := nodeB.verifyNodeAdminRequest(req, "node-update-install", "v9.9.9"); ok {
t.Fatalf("node A's secret authorized an admin action on node B")
} else if why != "bad-signature" {
t.Fatalf("expected bad-signature, got %q", why)
}
// The matching per-node secret still works on its own node.
reqOwn := httptest.NewRequest("POST", "/v1/update/install", nil)
reqOwn.Header.Set("x-panel-role", "admin")
reqOwn.Header.Set("x-panel-ts", ts)
reqOwn.Header.Set("x-panel-sign", hmacHex(nodeB.panelHMAC, base))
if ok, why := nodeB.verifyNodeAdminRequest(reqOwn, "node-update-install", "v9.9.9"); !ok {
t.Fatalf("node's own secret rejected: %s", why)
}
}
func TestValidPanelHMACSecret(t *testing.T) {
cases := []struct {
in string
want bool
}{
{strings.Repeat("a", 64), true},
{strings.Repeat("A1", 16), true},
{strings.Repeat("a", 31), false},
{strings.Repeat("a", 257), false},
{"", false},
{"has space" + strings.Repeat("a", 32), false},
{"pipe|" + strings.Repeat("a", 32), false},
{"dash-" + strings.Repeat("a", 32), false},
{"underscore_" + strings.Repeat("a", 32), false},
{"ümlaut" + strings.Repeat("a", 32), false},
}
for _, c := range cases {
if got := validPanelHMACSecret(c.in); got != c.want {
t.Fatalf("validPanelHMACSecret(%q) = %v, want %v", c.in, got, c.want)
}
}
}