update_handlers.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. package api
  2. import (
  3. "context"
  4. "encoding/json"
  5. "errors"
  6. "net/http"
  7. "net/url"
  8. "os"
  9. "os/exec"
  10. "path/filepath"
  11. release "proxmox-router"
  12. "proxmox-router/internal/auth"
  13. "regexp"
  14. "strconv"
  15. "strings"
  16. "time"
  17. )
  18. var BuildCommit = "unknown"
  19. const updateDir = "/var/lib/debtik/update"
  20. var pinPattern = regexp.MustCompile(`^sha256//[A-Za-z0-9+/]{43}=$`)
  21. type updateConfig struct {
  22. Repository string `json:"repository"`
  23. Branch string `json:"branch"`
  24. TLSKeyPin string `json:"tls_key_pin,omitempty"`
  25. }
  26. func validUpdateConfig(c updateConfig) bool {
  27. u, err := url.Parse(c.Repository)
  28. if err != nil {
  29. return false
  30. }
  31. if u.User != nil {
  32. if u.Scheme != "ssh" || u.User.Username() == "" {
  33. return false
  34. }
  35. if _, hasPassword := u.User.Password(); hasPassword {
  36. return false
  37. }
  38. }
  39. return (c.TLSKeyPin == "" || pinPattern.MatchString(c.TLSKeyPin)) && u.Host != "" && (u.Scheme == "http" || u.Scheme == "https" || u.Scheme == "ssh")
  40. }
  41. func readUpdateConfig() updateConfig {
  42. var c updateConfig
  43. data, err := os.ReadFile(filepath.Join(updateDir, "config.json"))
  44. if err == nil {
  45. _ = json.Unmarshal(data, &c)
  46. }
  47. return c
  48. }
  49. func requireUpdateAdmin(w http.ResponseWriter, r *http.Request) bool {
  50. session := getSessionFromContext(r.Context())
  51. if session == nil || session.Role != auth.RoleFull {
  52. http.Error(w, "Administrator required", http.StatusForbidden)
  53. return false
  54. }
  55. return true
  56. }
  57. func (s *Server) handleUpdateStatus(w http.ResponseWriter, r *http.Request) {
  58. c := readUpdateConfig()
  59. state := "idle"
  60. if data, err := os.ReadFile(filepath.Join(updateDir, "status")); err == nil {
  61. state = strings.TrimSpace(string(data))
  62. }
  63. logData, _ := os.ReadFile(filepath.Join(updateDir, "update.log"))
  64. if len(logData) > 12000 {
  65. logData = logData[len(logData)-12000:]
  66. }
  67. writeJSON(w, http.StatusOK, map[string]any{"repository": c.Repository, "branch": c.Branch, "tls_key_pin": c.TLSKeyPin, "installed_commit": BuildCommit, "installed_version": release.Version(), "state": state, "log": string(logData)})
  68. }
  69. func (s *Server) handleUpdateConfig(w http.ResponseWriter, r *http.Request) {
  70. if !requireUpdateAdmin(w, r) {
  71. return
  72. }
  73. var c updateConfig
  74. if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 4096)).Decode(&c); err != nil || !validUpdateConfig(c) {
  75. http.Error(w, "Valid HTTP(S)/SSH repository and branch required", http.StatusBadRequest)
  76. return
  77. }
  78. if err := os.MkdirAll(updateDir, 0700); err != nil {
  79. http.Error(w, err.Error(), 500)
  80. return
  81. }
  82. data, _ := json.Marshal(c)
  83. tmp, err := os.CreateTemp(updateDir, ".config-*")
  84. if err != nil {
  85. http.Error(w, err.Error(), 500)
  86. return
  87. }
  88. defer os.Remove(tmp.Name())
  89. if _, err = tmp.Write(data); err == nil {
  90. err = tmp.Close()
  91. } else {
  92. tmp.Close()
  93. }
  94. if err == nil {
  95. err = os.Rename(tmp.Name(), filepath.Join(updateDir, "config.json"))
  96. }
  97. if err != nil {
  98. http.Error(w, err.Error(), 500)
  99. return
  100. }
  101. writeJSON(w, 200, c)
  102. }
  103. func availableRelease(ctx context.Context, c updateConfig) (string, string, error) {
  104. ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
  105. defer cancel()
  106. args := []string{}
  107. if c.TLSKeyPin != "" {
  108. args = append(args, "-c", "http.sslVerify=false", "-c", "http.pinnedpubkey="+c.TLSKeyPin)
  109. }
  110. args = append(args, "ls-remote", "--tags", c.Repository, "refs/tags/v*")
  111. cmd := exec.CommandContext(ctx, "git", args...)
  112. cmd.Env = append(os.Environ(), "GIT_TERMINAL_PROMPT=0")
  113. data, err := cmd.Output()
  114. if err != nil {
  115. return "", "", err
  116. }
  117. return release.LatestTag(string(data))
  118. }
  119. func (s *Server) handleUpdateCheck(w http.ResponseWriter, r *http.Request) {
  120. if !requireUpdateAdmin(w, r) {
  121. return
  122. }
  123. c := readUpdateConfig()
  124. if !validUpdateConfig(c) {
  125. http.Error(w, "Configure repository first", 400)
  126. return
  127. }
  128. version, commit, err := availableRelease(r.Context(), c)
  129. if err != nil {
  130. http.Error(w, "Cannot find a stable version tag in repository", 502)
  131. return
  132. }
  133. newer, err := release.Newer(version, release.Version())
  134. if err != nil {
  135. http.Error(w, err.Error(), 500)
  136. return
  137. }
  138. writeJSON(w, 200, map[string]any{"installed_version": release.Version(), "available_version": version, "installed_commit": BuildCommit, "available_commit": commit, "update_available": newer})
  139. }
  140. func (s *Server) handleUpdateAction(w http.ResponseWriter, r *http.Request) {
  141. if !requireUpdateAdmin(w, r) {
  142. return
  143. }
  144. action := r.PathValue("action")
  145. if action != "install" && action != "rollback" {
  146. http.Error(w, "Unknown action", 400)
  147. return
  148. }
  149. c := readUpdateConfig()
  150. if action == "install" && !validUpdateConfig(c) {
  151. http.Error(w, "Configure repository first", 400)
  152. return
  153. }
  154. if action == "install" {
  155. candidate, _, err := availableRelease(r.Context(), c)
  156. if err != nil {
  157. http.Error(w, "Cannot read release versions", 502)
  158. return
  159. }
  160. newer, err := release.Newer(candidate, release.Version())
  161. if err != nil || !newer {
  162. http.Error(w, "Update requires a version greater than the installed version", 409)
  163. return
  164. }
  165. }
  166. if _, err := os.Stat("/usr/local/libexec/debtik-update"); err != nil {
  167. http.Error(w, "Update helper is not installed", 503)
  168. return
  169. }
  170. if err := os.MkdirAll(updateDir, 0700); err != nil {
  171. http.Error(w, err.Error(), 500)
  172. return
  173. }
  174. args := []string{"--unit=debtik-update-" + action + "-" + strconv.FormatInt(time.Now().UnixNano(), 10), "--collect", "/usr/local/libexec/debtik-update", action}
  175. if action == "install" {
  176. args = append(args, c.Repository, "master", c.TLSKeyPin)
  177. }
  178. cmd := exec.CommandContext(r.Context(), "systemd-run", args...)
  179. if out, err := cmd.CombinedOutput(); err != nil {
  180. if errors.Is(err, exec.ErrNotFound) {
  181. http.Error(w, "systemd-run unavailable", 503)
  182. } else {
  183. http.Error(w, string(out), 409)
  184. }
  185. return
  186. }
  187. writeJSON(w, http.StatusAccepted, map[string]string{"state": "starting", "action": action})
  188. }