Files
nmon/internal/app/authwire.go
Vibe Coder f31fb3712a
Some checks failed
ci / lint (push) Successful in 4m19s
ci / openapi (push) Successful in 29s
ci / postgres (push) Successful in 4m55s
ci / test (push) Failing after 19m48s
Add settings forms, first-install wizard, webhook presets, help and poll tools
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
2026-10-25 06:31:12 +00:00

150 lines
5.3 KiB
Go

package app
import (
"context"
"errors"
"fmt"
"net/http"
"time"
"github.com/v10networks/nmon/internal/api"
"github.com/v10networks/nmon/internal/auth"
"github.com/v10networks/nmon/internal/config"
"github.com/v10networks/nmon/internal/store"
)
// ingestPrefixes are the paths push ingest authenticates itself (push tokens); the auth middleware leaves them alone.
var ingestPrefixes = []string{"/write", "/api/v1/write"}
// breakGlassAlarmTTL is how long a break-glass alarm stays open after its last raise. A login lingers an hour so
// an operator who was not watching still sees it; failures and lockouts clear when the attacker stops.
func breakGlassAlarmTTL(kind string) time.Duration {
if kind == auth.AlarmBreakGlassLogin {
return time.Hour
}
return 20 * time.Minute
}
// startAuth builds the authentication service and declares the route policy. OIDC needs its client secret, a
// named secret set through PUT /api/v1/secrets/{name}; while it is missing OIDC stays off (with a warning) and
// break-glass still works, so an admin can sign in and set it. In install mode (no sign-in configured yet) the
// service lets the setup wizard through and nothing else; see install.go.
func (a *App) startAuth(ctx context.Context, s *settings) error {
svc, err := a.newAuth(ctx, s.cfg.Auth, s.mode)
if err != nil {
return err
}
a.authp.Store(svc)
a.runAuth(svc)
a.onStop("auth", func(context.Context) error { a.stopAuthRun(); return nil })
a.logAuth(s, svc.OIDCEnabled())
return nil
}
// newAuth builds an auth service for ac in the given mode. It is used at start and again when setup completes,
// so the live swap and a fresh start build exactly the same thing.
func (a *App) newAuth(ctx context.Context, ac config.Auth, mode authMode) (*auth.Auth, error) {
opts := auth.Options{
Store: a.st, Alarms: kindAlarms{a.alerting.sys, breakGlassAlarmTTL}, Logger: a.log,
Session: auth.SessionConfig{
InsecureCookies: a.flags.InsecureHTTP, Idle: ac.Session.Idle.D(), Absolute: ac.Session.Absolute.D(),
},
BreakGlass: auth.BreakGlassConfig{File: ac.BreakGlassFile, Username: ac.BreakGlassUser},
TrustedProxies: ac.TrustedProxies, IngestPrefixes: ingestPrefixes, Policy: auth.NewPolicy(),
DevOpen: mode.devOpen, Install: mode.install,
}
oidc, err := a.oidcConfig(ctx, ac)
if err != nil {
return nil, err
}
opts.OIDC = oidc
svc, err := auth.New(ctx, opts)
if err != nil {
return nil, fmt.Errorf("auth: %w", err)
}
api.DeclarePolicy(svc.Policy())
svc.Policy().Public("GET /healthz")
return svc, nil
}
// authRun is the housekeeping goroutine of the current auth service.
type authRun struct {
cancel context.CancelFunc
done chan struct{}
}
// runAuth starts svc's housekeeping and remembers how to stop it.
func (a *App) runAuth(svc *auth.Auth) {
actx, cancel := context.WithCancel(context.Background())
r := &authRun{cancel: cancel, done: make(chan struct{})}
go func() { svc.Run(actx); close(r.done) }()
a.authMu.Lock()
a.authRunning = r
a.authMu.Unlock()
}
// stopAuthRun stops the current auth service's housekeeping and waits for it.
func (a *App) stopAuthRun() {
a.authMu.Lock()
r := a.authRunning
a.authRunning = nil
a.authMu.Unlock()
if r != nil {
r.cancel()
<-r.done
}
}
// curAuth is the live auth service; setup completion swaps it.
func (a *App) curAuth() *auth.Auth { return a.authp.Load() }
// oidcConfig reads the client secret from the secret store. nil means OIDC is not configured, or its secret
// is not stored yet.
func (a *App) oidcConfig(ctx context.Context, ac config.Auth) (*auth.OIDCConfig, error) {
o := ac.OIDC
if o == nil {
return nil, nil
}
secret, err := a.st.GetSecret(ctx, o.ClientSecretName)
switch {
case errors.Is(err, store.ErrNotFound):
a.log.Warn("OIDC is configured but its client secret is not stored, so OIDC sign-in is OFF; "+
"sign in with break-glass, PUT /api/v1/secrets/"+o.ClientSecretName+", and restart", "secret", o.ClientSecretName)
return nil, nil
case err != nil:
return nil, fmt.Errorf("read OIDC client secret %q: %w", o.ClientSecretName, err)
}
return &auth.OIDCConfig{
Issuer: o.Issuer, ClientID: o.ClientID, ClientSecret: secret, RedirectURL: o.RedirectURL,
GroupsClaim: o.GroupsClaim, AdminGroup: o.AdminGroup,
}, nil
}
func (a *App) logAuth(s *settings, oidc bool) {
switch {
case s.mode.devOpen:
warnDevOpen(a.log, s.Listen)
return
case s.mode.install:
a.startInstallWarnings()
return
}
a.log.Info("authentication on", "oidc", oidc, "break_glass", s.cfg.Auth.BreakGlassFile != "",
"trusted_proxies", len(s.cfg.Auth.TrustedProxies))
}
// mux is the whole site behind the auth middleware: health, /auth/, push ingest, the API and the SPA. Only
// /auth/*, /healthz and the ingest paths are public. An unauthenticated page load (the SPA, its files, /docs) is
// redirected to sign in; an API call gets a 401 problem. The SPA itself has no login page.
func (a *App) mux(apiH http.Handler) http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
_, _ = w.Write([]byte("ok\n"))
})
mux.Handle("/auth/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { a.curAuth().Handler().ServeHTTP(w, r) }))
a.ingester.Mount(mux)
mux.Handle("/", apiH)
return mux
}