Files
nettopo-go/internal/api/handler.go
T
2026-04-10 15:35:45 +10:00

462 lines
12 KiB
Go

package api
import (
"encoding/json"
"net/http"
"strconv"
"strings"
"time"
"nettopo-go/internal/scans"
"nettopo-go/internal/webui"
)
type Handler struct {
store scans.Store
run *scans.Runner
}
type LinkView struct {
SourceIP string `json:"source_ip"`
SourcePort string `json:"source_port"`
TargetIP string `json:"target_ip,omitempty"`
TargetSysName string `json:"target_sys_name,omitempty"`
TargetPort string `json:"target_port,omitempty"`
RemoteChassis string `json:"remote_chassis_id,omitempty"`
ResolvedBy string `json:"resolved_by"`
}
type TopologyNode struct {
ID string `json:"id"`
IP string `json:"ip"`
Name string `json:"name,omitempty"`
}
type TopologyEdge struct {
SourceIP string `json:"source_ip"`
SourcePort string `json:"source_port,omitempty"`
TargetIP string `json:"target_ip,omitempty"`
TargetName string `json:"target_name,omitempty"`
TargetPort string `json:"target_port,omitempty"`
}
type ScanDiffResponse struct {
FromScanID string `json:"from_scan_id"`
ToScanID string `json:"to_scan_id"`
NewHosts []string `json:"new_hosts"`
MissingHosts []string `json:"missing_hosts"`
NewLinks []string `json:"new_links"`
MissingLinks []string `json:"missing_links"`
}
func NewHandler(store scans.Store, run *scans.Runner) *Handler {
return &Handler{store: store, run: run}
}
func (h *Handler) Routes() http.Handler {
mux := http.NewServeMux()
webFS := http.FileServer(http.FS(webui.FS))
mux.Handle("GET /", webFS)
mux.Handle("GET /web/", http.StripPrefix("/web/", webFS))
mux.HandleFunc("GET /health", h.health)
mux.HandleFunc("POST /api/scans", h.createScan)
mux.HandleFunc("GET /api/scans", h.listScans)
mux.HandleFunc("GET /api/scans/diff", h.getScansDiff)
mux.HandleFunc("GET /api/scans/{id}", h.getScan)
mux.HandleFunc("GET /api/scans/{id}/hosts", h.getScanHosts)
mux.HandleFunc("GET /api/scans/{id}/ports", h.getScanPorts)
mux.HandleFunc("GET /api/scans/{id}/snmp", h.getScanSNMP)
mux.HandleFunc("GET /api/scans/{id}/lldp", h.getScanLLDP)
mux.HandleFunc("GET /api/scans/{id}/links", h.getScanLinks)
mux.HandleFunc("GET /api/scans/{id}/topology", h.getScanTopology)
return withJSON(mux)
}
func (h *Handler) health(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, http.StatusOK, map[string]any{
"status": "ok",
"time": time.Now().UTC(),
})
}
func (h *Handler) createScan(w http.ResponseWriter, r *http.Request) {
var req scans.CreateScanRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeError(w, http.StatusBadRequest, "invalid json body")
return
}
req.Name = strings.TrimSpace(req.Name)
if req.Name == "" {
req.Name = "manual-scan"
}
job, err := h.store.CreateScan(req)
if err != nil {
writeError(w, http.StatusBadRequest, err.Error())
return
}
writeJSON(w, http.StatusCreated, map[string]any{
"scan_id": job.ID,
"status": job.Status,
})
if h.run != nil {
h.run.Start(job)
}
}
func (h *Handler) listScans(w http.ResponseWriter, r *http.Request) {
limit := 50
if raw := r.URL.Query().Get("limit"); raw != "" {
n, err := strconv.Atoi(raw)
if err != nil || n <= 0 || n > 500 {
writeError(w, http.StatusBadRequest, "limit must be between 1 and 500")
return
}
limit = n
}
writeJSON(w, http.StatusOK, map[string]any{
"items": h.store.ListScans(limit),
})
}
func (h *Handler) getScansDiff(w http.ResponseWriter, r *http.Request) {
fromID := strings.TrimSpace(r.URL.Query().Get("from"))
toID := strings.TrimSpace(r.URL.Query().Get("to"))
if fromID == "" || toID == "" {
writeError(w, http.StatusBadRequest, "both from and to are required")
return
}
if _, ok := h.store.GetScan(fromID); !ok {
writeError(w, http.StatusNotFound, "from scan not found")
return
}
if _, ok := h.store.GetScan(toID); !ok {
writeError(w, http.StatusNotFound, "to scan not found")
return
}
fromHosts := hostUpSet(h.store.ListHostResults(fromID, 200000))
toHosts := hostUpSet(h.store.ListHostResults(toID, 200000))
fromLinks := linkSet(h.store.ListLLDPResults(fromID, 200000))
toLinks := linkSet(h.store.ListLLDPResults(toID, 200000))
resp := ScanDiffResponse{
FromScanID: fromID,
ToScanID: toID,
NewHosts: setDiff(toHosts, fromHosts),
MissingHosts: setDiff(fromHosts, toHosts),
NewLinks: setDiff(toLinks, fromLinks),
MissingLinks: setDiff(fromLinks, toLinks),
}
writeJSON(w, http.StatusOK, resp)
}
func (h *Handler) getScan(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id")
if id == "" {
writeError(w, http.StatusBadRequest, "scan id is required")
return
}
job, ok := h.store.GetScan(id)
if !ok {
writeError(w, http.StatusNotFound, "scan not found")
return
}
writeJSON(w, http.StatusOK, job)
}
func (h *Handler) getScanHosts(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id")
if id == "" {
writeError(w, http.StatusBadRequest, "scan id is required")
return
}
if _, ok := h.store.GetScan(id); !ok {
writeError(w, http.StatusNotFound, "scan not found")
return
}
limit := 200000
if raw := r.URL.Query().Get("limit"); raw != "" {
n, err := strconv.Atoi(raw)
if err != nil || n <= 0 || n > 500000 {
writeError(w, http.StatusBadRequest, "limit must be between 1 and 500000")
return
}
limit = n
}
writeJSON(w, http.StatusOK, map[string]any{
"items": h.store.ListHostResults(id, limit),
})
}
func (h *Handler) getScanPorts(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id")
if id == "" {
writeError(w, http.StatusBadRequest, "scan id is required")
return
}
if _, ok := h.store.GetScan(id); !ok {
writeError(w, http.StatusNotFound, "scan not found")
return
}
limit := 1000
if raw := r.URL.Query().Get("limit"); raw != "" {
n, err := strconv.Atoi(raw)
if err != nil || n <= 0 || n > 10000 {
writeError(w, http.StatusBadRequest, "limit must be between 1 and 10000")
return
}
limit = n
}
writeJSON(w, http.StatusOK, map[string]any{
"items": h.store.ListOpenPortResults(id, limit),
})
}
func (h *Handler) getScanSNMP(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id")
if id == "" {
writeError(w, http.StatusBadRequest, "scan id is required")
return
}
if _, ok := h.store.GetScan(id); !ok {
writeError(w, http.StatusNotFound, "scan not found")
return
}
limit := 200000
if raw := r.URL.Query().Get("limit"); raw != "" {
n, err := strconv.Atoi(raw)
if err != nil || n <= 0 || n > 500000 {
writeError(w, http.StatusBadRequest, "limit must be between 1 and 500000")
return
}
limit = n
}
writeJSON(w, http.StatusOK, map[string]any{
"items": h.store.ListSNMPResults(id, limit),
})
}
func (h *Handler) getScanLLDP(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id")
if id == "" {
writeError(w, http.StatusBadRequest, "scan id is required")
return
}
if _, ok := h.store.GetScan(id); !ok {
writeError(w, http.StatusNotFound, "scan not found")
return
}
limit := 2000
if raw := r.URL.Query().Get("limit"); raw != "" {
n, err := strconv.Atoi(raw)
if err != nil || n <= 0 || n > 20000 {
writeError(w, http.StatusBadRequest, "limit must be between 1 and 20000")
return
}
limit = n
}
writeJSON(w, http.StatusOK, map[string]any{
"items": h.store.ListLLDPResults(id, limit),
})
}
func (h *Handler) getScanLinks(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id")
if id == "" {
writeError(w, http.StatusBadRequest, "scan id is required")
return
}
if _, ok := h.store.GetScan(id); !ok {
writeError(w, http.StatusNotFound, "scan not found")
return
}
limit := 2000
if raw := r.URL.Query().Get("limit"); raw != "" {
n, err := strconv.Atoi(raw)
if err != nil || n <= 0 || n > 20000 {
writeError(w, http.StatusBadRequest, "limit must be between 1 and 20000")
return
}
limit = n
}
snmpItems := h.store.ListSNMPResults(id, 10000)
lldpItems := h.store.ListLLDPResults(id, limit)
sysNameToIP := make(map[string]string, len(snmpItems))
for _, s := range snmpItems {
name := strings.TrimSpace(strings.ToLower(s.SysName))
if name == "" {
continue
}
if _, exists := sysNameToIP[name]; !exists {
sysNameToIP[name] = s.IP
}
}
links := make([]LinkView, 0, len(lldpItems))
for _, l := range lldpItems {
targetNameNorm := strings.TrimSpace(strings.ToLower(l.RemoteSysName))
targetIP := ""
resolvedBy := "unresolved"
if targetNameNorm != "" {
if ip, ok := sysNameToIP[targetNameNorm]; ok {
targetIP = ip
resolvedBy = "remote_sys_name"
}
}
links = append(links, LinkView{
SourceIP: l.IP,
SourcePort: l.LocalPortNum,
TargetIP: targetIP,
TargetSysName: l.RemoteSysName,
TargetPort: l.RemotePortID,
RemoteChassis: l.RemoteChassisID,
ResolvedBy: resolvedBy,
})
}
writeJSON(w, http.StatusOK, map[string]any{
"items": links,
})
}
func (h *Handler) getScanTopology(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id")
if id == "" {
writeError(w, http.StatusBadRequest, "scan id is required")
return
}
if _, ok := h.store.GetScan(id); !ok {
writeError(w, http.StatusNotFound, "scan not found")
return
}
limit := 5000
if raw := r.URL.Query().Get("limit"); raw != "" {
n, err := strconv.Atoi(raw)
if err != nil || n <= 0 || n > 50000 {
writeError(w, http.StatusBadRequest, "limit must be between 1 and 50000")
return
}
limit = n
}
snmpItems := h.store.ListSNMPResults(id, 10000)
lldpItems := h.store.ListLLDPResults(id, limit)
sysNameToIP := make(map[string]string, len(snmpItems))
nodesByIP := make(map[string]TopologyNode, len(snmpItems))
for _, s := range snmpItems {
nameNorm := strings.TrimSpace(strings.ToLower(s.SysName))
if nameNorm != "" {
if _, exists := sysNameToIP[nameNorm]; !exists {
sysNameToIP[nameNorm] = s.IP
}
}
nodesByIP[s.IP] = TopologyNode{
ID: s.IP,
IP: s.IP,
Name: s.SysName,
}
}
edges := make([]TopologyEdge, 0, len(lldpItems))
for _, l := range lldpItems {
targetIP := ""
targetNameNorm := strings.TrimSpace(strings.ToLower(l.RemoteSysName))
if targetNameNorm != "" {
targetIP = sysNameToIP[targetNameNorm]
}
if _, exists := nodesByIP[l.IP]; !exists {
nodesByIP[l.IP] = TopologyNode{ID: l.IP, IP: l.IP}
}
if targetIP != "" {
if _, exists := nodesByIP[targetIP]; !exists {
nodesByIP[targetIP] = TopologyNode{ID: targetIP, IP: targetIP, Name: l.RemoteSysName}
}
}
edges = append(edges, TopologyEdge{
SourceIP: l.IP,
SourcePort: l.LocalPortNum,
TargetIP: targetIP,
TargetName: l.RemoteSysName,
TargetPort: l.RemotePortID,
})
}
nodes := make([]TopologyNode, 0, len(nodesByIP))
for _, n := range nodesByIP {
nodes = append(nodes, n)
}
writeJSON(w, http.StatusOK, map[string]any{
"nodes": nodes,
"edges": edges,
})
}
func withJSON(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.HasPrefix(r.URL.Path, "/api/") || r.URL.Path == "/health" {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
}
next.ServeHTTP(w, r)
})
}
func hostUpSet(items []scans.HostResult) map[string]struct{} {
out := make(map[string]struct{}, len(items))
for _, h := range items {
if h.IsUp {
out[h.IP] = struct{}{}
}
}
return out
}
func linkSet(items []scans.LLDPResult) map[string]struct{} {
out := make(map[string]struct{}, len(items))
for _, l := range items {
key := l.IP + "|" + l.LocalPortNum + "|" + l.RemoteSysName + "|" + l.RemotePortID + "|" + l.RemoteChassisID
out[key] = struct{}{}
}
return out
}
func setDiff(a, b map[string]struct{}) []string {
out := make([]string, 0)
for k := range a {
if _, ok := b[k]; !ok {
out = append(out, k)
}
}
return out
}
func writeJSON(w http.ResponseWriter, status int, payload any) {
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(payload)
}
func writeError(w http.ResponseWriter, status int, message string) {
writeJSON(w, status, map[string]string{"error": message})
}