middleware.go 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. // middleware.go — requireAuth / requireAdmin (paridad auth.js:258-278).
  2. package auth
  3. import (
  4. "context"
  5. "encoding/json"
  6. "net/http"
  7. "net/url"
  8. "strings"
  9. "github.com/gnacho/netpulse/server-go/internal/db"
  10. )
  11. type ctxKey int
  12. const (
  13. ctxUser ctxKey = iota
  14. ctxSessionID
  15. ctxAPIToken
  16. )
  17. // UserFromContext devuelve el usuario autenticado (nil si no hay).
  18. func UserFromContext(ctx context.Context) *User {
  19. u, _ := ctx.Value(ctxUser).(*User)
  20. return u
  21. }
  22. // SessionIDFromContext devuelve el sessionId autenticado ("" si no hay).
  23. func SessionIDFromContext(ctx context.Context) string {
  24. s, _ := ctx.Value(ctxSessionID).(string)
  25. return s
  26. }
  27. // TokenValidator valida un bearer token y devuelve el usuario y scope.
  28. // Devuelve nil si el token no es válido. Implementado por apitoken.Store.
  29. type TokenValidator interface {
  30. ValidateBearer(raw string) (*User, string)
  31. }
  32. // Scopes de los API tokens. Un token read solo puede usar métodos seguros,
  33. // write puede mutar rutas no admin y admin alcanza también RequireAdmin.
  34. const (
  35. ScopeRead = "read"
  36. ScopeWrite = "write"
  37. ScopeAdmin = "admin"
  38. )
  39. // APITokenFromContext devuelve el scope del token API usado ("" si no es token).
  40. func APITokenFromContext(ctx context.Context) string {
  41. s, _ := ctx.Value(ctxAPIToken).(string)
  42. return s
  43. }
  44. // WriteError escribe el envelope de error {error, message?} con el status dado.
  45. func WriteError(w http.ResponseWriter, status int, code string, message ...string) {
  46. w.Header().Set("Content-Type", "application/json")
  47. w.WriteHeader(status)
  48. body := map[string]any{"error": code}
  49. if len(message) > 0 {
  50. body["message"] = message[0]
  51. }
  52. // json.Marshal (no Encoder): el cuerpo debe ser literal como Hono, SIN
  53. // el '\n' final que añade Encode.
  54. data, _ := json.Marshal(body)
  55. _, _ = w.Write(data)
  56. }
  57. // isAgentReportPath: /api/agents/{slug}/binary|stream|apply-result|upgrade-result|upgrade-progress|firmware-progress|firmware-result|firmware-backup.
  58. func isAgentReportPath(path string) bool {
  59. return strings.HasPrefix(path, "/api/agents/") &&
  60. (strings.HasSuffix(path, "/binary") || strings.HasSuffix(path, "/stream") ||
  61. strings.HasSuffix(path, "/apply-result") || strings.HasSuffix(path, "/upgrade-result") ||
  62. strings.HasSuffix(path, "/upgrade-progress") || strings.HasSuffix(path, "/firmware-progress") ||
  63. strings.HasSuffix(path, "/firmware-result") || strings.HasSuffix(path, "/firmware-backup"))
  64. }
  65. // IsAgentRequest reports whether r is a route agents and embedders call with
  66. // their own token - pushes, reports, pairing, config backups - rather than a
  67. // person with a session or an API token. FORK: while HTTPS is being rolled
  68. // out these keep working over plain HTTP until each agent has moved, when
  69. // everything else is already refused there.
  70. func IsAgentRequest(r *http.Request) bool {
  71. p := r.URL.Path
  72. return p == "/api/ingest/agent" || p == "/api/agents/pair" || p == "/api/agents/pair/hello" ||
  73. p == "/api/agents/executor-token" || p == "/api/agents/install-agent.sh" ||
  74. isAgentReportPath(p) ||
  75. (p == "/api/config-backup" && r.Method == http.MethodPost)
  76. }
  77. // isAnonymousPath indica si la ruta no requiere sesión (auth propia en el handler).
  78. func isAnonymousPath(path string) bool {
  79. if path == "/api/health" || path == "/api/auth/login" ||
  80. path == "/api/ingest/agent" || path == "/api/agents/pair" ||
  81. path == "/api/agents/pair/hello" || // FORK: proves the served key; no secret in or out
  82. path == "/api/agents/executor-token" ||
  83. // #1751: instalador servido por el servidor; lo baja curl desde el
  84. // router antes de que exista nada que autenticar (el token viaja en
  85. // los argumentos del script, no en la descarga).
  86. path == "/api/agents/install-agent.sh" ||
  87. isAgentReportPath(path) {
  88. return true
  89. }
  90. return false
  91. }
  92. // RequireAuth es middleware global: todo /api/* exige sesión salvo
  93. // /api/health, /api/auth/login, /api/ingest/agent (auth Bearer por token
  94. // de equipo), /api/agents/pair (pairing token de un solo uso, Fase 9 R3),
  95. // /api/agents/{slug}/binary (auth Bearer por token de agente,
  96. // Fase 6.2), /api/agents/{slug}/stream (SSE bidireccional, Fase 7.3),
  97. // /api/agents/{slug}/apply-result, /api/agents/{slug}/upgrade-result,
  98. // /api/agents/{slug}/upgrade-progress, /api/agents/{slug}/firmware-progress y
  99. // /api/agents/{slug}/firmware-result y /api/agents/{slug}/firmware-backup
  100. // (reportes del agente, auth Bearer), y /api/agents/install-agent.sh (#1751:
  101. // el instalador que baja curl en el router, sin secretos en el cuerpo).
  102. // POST /api/config-backup (issue #340): recibe snapshots UCI desde NetGrip;
  103. // auth Bearer por token de agente validado en el handler.
  104. // Acepta Bearer tokens de API (#330) como alternativa a la cookie de sesión.
  105. // Fallo → 401 {error:'unauthorized'}.
  106. func RequireAuth(d *db.DB, secret string, tv TokenValidator, next http.Handler) http.Handler {
  107. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  108. path := r.URL.Path
  109. if !strings.HasPrefix(path, "/api/") || isAnonymousPath(path) ||
  110. (path == "/api/config-backup" && r.Method == http.MethodPost) {
  111. next.ServeHTTP(w, r)
  112. return
  113. }
  114. if tv != nil {
  115. if raw := bearerToken(r); raw != "" {
  116. if user, scope := tv.ValidateBearer(raw); user != nil {
  117. if !scopeAllowsMethod(scope, r.Method) {
  118. WriteError(w, http.StatusForbidden, "insufficient_scope")
  119. return
  120. }
  121. ctx := context.WithValue(r.Context(), ctxUser, user)
  122. ctx = context.WithValue(ctx, ctxAPIToken, scope)
  123. next.ServeHTTP(w, r.WithContext(ctx))
  124. return
  125. }
  126. }
  127. }
  128. sess := SessionUserFromRequest(d, secret, r)
  129. if sess == nil {
  130. WriteError(w, http.StatusUnauthorized, "unauthorized")
  131. return
  132. }
  133. ctx := context.WithValue(r.Context(), ctxUser, sess.User)
  134. ctx = context.WithValue(ctx, ctxSessionID, sess.SessionID)
  135. next.ServeHTTP(w, r.WithContext(ctx))
  136. })
  137. }
  138. func bearerToken(r *http.Request) string {
  139. v := r.Header.Get("Authorization")
  140. if v == "" {
  141. return ""
  142. }
  143. if !strings.HasPrefix(v, "Bearer ") {
  144. return ""
  145. }
  146. return strings.TrimPrefix(v, "Bearer ")
  147. }
  148. // scopeAllowsMethod aplica el contrato de los scopes al método HTTP. Un token
  149. // read es de solo lectura: GET, HEAD y OPTIONS. write y admin pueden mutar,
  150. // pero solo admin supera además RequireAdmin.
  151. func scopeAllowsMethod(scope, method string) bool {
  152. switch scope {
  153. case ScopeWrite, ScopeAdmin:
  154. return true
  155. case ScopeRead:
  156. switch method {
  157. case http.MethodGet, http.MethodHead, http.MethodOptions:
  158. return true
  159. }
  160. }
  161. return false
  162. }
  163. // RequireAdmin exige role === 'admin' (tras RequireAuth) → 403 {error:'forbidden'}.
  164. // Con un API token exige además scope admin: un token read o write emitido por
  165. // un admin no hereda el rol y no entra en rutas de administración.
  166. func RequireAdmin(next http.Handler) http.Handler {
  167. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  168. user := UserFromContext(r.Context())
  169. if user == nil || user.Role != "admin" {
  170. WriteError(w, http.StatusForbidden, "forbidden")
  171. return
  172. }
  173. if scope := APITokenFromContext(r.Context()); scope != "" && scope != ScopeAdmin {
  174. WriteError(w, http.StatusForbidden, "insufficient_scope")
  175. return
  176. }
  177. next.ServeHTTP(w, r)
  178. })
  179. }
  180. // RequireSameOrigin es la defensa CSRF (issue #213). SameSite=Lax cubre el
  181. // envío de cookies cross-site de fetch/XHR, pero no hay defensa en
  182. // profundidad si la app se sirve desde otro origen o un navegador sin
  183. // SameSite. En mutaciones (POST/PUT/DELETE) se valida el header Origin contra
  184. // el host efectivo de la petición (X-Forwarded-Host si TRUST_PROXY, si no
  185. // r.Host). Un Origin ausente (cliente no-navegador: agente, curl, CLI) se
  186. // deja pasar; si el navegador envía Sec-Fetch-Site: cross-site sin Origin, se
  187. // rechaza igualmente. Un Origin que no casa → 403 {error:'cross_origin'}.
  188. func RequireSameOrigin(next http.Handler) http.Handler {
  189. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  190. if r.Method == http.MethodPost || r.Method == http.MethodPut || r.Method == http.MethodDelete {
  191. if !originAllowed(r) {
  192. WriteError(w, http.StatusForbidden, "cross_origin")
  193. return
  194. }
  195. }
  196. next.ServeHTTP(w, r)
  197. })
  198. }
  199. // originAllowed valida el header Origin (si viene) contra el host efectivo.
  200. func originAllowed(r *http.Request) bool {
  201. origin := r.Header.Get("Origin")
  202. if origin == "" {
  203. if sf := r.Header.Get("Sec-Fetch-Site"); sf != "" {
  204. return sf != "cross-site"
  205. }
  206. return true
  207. }
  208. u, err := url.Parse(origin)
  209. if err != nil {
  210. return false
  211. }
  212. // Origin "null" (iframe sandbox / redirect) no tiene host → no casa.
  213. if u.Host == "" {
  214. return false
  215. }
  216. return strings.EqualFold(u.Host, effectiveHost(r))
  217. }
  218. // effectiveHost devuelve el host al que el cliente cree estar llamando:
  219. // X-Forwarded-Host (si TRUST_PROXY) o r.Host. Sin TRUST_PROXY, un header
  220. // falseado no puede eludir la comprobación.
  221. func effectiveHost(r *http.Request) string {
  222. if trustProxy {
  223. if xfh := r.Header.Get("X-Forwarded-Host"); xfh != "" {
  224. if first := strings.TrimSpace(strings.Split(xfh, ",")[0]); first != "" {
  225. return first
  226. }
  227. }
  228. }
  229. return r.Host
  230. }