Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Lx9FNLG2CqeBbVGGd9bFsP
61 lines
2.0 KiB
Go
61 lines
2.0 KiB
Go
package api
|
|
|
|
import (
|
|
"net/http"
|
|
"sort"
|
|
|
|
"github.com/danielgtaylor/huma/v2"
|
|
|
|
"github.com/v10networks/nmon/internal/auth"
|
|
)
|
|
|
|
// Route is one operation of the API as the Go 1.22 ServeMux and auth.Policy write it.
|
|
type Route struct {
|
|
Method string
|
|
Pattern string // "PUT /api/v1/devices/{slug}"
|
|
Path string // "/api/v1/devices/{slug}"
|
|
}
|
|
|
|
// Routes lists every operation huma registers, taken from the same registration that serves them. The
|
|
// viewer-cannot-mutate test and the auth policy both start from it, so a new route cannot be missed.
|
|
func Routes() []Route {
|
|
s := &server{Deps: Deps{}.withDefaults()}
|
|
api := s.newHuma(http.NewServeMux())
|
|
s.register(api)
|
|
var out []Route
|
|
for path, item := range api.OpenAPI().Paths {
|
|
for method, op := range map[string]*huma.Operation{
|
|
http.MethodGet: item.Get, http.MethodPut: item.Put, http.MethodPost: item.Post,
|
|
http.MethodDelete: item.Delete, http.MethodPatch: item.Patch,
|
|
} {
|
|
if op == nil {
|
|
continue
|
|
}
|
|
out = append(out, Route{Method: method, Pattern: method + " " + path, Path: path})
|
|
}
|
|
}
|
|
sort.Slice(out, func(i, j int) bool { return out[i].Pattern < out[j].Pattern })
|
|
return out
|
|
}
|
|
|
|
// adminReads are GET routes only an admin may call: they reveal who can reach nmon or how it is configured.
|
|
var adminReads = []string{"GET /api/v1/tokens", "GET /api/v1/settings", "GET /api/v1/audit"}
|
|
|
|
// viewerPosts are non-GET routes that only read, so a viewer may call them. None today; a query endpoint taking
|
|
// a body would be listed here.
|
|
var viewerPosts []string
|
|
|
|
// DeclarePolicy states the minimum role of each route that departs from the default (GET and HEAD need viewer,
|
|
// everything else admin).
|
|
func DeclarePolicy(p *auth.Policy) {
|
|
for _, pat := range adminReads {
|
|
p.Require(pat, auth.RoleAdmin)
|
|
}
|
|
for _, pat := range viewerPosts {
|
|
p.Require(pat, auth.RoleViewer)
|
|
}
|
|
}
|
|
|
|
// ReadOnlyPosts are the non-GET patterns declared viewer-level, for the viewer-cannot-mutate test to skip.
|
|
func ReadOnlyPosts() []string { return append([]string(nil), viewerPosts...) }
|