| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029 |
- // config.go — rutas /api/config/* (paridad src/routes/config.js, SPEC §2.17):
- // CRUD de routers (tabla `routers`), clave SSH propia del servidor,
- // descubrimiento de la LAN y credenciales AdGuard GL.iNet (kv; la contraseña
- // NUNCA se devuelve). Tras cada mutación se sincroniza el adapter
- // (SetRouters) sin reiniciar.
- package httpapi
- import (
- "database/sql"
- "net/http"
- urlpkg "net/url"
- "regexp"
- "strconv"
- "strings"
- "github.com/gnacho/netpulse/server-go/internal/adapters"
- "github.com/gnacho/netpulse/server-go/internal/auth"
- "github.com/gnacho/netpulse/server-go/internal/discover"
- "github.com/gnacho/netpulse/server-go/internal/pve"
- "github.com/gnacho/netpulse/server-go/internal/routerstore"
- "github.com/gnacho/netpulse/server-go/internal/snmp"
- "github.com/gnacho/netpulse/server-go/internal/sshkey"
- )
- var (
- hostRe = regexp.MustCompile(`^[a-zA-Z0-9._-]+$`)
- hostPortRe = regexp.MustCompile(`^([a-zA-Z0-9._-]+)(:[0-9]{1,5})?$`)
- )
- // registerConfigRoutes registra las rutas /api/config/* en el mux.
- // Las mutaciones (añadir/borrar routers) y las que exponen credenciales o
- // escanean la red (sshkey, discover) exigen rol admin (auditoría v2.4.0 §2,
- // issue #7); la lista de routers es de lectura y queda tras RequireAuth.
- func (s *server) registerConfigRoutes(mux *http.ServeMux) {
- mux.Handle("GET /api/config/sshkey", auth.RequireAdmin(http.HandlerFunc(s.handleGetSSHKey)))
- mux.Handle("POST /api/config/sshkey/rotate", auth.RequireAdmin(http.HandlerFunc(s.handleRotateSSHKey)))
- mux.Handle("GET /api/config/discover", auth.RequireAdmin(http.HandlerFunc(s.handleDiscover)))
- mux.HandleFunc("GET /api/config/routers", s.handleListConfigRouters)
- mux.Handle("POST /api/config/routers", auth.RequireAdmin(http.HandlerFunc(s.handleAddConfigRouter)))
- mux.Handle("PUT /api/config/routers/{id}", auth.RequireAdmin(http.HandlerFunc(s.handleUpdateConfigRouter)))
- mux.Handle("DELETE /api/config/routers/{id}", auth.RequireAdmin(http.HandlerFunc(s.handleDeleteConfigRouter)))
- mux.Handle("GET /api/config/adguard", auth.RequireAdmin(http.HandlerFunc(s.handleGetAdguardConfig)))
- mux.Handle("PUT /api/config/adguard", auth.RequireAdmin(http.HandlerFunc(s.handlePutAdguardConfig)))
- mux.Handle("DELETE /api/config/adguard", auth.RequireAdmin(http.HandlerFunc(s.handleDeleteAdguardConfig)))
- mux.Handle("POST /api/config/adguard/detect", auth.RequireAdmin(http.HandlerFunc(s.handleDetectAdguard)))
- mux.Handle("GET /api/config/proxmox", auth.RequireAdmin(http.HandlerFunc(s.handleGetProxmoxConfig)))
- mux.Handle("PUT /api/config/proxmox", auth.RequireAdmin(http.HandlerFunc(s.handlePutProxmoxConfig)))
- mux.Handle("DELETE /api/config/proxmox/{id}", auth.RequireAdmin(http.HandlerFunc(s.handleDeleteProxmoxConfig)))
- mux.Handle("POST /api/config/proxmox/test", auth.RequireAdmin(http.HandlerFunc(s.handleTestProxmoxConfig)))
- mux.Handle("POST /api/config/proxmox/detect", auth.RequireAdmin(http.HandlerFunc(s.handleDetectProxmox)))
- }
- // syncRouters replica sync() de config.js: adapter.setRouters(listRouters(db)).
- func (s *server) syncRouters() {
- if s.adapter != nil {
- s.adapter.SetRouters(routerstore.ListRouters(s.db.DB))
- }
- }
- // GET /api/config/sshkey — clave pública propia para autorizar en routers.
- func (s *server) handleGetSSHKey(w http.ResponseWriter, r *http.Request) {
- key := sshkey.GetPublicKey(s.cfg.SSHKeyPath)
- if key == nil {
- writeError(w, http.StatusInternalServerError, "no_key")
- return
- }
- writeJSON(w, http.StatusOK, key)
- }
- // POST /api/config/sshkey/rotate — rota el par ed25519 del servidor (#242).
- // Respalda el par actual (keyPath.bak.<epoch>) y genera uno nuevo; devuelve
- // la nueva pública + fingerprint para reautorizarla en los routers. La clave
- // vieja deja de funcionar de inmediato: exige confirmación explícita del admin
- // (la UI pide escribir la palabra de confirmación).
- func (s *server) handleRotateSSHKey(w http.ResponseWriter, r *http.Request) {
- key, err := sshkey.RotateKeypair(s.cfg.SSHKeyPath)
- if err != nil {
- writeError(w, http.StatusInternalServerError, "rotate_failed", err.Error())
- return
- }
- writeJSON(w, http.StatusOK, map[string]any{
- "publicKey": key.PublicKey,
- "fingerprint": key.Fingerprint,
- "warning": "The previous key is no longer valid. Re-authorize this public key on every router before rotating again.",
- })
- }
- // GET /api/config/discover?force=1 — escaneo de la LAN (cacheado 60 s).
- func (s *server) handleDiscover(w http.ResponseWriter, r *http.Request) {
- result := discover.Routers(r.Context(), s.db.DB, s.cfg.SSHKeyPath, r.URL.Query().Get("force") == "1")
- writeJSON(w, http.StatusOK, result)
- }
- // routerListItem es la vista HTTP de un router. Omite la comunidad SNMP,
- // que solo necesita el adapter para sondear, y expone si esta configurada.
- type routerListItem struct {
- ID string `json:"id"`
- Name string `json:"name"`
- Host string `json:"host"`
- Type string `json:"type"`
- IsGateway bool `json:"is_gateway"`
- AgentOnly bool `json:"agent_only"`
- // InventoryMode (#1917): "auto" | "agent" | "ssh".
- InventoryMode string `json:"inventory_mode,omitempty"`
- CreatedAt int64 `json:"created_at"`
- FirmwareTarget string `json:"firmware_target,omitempty"`
- SnmpEnabled bool `json:"snmp_enabled"`
- SnmpCommunitySet bool `json:"snmp_community_set"`
- SnmpPort int `json:"snmp_port,omitempty"`
- SnmpPollInterval int `json:"snmp_poll_interval,omitempty"`
- // SNMPv3 (#2042). Las passphrases nunca salen: solo si están guardadas.
- SnmpVersion string `json:"snmp_version"`
- SnmpV3User string `json:"snmp_v3_user,omitempty"`
- SnmpV3SecurityLevel string `json:"snmp_v3_security_level,omitempty"`
- SnmpV3AuthProto string `json:"snmp_v3_auth_proto,omitempty"`
- SnmpV3AuthPassSet bool `json:"snmp_v3_auth_pass_set"`
- SnmpV3PrivProto string `json:"snmp_v3_priv_proto,omitempty"`
- SnmpV3PrivPassSet bool `json:"snmp_v3_priv_pass_set"`
- Disabled bool `json:"disabled"`
- ConsolePolling bool `json:"console_polling"`
- SSHPort int `json:"ssh_port,omitempty"`
- TempThreshold *int `json:"temp_threshold,omitempty"`
- }
- func newRouterListItem(rt adapters.RouterConfig) routerListItem {
- return routerListItem{
- ID: rt.ID,
- Name: rt.Name,
- Host: rt.Host,
- Type: rt.Type,
- IsGateway: rt.IsGateway,
- AgentOnly: rt.AgentOnly,
- InventoryMode: rt.InventoryMode,
- CreatedAt: rt.CreatedAt,
- FirmwareTarget: rt.FirmwareTarget,
- SnmpEnabled: rt.SnmpEnabled,
- SnmpCommunitySet: rt.SnmpCommunity != "",
- SnmpPort: rt.SnmpPort,
- SnmpPollInterval: rt.SnmpPollInterval,
- SnmpVersion: normalizeSnmpVersion(rt.SnmpVersion),
- SnmpV3User: rt.SnmpV3User,
- // Los protocolos y el nivel se devuelven porque no son secretos: la UI
- // los necesita para pintar el formulario al editar.
- SnmpV3SecurityLevel: defaultIfEmpty(rt.SnmpV3SecurityLevel, "authPriv"),
- SnmpV3AuthProto: defaultIfEmpty(rt.SnmpV3AuthProto, "SHA"),
- SnmpV3AuthPassSet: rt.SnmpV3AuthPass != "",
- SnmpV3PrivProto: defaultIfEmpty(rt.SnmpV3PrivProto, "AES"),
- SnmpV3PrivPassSet: rt.SnmpV3PrivPass != "",
- Disabled: rt.Disabled,
- ConsolePolling: rt.ConsolePolling,
- SSHPort: rt.SSHPort,
- TempThreshold: rt.TempThreshold,
- }
- }
- // normalizeSnmpVersion deja la versión en uno de los tres valores que habla
- // el poller. Cualquier otra cosa (filas viejas con NULL/"" incluidas) es v2c.
- func normalizeSnmpVersion(v string) string {
- if v == "1" || v == "3" {
- return v
- }
- return "2c"
- }
- // defaultIfEmpty evita que la UI reciba "" en los selects de SNMPv3 cuando la
- // fila es anterior a la migración.
- func defaultIfEmpty(v, fallback string) string {
- if v == "" {
- return fallback
- }
- return v
- }
- // derefStr lee un *string opcional quedándose con "" cuando no viene.
- func derefStr(p *string) string {
- if p == nil {
- return ""
- }
- return *p
- }
- // GET /api/config/routers — lista configurada (no el estado sondeado).
- func (s *server) handleListConfigRouters(w http.ResponseWriter, r *http.Request) {
- routers := routerstore.ListRouters(s.db.DB)
- items := make([]routerListItem, 0, len(routers))
- for _, rt := range routers {
- items = append(items, newRouterListItem(rt))
- }
- writeJSON(w, http.StatusOK, map[string]any{"routers": items})
- }
- type routerInput struct {
- Name *string `json:"name"`
- Host *string `json:"host"`
- Type string `json:"type"`
- // Gateway y AgentOnly son punteros por el mismo motivo que el resto:
- // ausente significa "no lo toques". Con bool a secas, un PUT parcial
- // (por ejemplo el que solo cambia inventory_mode) los reiniciaba a
- // false y tiraba el gateway o el agent-only de la unidad (#1937).
- Gateway *bool `json:"gateway"`
- AgentOnly *bool `json:"agent_only"`
- // InventoryMode (#1917): "auto" | "agent" | "ssh". Manda sobre agent_only.
- InventoryMode *string `json:"inventory_mode"`
- // Disabled (issue #1085): pausa la unidad (nil = no tocar).
- Disabled *bool `json:"disabled"`
- // FirmwareTarget: versión objetivo del firmware (issue #241; opcional).
- FirmwareTarget *string `json:"firmware_target"`
- // SNMP (issue #309): credenciales para sondeo SNMP del switch gestionado.
- SnmpEnabled *bool `json:"snmp_enabled"`
- // ConsolePolling (issue #863): sondeo HTTP de la consola del switch.
- ConsolePolling *bool `json:"console_polling"`
- SnmpCommunity *string `json:"snmp_community"`
- SnmpPort *int `json:"snmp_port"`
- SnmpPollInterval *int `json:"snmp_poll_interval"` // issue #414; segundos
- // SNMPv3 (#2042). "1" | "2c" | "3". Con v3 manda el bloque USM y la
- // comunidad se ignora. Las passphrases son secretos: nil = no tocar y ""
- // = borrar (mismo contrato que snmp_community).
- SnmpVersion *string `json:"snmp_version"`
- SnmpV3User *string `json:"snmp_v3_user"`
- SnmpV3SecurityLevel *string `json:"snmp_v3_security_level"`
- SnmpV3AuthProto *string `json:"snmp_v3_auth_proto"`
- SnmpV3AuthPass *string `json:"snmp_v3_auth_pass"`
- SnmpV3PrivProto *string `json:"snmp_v3_priv_proto"`
- SnmpV3PrivPass *string `json:"snmp_v3_priv_pass"`
- // SSHPort (issue #605): puerto SSH del router (dropbear en puerto no
- // estándar). Ausente/0 → 22.
- SSHPort *int `json:"ssh_port"`
- // TempThreshold (issue #716): umbral de alerta por temperatura alta (°C).
- // Ausente = no tocar; 0 = reset a default (65); 1..150 = fijar.
- TempThreshold *int `json:"temp_threshold"`
- }
- // validateHost replica hostSchema (trim, 1..253, regex). Devuelve el valor
- // trimmeado o "" + mensaje de error.
- func validateHost(host string) (string, string) {
- h := strings.TrimSpace(host)
- if len(h) < 1 {
- return "", "String must contain at least 1 character(s)"
- }
- if len(h) > 253 {
- return "", "String must contain at most 253 character(s)"
- }
- if !hostRe.MatchString(h) {
- return "", "host debe ser una IP o hostname válido"
- }
- return h, ""
- }
- // validateInventoryMode (#1917): "" se acepta y el store lo interpreta como
- // "auto" implicito (compatibilidad con clientes que no mandan el campo).
- func validateInventoryMode(v *string) (string, string) {
- if v == nil {
- return "", ""
- }
- m := strings.TrimSpace(*v)
- switch m {
- case "", "auto", "agent", "ssh":
- return m, ""
- }
- return "", "Invalid enum value. Expected 'auto' | 'agent' | 'ssh'"
- }
- // snmpV3Input es el bloque SNMPv3 (#2042) ya normalizado y validado. Los
- // punteros nil significan "no tocar" y se propagan tal cual al store; los
- // valores "" son borrados explícitos (passphrases) o defaults (protocolos).
- type snmpV3Input struct {
- Version *string
- User *string
- SecurityLevel *string
- AuthProto *string
- AuthPass *string
- PrivProto *string
- PrivPass *string
- }
- // validateSnmpV3 valida el bloque USM de una alta o una edición. Devuelve el
- // input normalizado y un mensaje de error ("" = ok).
- func validateSnmpV3(in routerInput) (snmpV3Input, string) {
- out := snmpV3Input{}
- if in.SnmpVersion != nil {
- v := strings.TrimSpace(*in.SnmpVersion)
- if v == "" {
- v = "2c"
- }
- if v != "1" && v != "2c" && v != "3" {
- return out, "Invalid enum value. Expected '1' | '2c' | '3'"
- }
- out.Version = &v
- }
- if in.SnmpV3User != nil {
- u := strings.TrimSpace(*in.SnmpV3User)
- if len(u) > 32 {
- return out, "snmp_v3_user must contain at most 32 characters"
- }
- out.User = &u
- }
- if in.SnmpV3SecurityLevel != nil {
- l := strings.TrimSpace(*in.SnmpV3SecurityLevel)
- if l != "" && !snmp.ValidV3SecurityLevel(l) {
- return out, "Invalid enum value. Expected 'noAuthNoPriv' | 'authNoPriv' | 'authPriv'"
- }
- out.SecurityLevel = &l
- }
- if in.SnmpV3AuthProto != nil {
- p := strings.TrimSpace(*in.SnmpV3AuthProto)
- if p != "" && !snmp.ValidV3AuthProtocol(p) {
- return out, "Invalid enum value. Expected 'MD5' | 'SHA' | 'SHA224' | 'SHA256' | 'SHA384' | 'SHA512'"
- }
- out.AuthProto = &p
- }
- if in.SnmpV3PrivProto != nil {
- p := strings.TrimSpace(*in.SnmpV3PrivProto)
- if p != "" && !snmp.ValidV3PrivProtocol(p) {
- return out, "Invalid enum value. Expected 'DES' | 'AES' | 'AES192' | 'AES256' | 'AES192C' | 'AES256C'"
- }
- out.PrivProto = &p
- }
- for _, f := range []struct {
- name string
- val *string
- dst **string
- }{
- {"snmp_v3_auth_pass", in.SnmpV3AuthPass, &out.AuthPass},
- {"snmp_v3_priv_pass", in.SnmpV3PrivPass, &out.PrivPass},
- } {
- if f.val == nil {
- continue
- }
- v := *f.val
- // La passphrase no se trimea: los espacios pueden ser parte del
- // secreto que el dispositivo espera.
- if v != "" && len(v) < snmp.MinV3Passphrase {
- return out, f.name + " must contain at least 8 characters"
- }
- if len(v) > 255 {
- return out, f.name + " must contain at most 255 characters"
- }
- *f.dst = &v
- }
- return out, ""
- }
- // validateAdGuardHost permite host o host:puerto (1..65535). Devuelve
- // host, puerto y mensaje de error.
- func validateAdGuardHost(host string) (string, int, string) {
- h := strings.TrimSpace(host)
- if len(h) < 1 {
- return "", 0, "String must contain at least 1 character(s)"
- }
- if len(h) > 253 {
- return "", 0, "String must contain at most 253 character(s)"
- }
- m := hostPortRe.FindStringSubmatch(h)
- if m == nil {
- return "", 0, "host debe ser una IP, hostname o host:puerto válido"
- }
- addr := m[1]
- port := 0
- if m[2] != "" {
- p, err := strconv.Atoi(m[2][1:])
- if err != nil || p < 1 || p > 65535 {
- return "", 0, "puerto fuera de rango (1-65535)"
- }
- port = p
- }
- return addr, port, ""
- }
- // POST /api/config/routers — añadir router manualmente desde Ajustes.
- func (s *server) handleAddConfigRouter(w http.ResponseWriter, r *http.Request) {
- var in routerInput
- if st := readJSONBody(w, r, &in); st != 0 {
- writeBodyError(w, st, "invalid_json", "")
- return
- }
- // Orden de validación del schema zod: name, host, type
- name := ""
- if in.Name != nil {
- name = strings.TrimSpace(*in.Name)
- if len(name) < 1 {
- writeError(w, http.StatusBadRequest, "invalid_input", "String must contain at least 1 character(s)")
- return
- }
- if len(name) > 60 {
- writeError(w, http.StatusBadRequest, "invalid_input", "String must contain at most 60 character(s)")
- return
- }
- }
- if in.Host == nil {
- writeError(w, http.StatusBadRequest, "invalid_input", "Required")
- return
- }
- host, msg := validateHost(*in.Host)
- if msg != "" {
- writeError(w, http.StatusBadRequest, "invalid_input", msg)
- return
- }
- typ := in.Type
- if typ == "" {
- typ = "openwrt"
- }
- if typ != "glinet" && typ != "openwrt" && typ != "managed-switch" && typ != "external" {
- writeError(w, http.StatusBadRequest, "invalid_input", "Invalid enum value. Expected 'glinet' | 'openwrt' | 'managed-switch' | 'external'")
- return
- }
- var firmwareTarget string
- if in.FirmwareTarget != nil {
- firmwareTarget = strings.TrimSpace(*in.FirmwareTarget)
- }
- snmpEnabled := false
- if in.SnmpEnabled != nil {
- snmpEnabled = *in.SnmpEnabled
- }
- snmpCommunity := ""
- if in.SnmpCommunity != nil {
- snmpCommunity = strings.TrimSpace(*in.SnmpCommunity)
- }
- snmpPort := 0
- if in.SnmpPort != nil {
- snmpPort = *in.SnmpPort
- if snmpPort < 0 || snmpPort > 65535 {
- writeError(w, http.StatusBadRequest, "invalid_input", "snmp_port must be between 0 and 65535")
- return
- }
- }
- snmpInterval := 60
- if in.SnmpPollInterval != nil {
- snmpInterval = *in.SnmpPollInterval
- if snmpInterval < 10 || snmpInterval > 3600 {
- writeError(w, http.StatusBadRequest, "invalid_input", "snmp_poll_interval must be between 10 and 3600")
- return
- }
- }
- for _, rt := range routerstore.ListRouters(s.db.DB) {
- if rt.Host == host {
- writeError(w, http.StatusConflict, "duplicate_host", "Ya hay un router con "+host)
- return
- }
- }
- v3, v3Msg := validateSnmpV3(in)
- if v3Msg != "" {
- writeError(w, http.StatusBadRequest, "invalid_input", v3Msg)
- return
- }
- snmpVersion := derefStr(v3.Version)
- snmpV3User := derefStr(v3.User)
- snmpSecLevel := defaultIfEmpty(derefStr(v3.SecurityLevel), "authPriv")
- snmpAuthProto := defaultIfEmpty(derefStr(v3.AuthProto), "SHA")
- snmpAuthPass := derefStr(v3.AuthPass)
- snmpPrivProto := defaultIfEmpty(derefStr(v3.PrivProto), "AES")
- snmpPrivPass := derefStr(v3.PrivPass)
- if snmpVersion == "3" {
- if snmpV3User == "" {
- writeError(w, http.StatusBadRequest, "invalid_input", "snmp_v3_user is required for SNMPv3")
- return
- }
- if (snmpSecLevel == "authNoPriv" || snmpSecLevel == "authPriv") && snmpAuthPass == "" {
- writeError(w, http.StatusBadRequest, "invalid_input", "snmp_v3_auth_pass is required for "+snmpSecLevel)
- return
- }
- if snmpSecLevel == "authPriv" && snmpPrivPass == "" {
- writeError(w, http.StatusBadRequest, "invalid_input", "snmp_v3_priv_pass is required for authPriv")
- return
- }
- }
- sshPort := 0
- if in.SSHPort != nil {
- p := *in.SSHPort
- if p < 1 || p > 65535 {
- writeError(w, http.StatusBadRequest, "invalid_input", "ssh_port must be between 1 and 65535")
- return
- }
- sshPort = p
- }
- invMode, invMsg := validateInventoryMode(in.InventoryMode)
- if invMsg != "" {
- writeError(w, http.StatusBadRequest, "invalid_input", invMsg)
- return
- }
- created, err := routerstore.AddRouter(s.db.DB, routerstore.AddInput{
- Name: name, Host: host, Type: typ,
- IsGateway: in.Gateway != nil && *in.Gateway, AgentOnly: in.AgentOnly != nil && *in.AgentOnly,
- InventoryMode: invMode,
- FirmwareTarget: firmwareTarget,
- SnmpEnabled: snmpEnabled, SnmpCommunity: snmpCommunity, SnmpPort: snmpPort, SnmpPollInterval: snmpInterval,
- SnmpVersion: snmpVersion, SnmpV3User: snmpV3User, SnmpV3SecurityLevel: snmpSecLevel,
- SnmpV3AuthProto: snmpAuthProto, SnmpV3AuthPass: snmpAuthPass,
- SnmpV3PrivProto: snmpPrivProto, SnmpV3PrivPass: snmpPrivPass,
- SSHPort: sshPort,
- })
- if err != nil {
- writeError(w, http.StatusInternalServerError, "internal_error")
- return
- }
- s.syncRouters()
- writeJSON(w, http.StatusCreated, map[string]any{"router": newRouterListItem(created)})
- }
- // DELETE /api/config/routers/:id — 204 o 404.
- func (s *server) handleDeleteConfigRouter(w http.ResponseWriter, r *http.Request) {
- id := r.PathValue("id")
- // #1276: MAC aprendida del último push del agente (bridge MAC), para
- // purgar su entrada del registro de clientes tras borrar el router.
- var macs []string
- if s.agents != nil {
- if p, ok := s.agents.StalePayload(id); ok {
- if sys := p.Data.System; sys != nil && sys.BridgeMAC != "" {
- macs = append(macs, sys.BridgeMAC)
- }
- }
- }
- if !routerstore.RemoveRouter(s.db.DB, id) {
- writeError(w, http.StatusNotFound, "not_found")
- return
- }
- // #1276: limpieza del stub de Dispositivos/Agentes. Sin esto, el estado
- // persistido (agent.state.*) y el registro seguían listando la unidad
- // borrada sin forma de quitarla. Se revoca TAMBIÉN el token: si el
- // agente sigue instalado en la caja, su siguiente push recibe 401 y
- // deja de re-crear la entrada. Re-añadir el router requiere re-emparejar
- // el agente (reinstall).
- _, _ = s.db.Exec("DELETE FROM kv WHERE key = ?", agentTokenKeyPrefix+id)
- _, _ = s.db.Exec("DELETE FROM kv WHERE key = ?", agentStateKeyPrefix+id)
- _, _ = s.db.Exec("DELETE FROM kv WHERE key = ?", agentTransportPrefix+id)
- if s.agents != nil {
- s.agents.Forget(id)
- }
- for _, m := range macs {
- _, _ = s.db.Exec("DELETE FROM device_seen WHERE mac = ? OR mac = ?",
- strings.ToUpper(m), strings.ToLower(strings.ReplaceAll(m, ":", "-")))
- }
- s.syncRouters()
- w.WriteHeader(http.StatusNoContent)
- }
- // PUT /api/config/routers/:id — edita host/name/type/gateway/agent_only.
- // Campos omitidos (nil) no se tocan. 404 si el router no existe.
- func (s *server) handleUpdateConfigRouter(w http.ResponseWriter, r *http.Request) {
- id := r.PathValue("id")
- var in routerInput
- if st := readJSONBody(w, r, &in); st != 0 {
- writeBodyError(w, st, "invalid_json", "")
- return
- }
- var name *string
- if in.Name != nil {
- n := strings.TrimSpace(*in.Name)
- if len(n) < 1 {
- writeError(w, http.StatusBadRequest, "invalid_input", "String must contain at least 1 character(s)")
- return
- }
- if len(n) > 60 {
- writeError(w, http.StatusBadRequest, "invalid_input", "String must contain at most 60 character(s)")
- return
- }
- name = &n
- }
- var host *string
- if in.Host != nil {
- h, msg := validateHost(*in.Host)
- if msg != "" {
- writeError(w, http.StatusBadRequest, "invalid_input", msg)
- return
- }
- // Duplicado: otro router con ese host (excluyendo el propio id).
- for _, rt := range routerstore.ListRouters(s.db.DB) {
- if rt.Host == h && rt.ID != id {
- writeError(w, http.StatusConflict, "duplicate_host", "Ya hay un router con "+h)
- return
- }
- }
- host = &h
- }
- var typ *string
- if in.Type != "" {
- t := in.Type
- if t != "glinet" && t != "openwrt" && t != "managed-switch" && t != "external" {
- writeError(w, http.StatusBadRequest, "invalid_input", "Invalid enum value. Expected 'glinet' | 'openwrt' | 'managed-switch' | 'external'")
- return
- }
- typ = &t
- }
- var invMode *string
- if in.InventoryMode != nil {
- m, msg := validateInventoryMode(in.InventoryMode)
- if msg != "" {
- writeError(w, http.StatusBadRequest, "invalid_input", msg)
- return
- }
- invMode = &m
- }
- var firmwareTarget *string
- if in.FirmwareTarget != nil {
- v := strings.TrimSpace(*in.FirmwareTarget)
- firmwareTarget = &v
- }
- var snmpPollInterval *int
- if in.SnmpPollInterval != nil {
- v := *in.SnmpPollInterval
- if v < 10 || v > 3600 {
- writeError(w, http.StatusBadRequest, "invalid_input", "snmp_poll_interval must be between 10 and 3600")
- return
- }
- snmpPollInterval = &v
- }
- var snmpPort *int
- if in.SnmpPort != nil {
- p := *in.SnmpPort
- if p < 0 || p > 65535 {
- writeError(w, http.StatusBadRequest, "invalid_input", "snmp_port must be between 0 and 65535")
- return
- }
- snmpPort = &p
- }
- var snmpCommunity *string
- if in.SnmpCommunity != nil {
- v := strings.TrimSpace(*in.SnmpCommunity)
- snmpCommunity = &v
- }
- // SNMPv3 (#2042). Los punteros nil siguen significando "no tocar".
- v3, v3Msg := validateSnmpV3(in)
- if v3Msg != "" {
- writeError(w, http.StatusBadRequest, "invalid_input", v3Msg)
- return
- }
- if v3.Version != nil && *v3.Version == "3" && v3.User != nil && *v3.User == "" {
- writeError(w, http.StatusBadRequest, "invalid_input", "snmp_v3_user is required for SNMPv3")
- return
- }
- var sshPort *int
- if in.SSHPort != nil {
- p := *in.SSHPort
- if p < 1 || p > 65535 {
- writeError(w, http.StatusBadRequest, "invalid_input", "ssh_port must be between 1 and 65535")
- return
- }
- sshPort = &p
- }
- var tempThreshold *int
- if in.TempThreshold != nil {
- v := *in.TempThreshold
- if v > 150 {
- writeError(w, http.StatusBadRequest, "invalid_input", "temp_threshold must be between 0 and 150")
- return
- }
- tempThreshold = &v
- }
- updated, ok := routerstore.UpdateRouter(s.db.DB, id, routerstore.UpdateInput{
- Name: name, Host: host, Type: typ,
- IsGateway: in.Gateway, AgentOnly: in.AgentOnly,
- InventoryMode: invMode,
- Disabled: in.Disabled,
- FirmwareTarget: firmwareTarget,
- SnmpEnabled: in.SnmpEnabled, SnmpCommunity: snmpCommunity, SnmpPort: snmpPort, SnmpPollInterval: snmpPollInterval,
- SnmpVersion: v3.Version, SnmpV3User: v3.User, SnmpV3SecurityLevel: v3.SecurityLevel,
- SnmpV3AuthProto: v3.AuthProto, SnmpV3AuthPass: v3.AuthPass,
- SnmpV3PrivProto: v3.PrivProto, SnmpV3PrivPass: v3.PrivPass,
- SSHPort: sshPort,
- TempThreshold: tempThreshold,
- ConsolePolling: in.ConsolePolling,
- })
- if !ok {
- writeError(w, http.StatusNotFound, "not_found")
- return
- }
- s.syncRouters()
- writeJSON(w, http.StatusOK, map[string]any{"router": newRouterListItem(updated)})
- }
- // --- AdGuard Home (GL.iNet) — solo admin; la contraseña NO se devuelve ---
- func kvGet(db *sql.DB, key string) string {
- var v string
- if err := db.QueryRow("SELECT value FROM kv WHERE key = ?", key).Scan(&v); err != nil {
- return ""
- }
- return v
- }
- // GET /api/config/adguard — {mode, host, port, user ('root' por defecto), passSet}.
- func (s *server) handleGetAdguardConfig(w http.ResponseWriter, r *http.Request) {
- user := kvGet(s.db.DB, "adguard_user")
- if user == "" {
- user = "root"
- }
- mode := kvGet(s.db.DB, "adguard_mode")
- if mode == "" {
- mode = "glinet"
- }
- portStr := kvGet(s.db.DB, "adguard_port")
- port := 0
- if p, err := strconv.Atoi(portStr); err == nil {
- port = p
- }
- writeJSON(w, http.StatusOK, map[string]any{
- "mode": mode,
- "host": kvGet(s.db.DB, "adguard_host"),
- "port": port,
- "user": user,
- "passSet": kvGet(s.db.DB, "adguard_pass") != "",
- })
- }
- type adguardInput struct {
- Mode string `json:"mode"`
- Host *string `json:"host"`
- Port int `json:"port"`
- User string `json:"user"`
- Password string `json:"password"`
- }
- // PUT /api/config/adguard — upsert en kv (password solo si viene). 204.
- func (s *server) handlePutAdguardConfig(w http.ResponseWriter, r *http.Request) {
- var in adguardInput
- if st := readJSONBody(w, r, &in); st != 0 {
- writeBodyError(w, st, "invalid_json", "")
- return
- }
- mode := strings.ToLower(strings.TrimSpace(in.Mode))
- if mode == "" {
- mode = "glinet"
- }
- if mode != "glinet" && mode != "standard" {
- writeError(w, http.StatusBadRequest, "invalid_input", "Invalid enum value. Expected 'glinet' | 'standard'")
- return
- }
- if in.Host == nil {
- writeError(w, http.StatusBadRequest, "invalid_input", "Required")
- return
- }
- host := strings.TrimSpace(*in.Host)
- port := 0
- if mode == "standard" {
- hostFromVal, portFromHost, msg := validateAdGuardHost(host)
- if msg != "" {
- writeError(w, http.StatusBadRequest, "invalid_input", msg)
- return
- }
- host = hostFromVal
- if in.Port < 1 || in.Port > 65535 {
- writeError(w, http.StatusBadRequest, "invalid_input", "port must be between 1 and 65535")
- return
- }
- port = in.Port
- if port == 0 {
- port = portFromHost
- }
- if port == 0 {
- port = 3000
- }
- }
- user := strings.TrimSpace(in.User)
- if user == "" {
- user = "root"
- }
- if len(user) > 64 {
- writeError(w, http.StatusBadRequest, "invalid_input", "String must contain at most 64 character(s)")
- return
- }
- if len(in.Password) > 128 {
- writeError(w, http.StatusBadRequest, "invalid_input", "String must contain at most 128 character(s)")
- return
- }
- upsert := "INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value"
- if _, err := s.db.Exec(upsert, "adguard_mode", mode); err != nil {
- writeError(w, http.StatusInternalServerError, "internal_error")
- return
- }
- if _, err := s.db.Exec(upsert, "adguard_host", host); err != nil {
- writeError(w, http.StatusInternalServerError, "internal_error")
- return
- }
- if mode == "standard" {
- if _, err := s.db.Exec(upsert, "adguard_port", strconv.Itoa(port)); err != nil {
- writeError(w, http.StatusInternalServerError, "internal_error")
- return
- }
- } else {
- if _, err := s.db.Exec("DELETE FROM kv WHERE key = ?", "adguard_port"); err != nil {
- writeError(w, http.StatusInternalServerError, "internal_error")
- return
- }
- }
- if _, err := s.db.Exec(upsert, "adguard_user", user); err != nil {
- writeError(w, http.StatusInternalServerError, "internal_error")
- return
- }
- if in.Password != "" {
- if _, err := s.db.Exec(upsert, "adguard_pass", in.Password); err != nil {
- writeError(w, http.StatusInternalServerError, "internal_error")
- return
- }
- }
- w.WriteHeader(http.StatusNoContent)
- }
- // DELETE /api/config/adguard - desactiva AdGuard Home (#813): borra la config
- // (mode/host/user/pass/port) para que deje de sondearse y de penalizar la
- // salud (el poller devuelve nil y computeHealth ya no resta "AdGuard inactivo").
- // Idempotente: 204 aunque no hubiera nada configurado.
- func (s *server) handleDeleteAdguardConfig(w http.ResponseWriter, r *http.Request) {
- for _, k := range []string{"adguard_mode", "adguard_host", "adguard_user", "adguard_pass", "adguard_port"} {
- if _, err := s.db.Exec("DELETE FROM kv WHERE key = ?", k); err != nil {
- writeError(w, http.StatusInternalServerError, "internal_error")
- return
- }
- }
- if s.pollNow != nil {
- s.pollNow()
- }
- w.WriteHeader(http.StatusNoContent)
- }
- // GET /api/config/proxmox - instancias configuradas (#764 multi-endpoint).
- // El secret nunca sale: tokenSet por instancia. Los campos planos legacy
- // (url/tokenId/tokenSet de la PRIMERA instancia) se mantienen una version
- // para no romper frontends cacheados.
- func (s *server) handleGetProxmoxConfig(w http.ResponseWriter, r *http.Request) {
- instances := pve.LoadInstances(s.db.DB)
- // Vista sanitizada: el secret JAMAS sale del server (#764).
- view := make([]map[string]any, 0, len(instances))
- for _, in := range instances {
- view = append(view, map[string]any{
- "id": in.ID, "name": in.Name, "url": in.URL, "tokenId": in.TokenID,
- "caPem": in.CAPEM, "fingerprintSha256": in.FingerprintSHA256, "insecure": in.Insecure,
- })
- }
- out := map[string]any{
- "instances": view,
- "url": "",
- "tokenId": "",
- "tokenSet": false,
- }
- if len(instances) > 0 {
- out["url"] = instances[0].URL
- out["tokenId"] = instances[0].TokenID
- out["tokenSet"] = instances[0].Secret != ""
- }
- writeJSON(w, http.StatusOK, out)
- }
- type proxmoxInput struct {
- URL *string `json:"url"` // nil = no tocar; "" = desactivar
- TokenID string `json:"tokenId"`
- Secret string `json:"secret"` // solo si viene (se conserva el anterior)
- }
- type proxmoxInstanceInput struct {
- ID string `json:"id"`
- Name string `json:"name"`
- URL string `json:"url"`
- TokenID string `json:"tokenId"`
- Secret string `json:"secret"` // vacío en edición = conservar el actual
- CAPEM *string `json:"caPem"`
- FingerprintSHA256 *string `json:"fingerprintSha256"`
- Insecure *bool `json:"insecure"`
- }
- // PUT /api/config/proxmox - upsert de UNA instancia multi (#764): body
- // {id, name, url, tokenId, secret?}. Compat: si el body NO lleva id, se
- // aplica al estilo legacy single (url/tokenId/secret sobre la instancia
- // migrada "default", creándola si hace falta; url "" desactiva todo).
- func (s *server) handlePutProxmoxConfig(w http.ResponseWriter, r *http.Request) {
- var in proxmoxInstanceInput
- if st := readJSONBody(w, r, &in); st != 0 {
- writeBodyError(w, st, "invalid_json", "")
- return
- }
- // Parcial (#764): sobre una instancia EXISTENTE, los campos vacíos se
- // conservan (url/tokenId/secret opcionales); para una NUEVA se exigen
- // url + tokenId + secret. Borrar es DELETE (ya no "url vacía").
- tokenID := strings.TrimSpace(in.TokenID)
- if len(tokenID) > 128 || len(in.Secret) > 256 {
- writeError(w, http.StatusBadRequest, "invalid_input", "token too long")
- return
- }
- id := strings.TrimSpace(in.ID)
- if id == "" {
- id = "default" // legacy sin id
- }
- url := strings.TrimRight(strings.TrimSpace(in.URL), "/")
- if url != "" {
- u, err := urlpkg.Parse(url)
- if err != nil || (u.Scheme != "https" && u.Scheme != "http") || u.Host == "" {
- writeError(w, http.StatusBadRequest, "invalid_input", "url must be a valid http(s) URL")
- return
- }
- }
- list := pve.LoadInstances(s.db.DB)
- var current *pve.Instance
- for i := range list {
- if list[i].ID == id {
- current = &list[i]
- break
- }
- }
- if current != nil {
- if url == "" && tokenID == "" && strings.TrimSpace(in.Name) == "" && in.Secret == "" &&
- in.CAPEM == nil && in.FingerprintSHA256 == nil && in.Insecure == nil {
- writeError(w, http.StatusBadRequest, "invalid_input", "nada que actualizar")
- return
- }
- if url != "" {
- current.URL = url
- }
- if tokenID != "" {
- current.TokenID = tokenID
- }
- if in.Secret != "" {
- current.Secret = in.Secret
- }
- if in.CAPEM != nil {
- current.CAPEM = strings.TrimSpace(*in.CAPEM)
- }
- if in.FingerprintSHA256 != nil {
- current.FingerprintSHA256 = strings.TrimSpace(*in.FingerprintSHA256)
- }
- if in.Insecure != nil {
- current.Insecure = *in.Insecure
- }
- if n := strings.TrimSpace(in.Name); n != "" {
- current.Name = n
- }
- if err := pve.SaveInstances(s.db.DB, list); err != nil {
- writeError(w, http.StatusInternalServerError, "internal_error")
- return
- }
- w.WriteHeader(http.StatusNoContent)
- return
- }
- // Instancia nueva: completa.
- if url == "" || tokenID == "" || in.Secret == "" {
- writeError(w, http.StatusBadRequest, "invalid_input", "url, tokenId y secret son requeridos para una instancia nueva")
- return
- }
- name := strings.TrimSpace(in.Name)
- if name == "" {
- name = id
- }
- cfg := pve.Config{URL: url, TokenID: tokenID, Secret: in.Secret}
- if in.CAPEM != nil {
- cfg.CAPEM = strings.TrimSpace(*in.CAPEM)
- }
- if in.FingerprintSHA256 != nil {
- cfg.FingerprintSHA256 = strings.TrimSpace(*in.FingerprintSHA256)
- }
- if in.Insecure != nil {
- cfg.Insecure = *in.Insecure
- }
- inst := pve.Instance{ID: id, Name: name, Config: cfg}
- if err := pve.UpsertInstance(s.db.DB, inst); err != nil {
- writeError(w, http.StatusBadRequest, "invalid_input", err.Error())
- return
- }
- w.WriteHeader(http.StatusNoContent)
- }
- // DELETE /api/config/proxmox/{id} - elimina una instancia (#764).
- func (s *server) handleDeleteProxmoxConfig(w http.ResponseWriter, r *http.Request) {
- id := r.PathValue("id")
- if !pve.ValidInstanceID(id) {
- writeError(w, http.StatusBadRequest, "invalid_input", "id inválido")
- return
- }
- if err := pve.DeleteInstance(s.db.DB, id); err != nil {
- writeError(w, http.StatusInternalServerError, "internal_error")
- return
- }
- w.WriteHeader(http.StatusNoContent)
- }
- // POST /api/config/proxmox/test - prueba una instancia y cuenta lo que ve.
- //
- // Sin esto, guardar la config no daba señal alguna: un token sin permisos
- // autentica igual, la API responde 200 con listas vacías (PVE filtra, no
- // rechaza) y la integración se queda muda — indistinguible de un cluster
- // sin invitados. El resultado dice también QUÉ falta cuando es eso.
- //
- // Body opcional: {id} prueba la instancia guardada; {url, tokenId, secret}
- // prueba lo que el usuario acaba de teclear sin guardarlo. Un secret vacío
- // reutiliza el almacenado, igual que el PUT.
- func (s *server) handleTestProxmoxConfig(w http.ResponseWriter, r *http.Request) {
- var in proxmoxInstanceInput
- _ = readJSONBody(w, r, &in) // cuerpo opcional
- id := strings.TrimSpace(in.ID)
- if id == "" {
- id = "default"
- }
- var cfg pve.Config
- for _, inst := range pve.LoadInstances(s.db.DB) {
- if inst.ID == id {
- cfg = inst.Config
- break
- }
- }
- if u := strings.TrimRight(strings.TrimSpace(in.URL), "/"); u != "" {
- cfg.URL = u
- }
- if t := strings.TrimSpace(in.TokenID); t != "" {
- cfg.TokenID = t
- }
- if in.Secret != "" {
- cfg.Secret = in.Secret
- }
- if in.CAPEM != nil {
- cfg.CAPEM = strings.TrimSpace(*in.CAPEM)
- }
- if in.FingerprintSHA256 != nil {
- cfg.FingerprintSHA256 = strings.TrimSpace(*in.FingerprintSHA256)
- }
- if in.Insecure != nil {
- cfg.Insecure = *in.Insecure
- }
- if !cfg.Enabled() {
- writeError(w, http.StatusBadRequest, "invalid_input", "missing url, tokenId or secret")
- return
- }
- // Un fallo es un RESULTADO, no un error HTTP: el formulario tiene que
- // poder enseñar lo que contestó Proxmox.
- res, err := pve.NewClient(cfg).Test(r.Context())
- if err != nil {
- writeJSON(w, http.StatusOK, map[string]any{"ok": false, "error": err.Error()})
- return
- }
- writeJSON(w, http.StatusOK, map[string]any{
- "ok": true, "version": res.Version, "nodes": res.Nodes,
- "vms": res.VMs, "cts": res.CTs, "limited": res.Limited,
- })
- }
|