Make nmon easier to install and run without editing YAML by hand: - Settings: point-and-click forms over config.yaml (GET/PUT /api/v1/settings/form); the YAML editor moves to /settings/yaml. - First install: with no sign-in configured nmon starts in install mode, serves only the setup wizard (sign-in, basics, devices, alerting) and closes it for good once sign-in is saved. A self-signed certificate is generated when no TLS source is given. poller.interval becomes a config setting. - Reverse proxies: opt-in --http-listen plain-HTTP listener beside HTTPS; sign-in stays required. - Webhooks: Generic, Teams Adaptive Card, Slack and Discord presets, template preview and test send. - Help: the operations, coverage and profile docs served at /help. - Polling: per-device "Poll now", a dry-run test poll returning an SNMP trace, and time-limited in-memory SNMP debug recording, in the UI and as `nmon device poll`. - Ansible: deploys into install mode when no sign-in is set, and no longer overwrites the config.yaml the wizard wrote. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_017TuKgyKve2XLFtrrXWMi2w
235 lines
9.3 KiB
Go
235 lines
9.3 KiB
Go
package app
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"io"
|
|
"net/http"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
|
|
"golang.org/x/crypto/bcrypt"
|
|
|
|
"github.com/v10networks/nmon/internal/api"
|
|
"github.com/v10networks/nmon/internal/config"
|
|
)
|
|
|
|
func TestPlanAuthDecisionTable(t *testing.T) {
|
|
signIn := config.Auth{BreakGlassFile: "bg"}
|
|
oidc := config.Auth{OIDC: &config.OIDC{Issuer: "https://idp.example"}}
|
|
insecure := &transport{insecure: true}
|
|
https := &transport{}
|
|
httpOnly := &transport{httpOnly: true, httpAddr: "[::1]:8080"}
|
|
for name, tc := range map[string]struct {
|
|
tr *transport
|
|
auth config.Auth
|
|
completed bool
|
|
want authMode
|
|
wantErr bool
|
|
}{
|
|
"fresh install over https": {tr: https, want: authMode{install: true}},
|
|
"fresh install over --http-listen": {tr: httpOnly, want: authMode{install: true}},
|
|
"break-glass configured": {tr: https, auth: signIn},
|
|
"oidc configured": {tr: https, auth: oidc},
|
|
"sign-in configured and completed": {tr: https, auth: signIn, completed: true},
|
|
"completed, then sign-in was removed": {tr: https, completed: true, wantErr: true},
|
|
"completed over --http-listen": {tr: httpOnly, completed: true, wantErr: true},
|
|
"--insecure-http stays dev-open": {tr: insecure, want: authMode{devOpen: true}},
|
|
"--insecure-http, setup completed": {tr: insecure, completed: true, want: authMode{devOpen: true}},
|
|
"--insecure-http with sign-in": {tr: insecure, auth: signIn},
|
|
} {
|
|
t.Run(name, func(t *testing.T) {
|
|
m, err := planAuth(tc.tr, tc.auth, tc.completed)
|
|
if (err != nil) != tc.wantErr || m != tc.want {
|
|
t.Fatalf("planAuth = %+v, %v; want %+v (error %v)", m, err, tc.want, tc.wantErr)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
// installFlags starts nmon on plain HTTP with no sign-in: a fresh install, in install mode.
|
|
func installFlags(f *config.Flags) { f.InsecureHTTP, f.HTTPListen = false, "[::1]:0" }
|
|
|
|
func doJSON(t *testing.T, method, url, body string) (int, string) {
|
|
t.Helper()
|
|
req, err := http.NewRequestWithContext(context.Background(), method, url, strings.NewReader(body))
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
req.Header.Set("Content-Type", "application/json")
|
|
resp, err := http.DefaultClient.Do(req)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defer func() { _ = resp.Body.Close() }()
|
|
b, _ := io.ReadAll(resp.Body)
|
|
return resp.StatusCode, string(b)
|
|
}
|
|
|
|
func TestInstallModeAllowsOnlyTheWizardRoutesAndAnswers503Elsewhere(t *testing.T) {
|
|
a, _ := startWith(t, installFlags, "")
|
|
if !a.InstallMode() {
|
|
t.Fatal("a fresh install with no sign-in must be in install mode")
|
|
}
|
|
base := "http://" + a.Addr()
|
|
for _, p := range []string{"/api/v1/me", "/api/v1/devices/x/overview", "/api/v1/tokens", "/api/v1/audit", "/api/v1/alerts", "/metrics"} {
|
|
code, body := getBody(t, http.DefaultClient, base+p)
|
|
if code != http.StatusServiceUnavailable || !strings.Contains(body, "setup not finished") {
|
|
t.Errorf("GET %s in install mode = %d %s, want 503 problem \"setup not finished\"", p, code, body)
|
|
}
|
|
}
|
|
for _, p := range []string{"/api/v1/setup", "/api/v1/meta", "/api/v1/devices", "/api/v1/settings/form", "/api/v1/notify/presets",
|
|
"/api/v1/profiles", "/api/v1/alert-policies", "/healthz"} {
|
|
if code, body := getBody(t, http.DefaultClient, base+p); code != http.StatusOK {
|
|
t.Errorf("GET %s in install mode = %d %s, want 200", p, code, body)
|
|
}
|
|
}
|
|
if code, _ := getBody(t, http.DefaultClient, base+"/"); code == http.StatusServiceUnavailable {
|
|
t.Error("the UI must be served in install mode")
|
|
}
|
|
if code, _ := doJSON(t, http.MethodPost, base+"/api/v1/devices/x/retire", "{}"); code != http.StatusServiceUnavailable {
|
|
t.Errorf("a state-changing route outside the wizard = %d, want 503", code)
|
|
}
|
|
}
|
|
|
|
func TestSignInThenCompleteEndsInstallModeForGoodAcrossRestarts(t *testing.T) {
|
|
a, f := startWith(t, installFlags, "")
|
|
base := "http://" + a.Addr()
|
|
if code, body := doJSON(t, http.MethodPost, base+"/api/v1/setup/complete", ""); code != http.StatusConflict {
|
|
t.Fatalf("complete before sign-in = %d %s, want 409", code, body)
|
|
}
|
|
if code, body := doJSON(t, http.MethodPost, base+"/api/v1/setup/signin", `{"username":"admin","password":"short"}`); code != http.StatusUnprocessableEntity {
|
|
t.Fatalf("short password = %d %s, want 422", code, body)
|
|
}
|
|
const pw = "correct horse battery"
|
|
if code, body := doJSON(t, http.MethodPost, base+"/api/v1/setup/signin", `{"username":"admin","password":"`+pw+`"}`); code != http.StatusOK {
|
|
t.Fatalf("sign-in step = %d %s", code, body)
|
|
} else if strings.Contains(body, pw) {
|
|
t.Fatal("the response echoes the password")
|
|
}
|
|
file := filepath.Join(f.DataDir, "breakglass")
|
|
if st, err := os.Stat(file); err != nil || st.Mode().Perm() != 0o600 {
|
|
t.Fatalf("break-glass file: %v %v", st, err)
|
|
}
|
|
raw, _ := os.ReadFile(file)
|
|
user, hash, _ := strings.Cut(strings.TrimSpace(string(raw)), ":")
|
|
if user != "admin" || bcrypt.CompareHashAndPassword([]byte(hash), []byte(pw)) != nil {
|
|
t.Fatalf("break-glass file %q is not user:bcrypt(password)", raw)
|
|
}
|
|
if cfg, err := config.Load(f.DataDir); err != nil || cfg.Auth.BreakGlassFile != file {
|
|
t.Fatalf("config.yaml auth.break_glass_file = %q (%v)", cfg.Auth.BreakGlassFile, err)
|
|
}
|
|
if !a.InstallMode() {
|
|
t.Fatal("install mode must last until complete")
|
|
}
|
|
code, body := doJSON(t, http.MethodPost, base+"/api/v1/setup/complete", "")
|
|
if code != http.StatusOK || !strings.Contains(body, "/auth/breakglass") {
|
|
t.Fatalf("complete = %d %s", code, body)
|
|
}
|
|
if a.InstallMode() {
|
|
t.Fatal("install mode still on after complete")
|
|
}
|
|
// Authentication is live without a restart: the same listener now demands a credential.
|
|
if code, _ := getBody(t, http.DefaultClient, base+"/api/v1/me"); code != http.StatusUnauthorized {
|
|
t.Fatalf("/api/v1/me after complete = %d, want 401", code)
|
|
}
|
|
if code, _ := doJSON(t, http.MethodPost, base+"/api/v1/setup/signin", `{"username":"x","password":"`+pw+`"}`); code != http.StatusUnauthorized {
|
|
t.Fatalf("setup POST after complete without a credential = %d, want 401", code)
|
|
}
|
|
if _, err := a.SignIn(context.Background(), "t", api.SetupSignInBody{Username: "x", Password: pw}); err == nil {
|
|
t.Fatal("sign-in step must be closed after completion")
|
|
}
|
|
var st struct{ InstallMode, Completed bool }
|
|
_, body = getBody(t, http.DefaultClient, base+"/api/v1/setup")
|
|
if err := json.Unmarshal([]byte(strings.NewReplacer("install_mode", "InstallMode", "completed", "Completed").Replace(body)), &st); err != nil ||
|
|
st.InstallMode || !st.Completed {
|
|
t.Fatalf("GET /setup after complete: %s", body)
|
|
}
|
|
stopApp(t, a)
|
|
restartAfterCompletion(t, f, file)
|
|
}
|
|
|
|
// restartAfterCompletion proves the flag is permanent: a restart is not in install mode, and removing the sign-in
|
|
// from config.yaml and deleting the break-glass file does not reopen setup (nmon refuses to start instead).
|
|
func restartAfterCompletion(t *testing.T, f config.Flags, file string) {
|
|
t.Helper()
|
|
installFlags(&f)
|
|
a2, err := Start(context.Background(), f)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if a2.InstallMode() {
|
|
t.Fatal("install mode came back after a restart")
|
|
}
|
|
if code, _ := getBody(t, http.DefaultClient, "http://"+a2.Addr()+"/api/v1/me"); code != http.StatusUnauthorized {
|
|
t.Fatalf("after restart /api/v1/me = %d, want 401", code)
|
|
}
|
|
stopApp(t, a2)
|
|
if err := os.Remove(file); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := os.WriteFile(config.File(f.DataDir), []byte("timezone: UTC\n"), 0o600); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
a3, err := Start(context.Background(), f)
|
|
if err == nil {
|
|
stopApp(t, a3)
|
|
t.Fatal("a completed install with no sign-in must refuse to start, not reopen setup")
|
|
}
|
|
if !strings.Contains(err.Error(), "no way to sign in") {
|
|
t.Fatalf("error %v", err)
|
|
}
|
|
}
|
|
|
|
func TestStartMarksAnExistingInstallWithSignInCompleted(t *testing.T) {
|
|
a, _ := startWith(t, installFlags, "auth:\n break_glass_file: "+breakGlassFile(t)+"\n")
|
|
if a.InstallMode() {
|
|
t.Fatal("a configured sign-in means no install mode")
|
|
}
|
|
if done, _, err := a.st.SetupCompleted(context.Background()); err != nil || !done {
|
|
t.Fatalf("existing install not marked completed: %v %v", done, err)
|
|
}
|
|
}
|
|
|
|
func TestDevOpenIsNeverInstallMode(t *testing.T) {
|
|
a, _ := startWith(t, nil, "")
|
|
if a.InstallMode() {
|
|
t.Fatal("--insecure-http must stay dev-open, not install mode")
|
|
}
|
|
if done, _, _ := a.st.SetupCompleted(context.Background()); done {
|
|
t.Fatal("dev-open must not mark setup completed")
|
|
}
|
|
}
|
|
|
|
func TestPollerIntervalSettingReachesTheLiveCadenceAndTheFlagWins(t *testing.T) {
|
|
a, _ := startWith(t, nil, "poller:\n interval: 2m\n")
|
|
if got := a.cadence.Get(); got != 2*time.Minute {
|
|
t.Fatalf("cadence at start = %v, want 2m", got)
|
|
}
|
|
set := func(v string) {
|
|
t.Helper()
|
|
_, err := a.UpdateConfig(context.Background(), "t", func(c *config.Config) error {
|
|
d, err := config.ParseDuration(v)
|
|
c.Poller.Interval = config.Duration(d)
|
|
return err
|
|
})
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
set("10m")
|
|
if got := a.cadence.Get(); got != 10*time.Minute {
|
|
t.Fatalf("cadence after reload = %v, want 10m", got)
|
|
}
|
|
if _, err := a.UpdateConfig(context.Background(), "t", func(c *config.Config) error { c.Poller.Interval = config.Duration(5 * time.Second); return nil }); err == nil {
|
|
t.Fatal("5s is below the 30s minimum")
|
|
}
|
|
b, _ := startWith(t, func(f *config.Flags) { f.PollInterval = 45 * time.Second }, "poller:\n interval: 2m\n")
|
|
if got := b.cadence.Get(); got != 45*time.Second {
|
|
t.Fatalf("flag must win over config: %v", got)
|
|
}
|
|
}
|