middleware.go 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  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" || isAgentReportPath(p) ||
  74. (p == "/api/config-backup" && r.Method == http.MethodPost)
  75. }
  76. // isAnonymousPath indica si la ruta no requiere sesión (auth propia en el handler).
  77. func isAnonymousPath(path string) bool {
  78. if path == "/api/health" || path == "/api/auth/login" ||
  79. path == "/api/ingest/agent" || path == "/api/agents/pair" ||
  80. path == "/api/agents/pair/hello" || // FORK: proves the served key; no secret in or out
  81. path == "/api/agents/executor-token" ||
  82. isAgentReportPath(path) {
  83. return true
  84. }
  85. return false
  86. }
  87. // RequireAuth es middleware global: todo /api/* exige sesión salvo
  88. // /api/health, /api/auth/login, /api/ingest/agent (auth Bearer por token
  89. // de equipo), /api/agents/pair (pairing token de un solo uso, Fase 9 R3),
  90. // /api/agents/{slug}/binary (auth Bearer por token de agente,
  91. // Fase 6.2), /api/agents/{slug}/stream (SSE bidireccional, Fase 7.3),
  92. // /api/agents/{slug}/apply-result, /api/agents/{slug}/upgrade-result,
  93. // /api/agents/{slug}/upgrade-progress, /api/agents/{slug}/firmware-progress y
  94. // /api/agents/{slug}/firmware-result (reportes del agente, auth Bearer).
  95. // POST /api/config-backup (issue #340): recibe snapshots UCI desde NetGrip;
  96. // auth Bearer por token de agente validado en el handler.
  97. // Acepta Bearer tokens de API (#330) como alternativa a la cookie de sesión.
  98. // Fallo → 401 {error:'unauthorized'}.
  99. func RequireAuth(d *db.DB, secret string, tv TokenValidator, next http.Handler) http.Handler {
  100. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  101. path := r.URL.Path
  102. if !strings.HasPrefix(path, "/api/") || isAnonymousPath(path) ||
  103. (path == "/api/config-backup" && r.Method == http.MethodPost) {
  104. next.ServeHTTP(w, r)
  105. return
  106. }
  107. if tv != nil {
  108. if raw := bearerToken(r); raw != "" {
  109. if user, scope := tv.ValidateBearer(raw); user != nil {
  110. if !scopeAllowsMethod(scope, r.Method) {
  111. WriteError(w, http.StatusForbidden, "insufficient_scope")
  112. return
  113. }
  114. ctx := context.WithValue(r.Context(), ctxUser, user)
  115. ctx = context.WithValue(ctx, ctxAPIToken, scope)
  116. next.ServeHTTP(w, r.WithContext(ctx))
  117. return
  118. }
  119. }
  120. }
  121. sess := SessionUserFromRequest(d, secret, r)
  122. if sess == nil {
  123. WriteError(w, http.StatusUnauthorized, "unauthorized")
  124. return
  125. }
  126. ctx := context.WithValue(r.Context(), ctxUser, sess.User)
  127. ctx = context.WithValue(ctx, ctxSessionID, sess.SessionID)
  128. next.ServeHTTP(w, r.WithContext(ctx))
  129. })
  130. }
  131. func bearerToken(r *http.Request) string {
  132. v := r.Header.Get("Authorization")
  133. if v == "" {
  134. return ""
  135. }
  136. if !strings.HasPrefix(v, "Bearer ") {
  137. return ""
  138. }
  139. return strings.TrimPrefix(v, "Bearer ")
  140. }
  141. // scopeAllowsMethod aplica el contrato de los scopes al método HTTP. Un token
  142. // read es de solo lectura: GET, HEAD y OPTIONS. write y admin pueden mutar,
  143. // pero solo admin supera además RequireAdmin.
  144. func scopeAllowsMethod(scope, method string) bool {
  145. switch scope {
  146. case ScopeWrite, ScopeAdmin:
  147. return true
  148. case ScopeRead:
  149. switch method {
  150. case http.MethodGet, http.MethodHead, http.MethodOptions:
  151. return true
  152. }
  153. }
  154. return false
  155. }
  156. // RequireAdmin exige role === 'admin' (tras RequireAuth) → 403 {error:'forbidden'}.
  157. // Con un API token exige además scope admin: un token read o write emitido por
  158. // un admin no hereda el rol y no entra en rutas de administración.
  159. func RequireAdmin(next http.Handler) http.Handler {
  160. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  161. user := UserFromContext(r.Context())
  162. if user == nil || user.Role != "admin" {
  163. WriteError(w, http.StatusForbidden, "forbidden")
  164. return
  165. }
  166. if scope := APITokenFromContext(r.Context()); scope != "" && scope != ScopeAdmin {
  167. WriteError(w, http.StatusForbidden, "insufficient_scope")
  168. return
  169. }
  170. next.ServeHTTP(w, r)
  171. })
  172. }
  173. // RequireSameOrigin es la defensa CSRF (issue #213). SameSite=Lax cubre el
  174. // envío de cookies cross-site de fetch/XHR, pero no hay defensa en
  175. // profundidad si la app se sirve desde otro origen o un navegador sin
  176. // SameSite. En mutaciones (POST/PUT/DELETE) se valida el header Origin contra
  177. // el host efectivo de la petición (X-Forwarded-Host si TRUST_PROXY, si no
  178. // r.Host). Un Origin ausente (cliente no-navegador: agente, curl, CLI) se
  179. // deja pasar; si el navegador envía Sec-Fetch-Site: cross-site sin Origin, se
  180. // rechaza igualmente. Un Origin que no casa → 403 {error:'cross_origin'}.
  181. func RequireSameOrigin(next http.Handler) http.Handler {
  182. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  183. if r.Method == http.MethodPost || r.Method == http.MethodPut || r.Method == http.MethodDelete {
  184. if !originAllowed(r) {
  185. WriteError(w, http.StatusForbidden, "cross_origin")
  186. return
  187. }
  188. }
  189. next.ServeHTTP(w, r)
  190. })
  191. }
  192. // originAllowed valida el header Origin (si viene) contra el host efectivo.
  193. func originAllowed(r *http.Request) bool {
  194. origin := r.Header.Get("Origin")
  195. if origin == "" {
  196. if sf := r.Header.Get("Sec-Fetch-Site"); sf != "" {
  197. return sf != "cross-site"
  198. }
  199. return true
  200. }
  201. u, err := url.Parse(origin)
  202. if err != nil {
  203. return false
  204. }
  205. // Origin "null" (iframe sandbox / redirect) no tiene host → no casa.
  206. if u.Host == "" {
  207. return false
  208. }
  209. return strings.EqualFold(u.Host, effectiveHost(r))
  210. }
  211. // effectiveHost devuelve el host al que el cliente cree estar llamando:
  212. // X-Forwarded-Host (si TRUST_PROXY) o r.Host. Sin TRUST_PROXY, un header
  213. // falseado no puede eludir la comprobación.
  214. func effectiveHost(r *http.Request) string {
  215. if trustProxy {
  216. if xfh := r.Header.Get("X-Forwarded-Host"); xfh != "" {
  217. if first := strings.TrimSpace(strings.Split(xfh, ",")[0]); first != "" {
  218. return first
  219. }
  220. }
  221. }
  222. return r.Host
  223. }