config.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550
  1. // config.go — rutas /api/config/* (paridad src/routes/config.js, SPEC §2.17):
  2. // CRUD de routers (tabla `routers`), clave SSH propia del servidor,
  3. // descubrimiento de la LAN y credenciales AdGuard GL.iNet (kv; la contraseña
  4. // NUNCA se devuelve). Tras cada mutación se sincroniza el adapter
  5. // (SetRouters) sin reiniciar.
  6. package httpapi
  7. import (
  8. "database/sql"
  9. "net/http"
  10. urlpkg "net/url"
  11. "regexp"
  12. "strconv"
  13. "strings"
  14. "github.com/gnacho/netpulse/server-go/internal/auth"
  15. "github.com/gnacho/netpulse/server-go/internal/discover"
  16. "github.com/gnacho/netpulse/server-go/internal/routerstore"
  17. "github.com/gnacho/netpulse/server-go/internal/sshkey"
  18. )
  19. var (
  20. hostRe = regexp.MustCompile(`^[a-zA-Z0-9._-]+$`)
  21. hostPortRe = regexp.MustCompile(`^([a-zA-Z0-9._-]+)(:[0-9]{1,5})?$`)
  22. )
  23. // registerConfigRoutes registra las rutas /api/config/* en el mux.
  24. // Las mutaciones (añadir/borrar routers) y las que exponen credenciales o
  25. // escanean la red (sshkey, discover) exigen rol admin (auditoría v2.4.0 §2,
  26. // issue #7); la lista de routers es de lectura y queda tras RequireAuth.
  27. func (s *server) registerConfigRoutes(mux *http.ServeMux) {
  28. mux.Handle("GET /api/config/sshkey", auth.RequireAdmin(http.HandlerFunc(s.handleGetSSHKey)))
  29. mux.Handle("POST /api/config/sshkey/rotate", auth.RequireAdmin(http.HandlerFunc(s.handleRotateSSHKey)))
  30. mux.Handle("GET /api/config/discover", auth.RequireAdmin(http.HandlerFunc(s.handleDiscover)))
  31. mux.HandleFunc("GET /api/config/routers", s.handleListConfigRouters)
  32. mux.Handle("POST /api/config/routers", auth.RequireAdmin(http.HandlerFunc(s.handleAddConfigRouter)))
  33. mux.Handle("PUT /api/config/routers/{id}", auth.RequireAdmin(http.HandlerFunc(s.handleUpdateConfigRouter)))
  34. mux.Handle("DELETE /api/config/routers/{id}", auth.RequireAdmin(http.HandlerFunc(s.handleDeleteConfigRouter)))
  35. mux.Handle("GET /api/config/adguard", auth.RequireAdmin(http.HandlerFunc(s.handleGetAdguardConfig)))
  36. mux.Handle("PUT /api/config/adguard", auth.RequireAdmin(http.HandlerFunc(s.handlePutAdguardConfig)))
  37. mux.Handle("GET /api/config/proxmox", auth.RequireAdmin(http.HandlerFunc(s.handleGetProxmoxConfig)))
  38. mux.Handle("PUT /api/config/proxmox", auth.RequireAdmin(http.HandlerFunc(s.handlePutProxmoxConfig)))
  39. }
  40. // syncRouters replica sync() de config.js: adapter.setRouters(listRouters(db)).
  41. func (s *server) syncRouters() {
  42. if s.adapter != nil {
  43. s.adapter.SetRouters(routerstore.ListRouters(s.db.DB))
  44. }
  45. }
  46. // GET /api/config/sshkey — clave pública propia para autorizar en routers.
  47. func (s *server) handleGetSSHKey(w http.ResponseWriter, r *http.Request) {
  48. key := sshkey.GetPublicKey(s.cfg.SSHKeyPath)
  49. if key == nil {
  50. writeError(w, http.StatusInternalServerError, "no_key")
  51. return
  52. }
  53. writeJSON(w, http.StatusOK, key)
  54. }
  55. // POST /api/config/sshkey/rotate — rota el par ed25519 del servidor (#242).
  56. // Respalda el par actual (keyPath.bak.<epoch>) y genera uno nuevo; devuelve
  57. // la nueva pública + fingerprint para reautorizarla en los routers. La clave
  58. // vieja deja de funcionar de inmediato: exige confirmación explícita del admin
  59. // (la UI pide escribir la palabra de confirmación).
  60. func (s *server) handleRotateSSHKey(w http.ResponseWriter, r *http.Request) {
  61. key, err := sshkey.RotateKeypair(s.cfg.SSHKeyPath)
  62. if err != nil {
  63. writeError(w, http.StatusInternalServerError, "rotate_failed", err.Error())
  64. return
  65. }
  66. writeJSON(w, http.StatusOK, map[string]any{
  67. "publicKey": key.PublicKey,
  68. "fingerprint": key.Fingerprint,
  69. "warning": "The previous key is no longer valid. Re-authorize this public key on every router before rotating again.",
  70. })
  71. }
  72. // GET /api/config/discover?force=1 — escaneo de la LAN (cacheado 60 s).
  73. func (s *server) handleDiscover(w http.ResponseWriter, r *http.Request) {
  74. result := discover.Routers(r.Context(), s.db.DB, s.cfg.SSHKeyPath, r.URL.Query().Get("force") == "1")
  75. writeJSON(w, http.StatusOK, result)
  76. }
  77. // GET /api/config/routers — lista configurada (no el estado sondeado).
  78. func (s *server) handleListConfigRouters(w http.ResponseWriter, r *http.Request) {
  79. writeJSON(w, http.StatusOK, map[string]any{"routers": routerstore.ListRouters(s.db.DB)})
  80. }
  81. type routerInput struct {
  82. Name *string `json:"name"`
  83. Host *string `json:"host"`
  84. Type string `json:"type"`
  85. Gateway bool `json:"gateway"`
  86. AgentOnly bool `json:"agent_only"`
  87. // FirmwareTarget: versión objetivo del firmware (issue #241; opcional).
  88. FirmwareTarget *string `json:"firmware_target"`
  89. // SNMP (issue #309): credenciales para sondeo SNMP del switch gestionado.
  90. SnmpEnabled *bool `json:"snmp_enabled"`
  91. SnmpCommunity *string `json:"snmp_community"`
  92. SnmpPort *int `json:"snmp_port"`
  93. SnmpPollInterval *int `json:"snmp_poll_interval"` // issue #414; segundos
  94. // SSHPort (issue #605): puerto SSH del router (dropbear en puerto no
  95. // estándar). Ausente/0 → 22.
  96. SSHPort *int `json:"ssh_port"`
  97. }
  98. // validateHost replica hostSchema (trim, 1..253, regex). Devuelve el valor
  99. // trimmeado o "" + mensaje de error.
  100. func validateHost(host string) (string, string) {
  101. h := strings.TrimSpace(host)
  102. if len(h) < 1 {
  103. return "", "String must contain at least 1 character(s)"
  104. }
  105. if len(h) > 253 {
  106. return "", "String must contain at most 253 character(s)"
  107. }
  108. if !hostRe.MatchString(h) {
  109. return "", "host debe ser una IP o hostname válido"
  110. }
  111. return h, ""
  112. }
  113. // validateAdGuardHost permite host o host:puerto (1..65535). Devuelve
  114. // host, puerto y mensaje de error.
  115. func validateAdGuardHost(host string) (string, int, string) {
  116. h := strings.TrimSpace(host)
  117. if len(h) < 1 {
  118. return "", 0, "String must contain at least 1 character(s)"
  119. }
  120. if len(h) > 253 {
  121. return "", 0, "String must contain at most 253 character(s)"
  122. }
  123. m := hostPortRe.FindStringSubmatch(h)
  124. if m == nil {
  125. return "", 0, "host debe ser una IP, hostname o host:puerto válido"
  126. }
  127. addr := m[1]
  128. port := 0
  129. if m[2] != "" {
  130. p, err := strconv.Atoi(m[2][1:])
  131. if err != nil || p < 1 || p > 65535 {
  132. return "", 0, "puerto fuera de rango (1-65535)"
  133. }
  134. port = p
  135. }
  136. return addr, port, ""
  137. }
  138. // POST /api/config/routers — añadir router manualmente desde Ajustes.
  139. func (s *server) handleAddConfigRouter(w http.ResponseWriter, r *http.Request) {
  140. var in routerInput
  141. if st := readJSONBody(w, r, &in); st != 0 {
  142. writeBodyError(w, st, "invalid_json", "")
  143. return
  144. }
  145. // Orden de validación del schema zod: name, host, type
  146. name := ""
  147. if in.Name != nil {
  148. name = strings.TrimSpace(*in.Name)
  149. if len(name) < 1 {
  150. writeError(w, http.StatusBadRequest, "invalid_input", "String must contain at least 1 character(s)")
  151. return
  152. }
  153. if len(name) > 60 {
  154. writeError(w, http.StatusBadRequest, "invalid_input", "String must contain at most 60 character(s)")
  155. return
  156. }
  157. }
  158. if in.Host == nil {
  159. writeError(w, http.StatusBadRequest, "invalid_input", "Required")
  160. return
  161. }
  162. host, msg := validateHost(*in.Host)
  163. if msg != "" {
  164. writeError(w, http.StatusBadRequest, "invalid_input", msg)
  165. return
  166. }
  167. typ := in.Type
  168. if typ == "" {
  169. typ = "openwrt"
  170. }
  171. if typ != "glinet" && typ != "openwrt" && typ != "managed-switch" && typ != "external" {
  172. writeError(w, http.StatusBadRequest, "invalid_input", "Invalid enum value. Expected 'glinet' | 'openwrt' | 'managed-switch' | 'external'")
  173. return
  174. }
  175. var firmwareTarget string
  176. if in.FirmwareTarget != nil {
  177. firmwareTarget = strings.TrimSpace(*in.FirmwareTarget)
  178. }
  179. snmpEnabled := false
  180. if in.SnmpEnabled != nil {
  181. snmpEnabled = *in.SnmpEnabled
  182. }
  183. snmpCommunity := ""
  184. if in.SnmpCommunity != nil {
  185. snmpCommunity = strings.TrimSpace(*in.SnmpCommunity)
  186. }
  187. snmpPort := 0
  188. if in.SnmpPort != nil {
  189. snmpPort = *in.SnmpPort
  190. if snmpPort < 0 || snmpPort > 65535 {
  191. writeError(w, http.StatusBadRequest, "invalid_input", "snmp_port must be between 0 and 65535")
  192. return
  193. }
  194. }
  195. snmpInterval := 60
  196. if in.SnmpPollInterval != nil {
  197. snmpInterval = *in.SnmpPollInterval
  198. if snmpInterval < 10 || snmpInterval > 3600 {
  199. writeError(w, http.StatusBadRequest, "invalid_input", "snmp_poll_interval must be between 10 and 3600")
  200. return
  201. }
  202. }
  203. for _, rt := range routerstore.ListRouters(s.db.DB) {
  204. if rt.Host == host {
  205. writeError(w, http.StatusConflict, "duplicate_host", "Ya hay un router con "+host)
  206. return
  207. }
  208. }
  209. sshPort := 0
  210. if in.SSHPort != nil {
  211. p := *in.SSHPort
  212. if p < 1 || p > 65535 {
  213. writeError(w, http.StatusBadRequest, "invalid_input", "ssh_port must be between 1 and 65535")
  214. return
  215. }
  216. sshPort = p
  217. }
  218. created, err := routerstore.AddRouter(s.db.DB, routerstore.AddInput{
  219. Name: name, Host: host, Type: typ, IsGateway: in.Gateway, AgentOnly: in.AgentOnly,
  220. FirmwareTarget: firmwareTarget,
  221. SnmpEnabled: snmpEnabled, SnmpCommunity: snmpCommunity, SnmpPort: snmpPort, SnmpPollInterval: snmpInterval,
  222. SSHPort: sshPort,
  223. })
  224. if err != nil {
  225. writeError(w, http.StatusInternalServerError, "internal_error")
  226. return
  227. }
  228. s.syncRouters()
  229. writeJSON(w, http.StatusCreated, map[string]any{"router": created})
  230. }
  231. // DELETE /api/config/routers/:id — 204 o 404.
  232. func (s *server) handleDeleteConfigRouter(w http.ResponseWriter, r *http.Request) {
  233. if !routerstore.RemoveRouter(s.db.DB, r.PathValue("id")) {
  234. writeError(w, http.StatusNotFound, "not_found")
  235. return
  236. }
  237. s.syncRouters()
  238. w.WriteHeader(http.StatusNoContent)
  239. }
  240. // PUT /api/config/routers/:id — edita host/name/type/gateway/agent_only.
  241. // Campos omitidos (nil) no se tocan. 404 si el router no existe.
  242. func (s *server) handleUpdateConfigRouter(w http.ResponseWriter, r *http.Request) {
  243. id := r.PathValue("id")
  244. var in routerInput
  245. if st := readJSONBody(w, r, &in); st != 0 {
  246. writeBodyError(w, st, "invalid_json", "")
  247. return
  248. }
  249. var name *string
  250. if in.Name != nil {
  251. n := strings.TrimSpace(*in.Name)
  252. if len(n) < 1 {
  253. writeError(w, http.StatusBadRequest, "invalid_input", "String must contain at least 1 character(s)")
  254. return
  255. }
  256. if len(n) > 60 {
  257. writeError(w, http.StatusBadRequest, "invalid_input", "String must contain at most 60 character(s)")
  258. return
  259. }
  260. name = &n
  261. }
  262. var host *string
  263. if in.Host != nil {
  264. h, msg := validateHost(*in.Host)
  265. if msg != "" {
  266. writeError(w, http.StatusBadRequest, "invalid_input", msg)
  267. return
  268. }
  269. // Duplicado: otro router con ese host (excluyendo el propio id).
  270. for _, rt := range routerstore.ListRouters(s.db.DB) {
  271. if rt.Host == h && rt.ID != id {
  272. writeError(w, http.StatusConflict, "duplicate_host", "Ya hay un router con "+h)
  273. return
  274. }
  275. }
  276. host = &h
  277. }
  278. var typ *string
  279. if in.Type != "" {
  280. t := in.Type
  281. if t != "glinet" && t != "openwrt" && t != "managed-switch" && t != "external" {
  282. writeError(w, http.StatusBadRequest, "invalid_input", "Invalid enum value. Expected 'glinet' | 'openwrt' | 'managed-switch' | 'external'")
  283. return
  284. }
  285. typ = &t
  286. }
  287. gw := in.Gateway
  288. ao := in.AgentOnly
  289. var firmwareTarget *string
  290. if in.FirmwareTarget != nil {
  291. v := strings.TrimSpace(*in.FirmwareTarget)
  292. firmwareTarget = &v
  293. }
  294. var snmpPollInterval *int
  295. if in.SnmpPollInterval != nil {
  296. v := *in.SnmpPollInterval
  297. if v < 10 || v > 3600 {
  298. writeError(w, http.StatusBadRequest, "invalid_input", "snmp_poll_interval must be between 10 and 3600")
  299. return
  300. }
  301. snmpPollInterval = &v
  302. }
  303. var snmpPort *int
  304. if in.SnmpPort != nil {
  305. p := *in.SnmpPort
  306. if p < 0 || p > 65535 {
  307. writeError(w, http.StatusBadRequest, "invalid_input", "snmp_port must be between 0 and 65535")
  308. return
  309. }
  310. snmpPort = &p
  311. }
  312. var snmpCommunity *string
  313. if in.SnmpCommunity != nil {
  314. v := strings.TrimSpace(*in.SnmpCommunity)
  315. snmpCommunity = &v
  316. }
  317. var sshPort *int
  318. if in.SSHPort != nil {
  319. p := *in.SSHPort
  320. if p < 1 || p > 65535 {
  321. writeError(w, http.StatusBadRequest, "invalid_input", "ssh_port must be between 1 and 65535")
  322. return
  323. }
  324. sshPort = &p
  325. }
  326. updated, ok := routerstore.UpdateRouter(s.db.DB, id, routerstore.UpdateInput{
  327. Name: name, Host: host, Type: typ,
  328. IsGateway: &gw, AgentOnly: &ao,
  329. FirmwareTarget: firmwareTarget,
  330. SnmpEnabled: in.SnmpEnabled, SnmpCommunity: snmpCommunity, SnmpPort: snmpPort, SnmpPollInterval: snmpPollInterval,
  331. SSHPort: sshPort,
  332. })
  333. if !ok {
  334. writeError(w, http.StatusNotFound, "not_found")
  335. return
  336. }
  337. s.syncRouters()
  338. writeJSON(w, http.StatusOK, map[string]any{"router": updated})
  339. }
  340. // --- AdGuard Home (GL.iNet) — solo admin; la contraseña NO se devuelve ---
  341. func kvGet(db *sql.DB, key string) string {
  342. var v string
  343. if err := db.QueryRow("SELECT value FROM kv WHERE key = ?", key).Scan(&v); err != nil {
  344. return ""
  345. }
  346. return v
  347. }
  348. // GET /api/config/adguard — {mode, host, port, user ('root' por defecto), passSet}.
  349. func (s *server) handleGetAdguardConfig(w http.ResponseWriter, r *http.Request) {
  350. user := kvGet(s.db.DB, "adguard_user")
  351. if user == "" {
  352. user = "root"
  353. }
  354. mode := kvGet(s.db.DB, "adguard_mode")
  355. if mode == "" {
  356. mode = "glinet"
  357. }
  358. portStr := kvGet(s.db.DB, "adguard_port")
  359. port := 0
  360. if p, err := strconv.Atoi(portStr); err == nil {
  361. port = p
  362. }
  363. writeJSON(w, http.StatusOK, map[string]any{
  364. "mode": mode,
  365. "host": kvGet(s.db.DB, "adguard_host"),
  366. "port": port,
  367. "user": user,
  368. "passSet": kvGet(s.db.DB, "adguard_pass") != "",
  369. })
  370. }
  371. type adguardInput struct {
  372. Mode string `json:"mode"`
  373. Host *string `json:"host"`
  374. Port int `json:"port"`
  375. User string `json:"user"`
  376. Password string `json:"password"`
  377. }
  378. // PUT /api/config/adguard — upsert en kv (password solo si viene). 204.
  379. func (s *server) handlePutAdguardConfig(w http.ResponseWriter, r *http.Request) {
  380. var in adguardInput
  381. if st := readJSONBody(w, r, &in); st != 0 {
  382. writeBodyError(w, st, "invalid_json", "")
  383. return
  384. }
  385. mode := strings.ToLower(strings.TrimSpace(in.Mode))
  386. if mode == "" {
  387. mode = "glinet"
  388. }
  389. if mode != "glinet" && mode != "standard" {
  390. writeError(w, http.StatusBadRequest, "invalid_input", "Invalid enum value. Expected 'glinet' | 'standard'")
  391. return
  392. }
  393. if in.Host == nil {
  394. writeError(w, http.StatusBadRequest, "invalid_input", "Required")
  395. return
  396. }
  397. host := strings.TrimSpace(*in.Host)
  398. port := 0
  399. if mode == "standard" {
  400. hostFromVal, portFromHost, msg := validateAdGuardHost(host)
  401. if msg != "" {
  402. writeError(w, http.StatusBadRequest, "invalid_input", msg)
  403. return
  404. }
  405. host = hostFromVal
  406. if in.Port < 1 || in.Port > 65535 {
  407. writeError(w, http.StatusBadRequest, "invalid_input", "port must be between 1 and 65535")
  408. return
  409. }
  410. port = in.Port
  411. if port == 0 {
  412. port = portFromHost
  413. }
  414. if port == 0 {
  415. port = 3000
  416. }
  417. }
  418. user := strings.TrimSpace(in.User)
  419. if user == "" {
  420. user = "root"
  421. }
  422. if len(user) > 64 {
  423. writeError(w, http.StatusBadRequest, "invalid_input", "String must contain at most 64 character(s)")
  424. return
  425. }
  426. if len(in.Password) > 128 {
  427. writeError(w, http.StatusBadRequest, "invalid_input", "String must contain at most 128 character(s)")
  428. return
  429. }
  430. upsert := "INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value"
  431. if _, err := s.db.Exec(upsert, "adguard_mode", mode); err != nil {
  432. writeError(w, http.StatusInternalServerError, "internal_error")
  433. return
  434. }
  435. if _, err := s.db.Exec(upsert, "adguard_host", host); err != nil {
  436. writeError(w, http.StatusInternalServerError, "internal_error")
  437. return
  438. }
  439. if mode == "standard" {
  440. if _, err := s.db.Exec(upsert, "adguard_port", strconv.Itoa(port)); err != nil {
  441. writeError(w, http.StatusInternalServerError, "internal_error")
  442. return
  443. }
  444. } else {
  445. if _, err := s.db.Exec("DELETE FROM kv WHERE key = ?", "adguard_port"); err != nil {
  446. writeError(w, http.StatusInternalServerError, "internal_error")
  447. return
  448. }
  449. }
  450. if _, err := s.db.Exec(upsert, "adguard_user", user); err != nil {
  451. writeError(w, http.StatusInternalServerError, "internal_error")
  452. return
  453. }
  454. if in.Password != "" {
  455. if _, err := s.db.Exec(upsert, "adguard_pass", in.Password); err != nil {
  456. writeError(w, http.StatusInternalServerError, "internal_error")
  457. return
  458. }
  459. }
  460. w.WriteHeader(http.StatusNoContent)
  461. }
  462. // GET /api/config/proxmox — {url, tokenId, tokenSet} (el secret nunca se
  463. // devuelve). Config de la integración PVE del #561.
  464. func (s *server) handleGetProxmoxConfig(w http.ResponseWriter, r *http.Request) {
  465. writeJSON(w, http.StatusOK, map[string]any{
  466. "url": kvGet(s.db.DB, "proxmox_url"),
  467. "tokenId": kvGet(s.db.DB, "proxmox_token_id"),
  468. "tokenSet": kvGet(s.db.DB, "proxmox_token_secret") != "",
  469. })
  470. }
  471. type proxmoxInput struct {
  472. URL *string `json:"url"` // nil = no tocar; "" = desactivar
  473. TokenID string `json:"tokenId"`
  474. Secret string `json:"secret"` // solo si viene (se conserva el anterior)
  475. }
  476. // PUT /api/config/proxmox — upsert en kv (secret solo si viene). 204.
  477. // url: base del cluster pve (p. ej. "https://192.168.1.100:8006").
  478. // tokenId: "USER@REALM!TOKENID"; secret: la parte UUID del token.
  479. func (s *server) handlePutProxmoxConfig(w http.ResponseWriter, r *http.Request) {
  480. var in proxmoxInput
  481. if st := readJSONBody(w, r, &in); st != 0 {
  482. writeBodyError(w, st, "invalid_json", "")
  483. return
  484. }
  485. tokenID := strings.TrimSpace(in.TokenID)
  486. if len(tokenID) > 128 || len(in.Secret) > 256 {
  487. writeError(w, http.StatusBadRequest, "invalid_input", "token too long")
  488. return
  489. }
  490. upsert := "INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value"
  491. if in.URL != nil {
  492. url := strings.TrimRight(strings.TrimSpace(*in.URL), "/")
  493. if url == "" {
  494. // url vacío = desactivar la integración: limpia todo.
  495. for _, k := range []string{"proxmox_url", "proxmox_token_id", "proxmox_token_secret"} {
  496. if _, err := s.db.Exec("DELETE FROM kv WHERE key = ?", k); err != nil {
  497. writeError(w, http.StatusInternalServerError, "internal_error")
  498. return
  499. }
  500. }
  501. w.WriteHeader(http.StatusNoContent)
  502. return
  503. }
  504. u, err := urlpkg.Parse(url)
  505. if err != nil || (u.Scheme != "https" && u.Scheme != "http") || u.Host == "" {
  506. writeError(w, http.StatusBadRequest, "invalid_input", "url must be a valid http(s) URL")
  507. return
  508. }
  509. if _, err := s.db.Exec(upsert, "proxmox_url", url); err != nil {
  510. writeError(w, http.StatusInternalServerError, "internal_error")
  511. return
  512. }
  513. }
  514. if tokenID != "" {
  515. if _, err := s.db.Exec(upsert, "proxmox_token_id", tokenID); err != nil {
  516. writeError(w, http.StatusInternalServerError, "internal_error")
  517. return
  518. }
  519. }
  520. if in.Secret != "" {
  521. if _, err := s.db.Exec(upsert, "proxmox_token_secret", in.Secret); err != nil {
  522. writeError(w, http.StatusInternalServerError, "internal_error")
  523. return
  524. }
  525. }
  526. w.WriteHeader(http.StatusNoContent)
  527. }