Files
platform/cmd/cmsctl/precedence_test.go
T
mats a5d00c9d7e cmsctl: persist a scoped API key for script auth
Add `auth api-key {set|clear}` and prefer a stored key over the device
token, so scripts authenticate with a permanent minted API key
(X-API-Key) instead of re-running the 12h device flow. Explicit flags
and env still win over persisted credentials. Also treat a zero-byte
config file as defaults (previously every command failed to parse), and
correct AGENTS.md, which claimed device tokens auto-refresh.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>
2026-08-29 14:52:50 +02:00

52 lines
1.6 KiB
Go

package main
import (
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
)
func TestCredentialPrecedence(t *testing.T) {
cases := []struct {
name string
args []string
wantAuth string
wantKey string
}{
{"persisted key sent", []string{"cms", "nodes", "list"}, "", "persisted-key"},
{"explicit token beats persisted key", []string{"--token", "flag-token", "cms", "nodes", "list"}, "Bearer flag-token", ""},
{"explicit api-key flag wins", []string{"--api-key", "flag-key", "cms", "nodes", "list"}, "", "flag-key"},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
var gotAuth, gotKey string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
gotAuth = r.Header.Get("Authorization")
gotKey = r.Header.Get("X-API-Key")
_, _ = w.Write([]byte(`{"data":[]}`))
}))
defer srv.Close()
cfgPath := filepath.Join(t.TempDir(), "config.json")
cfg := defaultConfig()
cfg.BaseURL = srv.URL
cfg.APIKey = "persisted-key"
if err := saveConfig(cfgPath, cfg); err != nil {
t.Fatal(err)
}
var stdout, stderr strings.Builder
full := append([]string{"--config", cfgPath, "--base-url", srv.URL}, tc.args...)
if err := runWithStdin(full, strings.NewReader(""), &stdout, &stderr); err != nil {
t.Fatalf("run: %v (stderr=%s)", err, stderr.String())
}
if gotAuth != tc.wantAuth || gotKey != tc.wantKey {
t.Fatalf("auth=%q key=%q, want auth=%q key=%q", gotAuth, gotKey, tc.wantAuth, tc.wantKey)
}
})
}
}
func TestMain(m *testing.M) { os.Exit(m.Run()) }