auth_test.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  1. package auth
  2. import (
  3. "net/http"
  4. "net/http/httptest"
  5. "strings"
  6. "testing"
  7. "golang.org/x/crypto/bcrypt"
  8. "github.com/gnacho/netpulse/server-go/internal/config"
  9. "github.com/gnacho/netpulse/server-go/internal/db"
  10. )
  11. func testDB(t *testing.T) *db.DB {
  12. t.Helper()
  13. d, err := db.Open(t.TempDir())
  14. if err != nil {
  15. t.Fatalf("open db: %v", err)
  16. }
  17. t.Cleanup(func() { d.Close() })
  18. return d
  19. }
  20. func testCfg() *config.Config {
  21. return &config.Config{AuthUser: "admin", AuthPass: "test123456", CookieSecure: "auto"}
  22. }
  23. func TestSignVerifyRoundtrip(t *testing.T) {
  24. secret := strings.Repeat("ab", 32)
  25. id := "f47ac10b-58cc-4372-a567-0e02b2c3d479"
  26. signed := SignSessionID(secret, id)
  27. if got := VerifySessionCookie(secret, signed); got != id {
  28. t.Fatalf("roundtrip: got %q, want %q", got, id)
  29. }
  30. // El id puede contener puntos: el split es por el ÚLTIMO punto.
  31. weird := "id.con.puntos"
  32. if got := VerifySessionCookie(secret, SignSessionID(secret, weird)); got != weird {
  33. t.Fatalf("split último punto: got %q", got)
  34. }
  35. }
  36. func TestVerifyRejects(t *testing.T) {
  37. secret := strings.Repeat("ab", 32)
  38. id := "f47ac10b-58cc-4372-a567-0e02b2c3d479"
  39. signed := SignSessionID(secret, id)
  40. cases := map[string]string{
  41. "vacío": "",
  42. "sin punto": "abcdef",
  43. "punto al inicio": ".abcdef",
  44. "firma alterada": signed[:len(signed)-2] + "00",
  45. "otro secret": SignSessionID(strings.Repeat("cd", 32), id),
  46. "misma longitud, distinta firma": tamperedSignature(secret, id),
  47. }
  48. for name, v := range cases {
  49. if got := VerifySessionCookie(secret, v); got != "" {
  50. t.Errorf("%s: esperaba rechazo, got %q", name, got)
  51. }
  52. }
  53. }
  54. // tamperedSignature cambia el último carácter hex de la firma (misma longitud).
  55. func tamperedSignature(secret, id string) string {
  56. signed := SignSessionID(secret, id)
  57. last := signed[len(signed)-1]
  58. repl := byte('0')
  59. if last == '0' {
  60. repl = '1'
  61. }
  62. return signed[:len(signed)-1] + string(repl)
  63. }
  64. func TestCookieExtraction(t *testing.T) {
  65. d := testDB(t)
  66. secret, err := EnsureSessionSecret(d, testCfg())
  67. if err != nil {
  68. t.Fatal(err)
  69. }
  70. if len(secret) != 64 {
  71. t.Fatalf("secret autogenerado debe ser 64 hex, got %d", len(secret))
  72. }
  73. // Persistido en kv: segunda llamada devuelve el mismo.
  74. again, _ := EnsureSessionSecret(d, testCfg())
  75. if again != secret {
  76. t.Fatal("el secret debe persistirse en kv")
  77. }
  78. if err := EnsureUsers(d, testCfg()); err != nil {
  79. t.Fatal(err)
  80. }
  81. admin := GetUserByName(d, "admin")
  82. if admin == nil {
  83. t.Fatal("seed admin")
  84. }
  85. id := CreateSession(d, "TestAgent/1.0", admin.ID)
  86. signed := SignSessionID(secret, id)
  87. r := httptest.NewRequest("GET", "/api/auth/me", nil)
  88. r.Header.Set("Cookie", "other=1; session="+signed+"; theme=dark")
  89. su := SessionUserFromRequest(d, secret, r)
  90. if su == nil {
  91. t.Fatal("cookie válida debe autenticar")
  92. }
  93. if su.SessionID != id {
  94. t.Fatalf("sessionId: got %q want %q", su.SessionID, id)
  95. }
  96. // Primera ocurrencia gana (regex del JS).
  97. r2 := httptest.NewRequest("GET", "/x", nil)
  98. r2.Header.Set("Cookie", "session="+signed+"; session=garbage.garbage")
  99. if SessionIDFromRequest(d, secret, r2) != id {
  100. t.Fatal("debe usar la primera ocurrencia de session=")
  101. }
  102. }
  103. func TestSessionExpiry(t *testing.T) {
  104. d := testDB(t)
  105. id := CreateSession(d, "", 1)
  106. // Expira la sesión manualmente.
  107. _, _ = d.Exec("UPDATE sessions SET expires_at = ? WHERE id = ?", db.NowMS()-1000, id)
  108. if GetSession(d, id) != nil {
  109. t.Fatal("sesión expirada debe ser inválida")
  110. }
  111. // Y se borra de la tabla.
  112. var n int
  113. _ = d.QueryRow("SELECT COUNT(*) FROM sessions WHERE id = ?", id).Scan(&n)
  114. if n != 0 {
  115. t.Fatal("sesión expirada debe borrarse al leerla")
  116. }
  117. }
  118. func TestSessionWithoutUserIDDoesNotAuthenticate(t *testing.T) {
  119. d := testDB(t)
  120. secret, _ := EnsureSessionSecret(d, testCfg())
  121. // Sesión legacy sin user_id.
  122. _, _ = d.Exec("INSERT INTO sessions (id, created_at, expires_at, ua, user_id) VALUES ('legacy', ?, ?, '', NULL)",
  123. db.NowMS(), db.NowMS()+SessionTTLMS)
  124. r := httptest.NewRequest("GET", "/api/overview", nil)
  125. r.Header.Set("Cookie", "session="+SignSessionID(secret, "legacy"))
  126. if SessionUserFromRequest(d, secret, r) != nil {
  127. t.Fatal("sesión sin user_id NO debe autenticar")
  128. }
  129. }
  130. func TestRateLimitFifthFailArmsLock(t *testing.T) {
  131. // El test simula la IP del cliente vía X-Forwarded-For; en producción
  132. // solo se confía con TRUST_PROXY (auditoría #1).
  133. SetTrustProxy(true)
  134. t.Cleanup(func() { SetTrustProxy(false) })
  135. d := testDB(t)
  136. newReq := func() *http.Request {
  137. r := httptest.NewRequest("POST", "/api/auth/login", nil)
  138. r.Header.Set("X-Forwarded-For", "10.9.9.9, 10.0.0.1")
  139. return r
  140. }
  141. for i := 1; i <= 5; i++ {
  142. if limited, _ := LoginRateLimited(d, newReq()); limited {
  143. t.Fatalf("fallo %d: no debe estar limitado aún", i)
  144. }
  145. RegisterLoginFail(d, newReq())
  146. }
  147. limited, retry := LoginRateLimited(d, newReq())
  148. if !limited {
  149. t.Fatal("tras el 5º fallo la IP debe estar bloqueada")
  150. }
  151. if retry <= 0 || retry > 300 {
  152. t.Fatalf("retryAfterSec debe estar en (0, 300], got %d", retry)
  153. }
  154. // Persistencia en SQLite.
  155. var attempts int
  156. var lockedUntil int64
  157. if err := d.QueryRow("SELECT attempts, locked_until FROM login_attempts WHERE ip = '10.9.9.9'").
  158. Scan(&attempts, &lockedUntil); err != nil {
  159. t.Fatal(err)
  160. }
  161. if attempts < 5 || lockedUntil <= db.NowMS() {
  162. t.Fatalf("fila esperada attempts>=5 y locked_until futuro: %d %d", attempts, lockedUntil)
  163. }
  164. // LoginOk limpia la fila.
  165. LoginOk(d, newReq())
  166. if limited, _ := LoginRateLimited(d, newReq()); limited {
  167. t.Fatal("LoginOk debe limpiar el bloqueo")
  168. }
  169. }
  170. func TestLoginAttemptsDecayTrasLockExpired(t *testing.T) {
  171. // Issue #211: tras expirar el lockout (5 min), un fallo suelto ya NO
  172. // rearma el bloqueo — la cuenta decae a 1.
  173. SetTrustProxy(true)
  174. t.Cleanup(func() { SetTrustProxy(false) })
  175. d := testDB(t)
  176. newReq := func() *http.Request {
  177. r := httptest.NewRequest("POST", "/api/auth/login", nil)
  178. r.Header.Set("X-Forwarded-For", "10.9.9.9, 10.0.0.1")
  179. return r
  180. }
  181. for i := 0; i < 5; i++ {
  182. RegisterLoginFail(d, newReq())
  183. }
  184. if limited, _ := LoginRateLimited(d, newReq()); !limited {
  185. t.Fatal("tras 5 fallos debe estar bloqueado")
  186. }
  187. // El lockout expira.
  188. _, _ = d.Exec("UPDATE login_attempts SET locked_until = ? WHERE ip = '10.9.9.9'", db.NowMS()-1)
  189. // Un fallo suelto tras la expiración no rearma el lockout.
  190. RegisterLoginFail(d, newReq())
  191. if limited, _ := LoginRateLimited(d, newReq()); limited {
  192. t.Fatal("un fallo tras expirar el lockout no debe rearmarlo")
  193. }
  194. var attempts int
  195. var lockedUntil int64
  196. if err := d.QueryRow("SELECT attempts, locked_until FROM login_attempts WHERE ip = '10.9.9.9'").
  197. Scan(&attempts, &lockedUntil); err != nil {
  198. t.Fatal(err)
  199. }
  200. if attempts != 1 || lockedUntil != 0 {
  201. t.Fatalf("tras el decay esperaba attempts=1 locked_until=0, got %d %d", attempts, lockedUntil)
  202. }
  203. }
  204. func TestLoginAttemptsRearmanTrasBurstNuevo(t *testing.T) {
  205. // Issue #211: tras el decay, una ráfaga nueva de 5 fallos vuelve a
  206. // armar el bloqueo (no se queda desarmado para siempre).
  207. SetTrustProxy(true)
  208. t.Cleanup(func() { SetTrustProxy(false) })
  209. d := testDB(t)
  210. newReq := func() *http.Request {
  211. r := httptest.NewRequest("POST", "/api/auth/login", nil)
  212. r.Header.Set("X-Forwarded-For", "10.9.9.9, 10.0.0.1")
  213. return r
  214. }
  215. for i := 0; i < 5; i++ {
  216. RegisterLoginFail(d, newReq())
  217. }
  218. _, _ = d.Exec("UPDATE login_attempts SET locked_until = ? WHERE ip = '10.9.9.9'", db.NowMS()-1)
  219. // Decay: primer fallo tras la expiración resetea a 1.
  220. RegisterLoginFail(d, newReq())
  221. if limited, _ := LoginRateLimited(d, newReq()); limited {
  222. t.Fatal("el primer fallo tras expirar no debe rearmar")
  223. }
  224. // Ráfaga nueva completa: 5 fallos seguidos vuelven a armar el lockout.
  225. for i := 0; i < 5; i++ {
  226. RegisterLoginFail(d, newReq())
  227. }
  228. if limited, _ := LoginRateLimited(d, newReq()); !limited {
  229. t.Fatal("una ráfaga nueva de 5 fallos debe rearmar el lockout")
  230. }
  231. }
  232. func TestRequireSameOrigin(t *testing.T) {
  233. // Issue #213: mutaciones (POST/PUT/DELETE) validan Origin contra el host.
  234. SetTrustProxy(true)
  235. t.Cleanup(func() { SetTrustProxy(false) })
  236. next := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusNoContent) })
  237. h := RequireSameOrigin(next)
  238. // POST sin Origin (cliente no-navegador) → pasa.
  239. rec := httptest.NewRecorder()
  240. h.ServeHTTP(rec, httptest.NewRequest("POST", "http://192.168.1.226:3000/api/x", nil))
  241. if rec.Code != http.StatusNoContent {
  242. t.Fatalf("POST sin Origin debe pasar, got %d", rec.Code)
  243. }
  244. // POST con Origin == Host → pasa.
  245. req := httptest.NewRequest("POST", "http://192.168.1.226:3000/api/x", nil)
  246. req.Header.Set("Origin", "http://192.168.1.226:3000")
  247. rec2 := httptest.NewRecorder()
  248. h.ServeHTTP(rec2, req)
  249. if rec2.Code != http.StatusNoContent {
  250. t.Fatalf("POST Origin==Host debe pasar, got %d", rec2.Code)
  251. }
  252. // POST con Origin distinto → 403 cross_origin.
  253. req2 := httptest.NewRequest("POST", "http://192.168.1.226:3000/api/x", nil)
  254. req2.Header.Set("Origin", "https://evil.example")
  255. rec3 := httptest.NewRecorder()
  256. h.ServeHTTP(rec3, req2)
  257. if rec3.Code != http.StatusForbidden {
  258. t.Fatalf("POST Origin distinto debe dar 403, got %d", rec3.Code)
  259. }
  260. // POST con Origin null (iframe sandbox) → 403.
  261. req3 := httptest.NewRequest("POST", "http://192.168.1.226:3000/api/x", nil)
  262. req3.Header.Set("Origin", "null")
  263. rec4 := httptest.NewRecorder()
  264. h.ServeHTTP(rec4, req3)
  265. if rec4.Code != http.StatusForbidden {
  266. t.Fatalf("POST Origin null debe dar 403, got %d", rec4.Code)
  267. }
  268. // GET no se valida (no es mutación).
  269. req4 := httptest.NewRequest("GET", "http://192.168.1.226:3000/api/x", nil)
  270. req4.Header.Set("Origin", "https://evil.example")
  271. rec5 := httptest.NewRecorder()
  272. h.ServeHTTP(rec5, req4)
  273. if rec5.Code != http.StatusNoContent {
  274. t.Fatalf("GET con Origin distinto no debe validarse, got %d", rec5.Code)
  275. }
  276. // Sec-Fetch-Site: cross-site sin Origin → 403.
  277. req5 := httptest.NewRequest("POST", "http://192.168.1.226:3000/api/x", nil)
  278. req5.Header.Set("Sec-Fetch-Site", "cross-site")
  279. rec6 := httptest.NewRecorder()
  280. h.ServeHTTP(rec6, req5)
  281. if rec6.Code != http.StatusForbidden {
  282. t.Fatalf("POST Sec-Fetch-Site=cross-site debe dar 403, got %d", rec6.Code)
  283. }
  284. }
  285. func TestEffectiveHostConfiaEnXFH(t *testing.T) {
  286. // Con TRUST_PROXY, X-Forwarded-Host (primer valor) es el host efectivo.
  287. SetTrustProxy(true)
  288. t.Cleanup(func() { SetTrustProxy(false) })
  289. r := httptest.NewRequest("POST", "http://internal:3000/api/x", nil)
  290. r.Header.Set("X-Forwarded-Host", "netpulse.example.com, internal:3000")
  291. if got := effectiveHost(r); got != "netpulse.example.com" {
  292. t.Fatalf("effectiveHost con XFH: %q", got)
  293. }
  294. // Sin TRUST_PROXY, XFH se ignora.
  295. SetTrustProxy(false)
  296. if got := effectiveHost(r); got != "internal:3000" {
  297. t.Fatalf("effectiveHost sin TRUST_PROXY: %q", got)
  298. }
  299. }
  300. func TestBuildSessionCookieFlags(t *testing.T) {
  301. // El caso X-Forwarded-Proto=https requiere TRUST_PROXY (auditoría #1).
  302. SetTrustProxy(true)
  303. t.Cleanup(func() { SetTrustProxy(false) })
  304. cfg := &config.Config{CookieSecure: "auto"}
  305. r := httptest.NewRequest("POST", "http://x/api/auth/login", nil)
  306. c := BuildSessionCookie(cfg, r, "id.sig", 2592000)
  307. want := "session=id.sig; Path=/; HttpOnly; SameSite=Lax; Max-Age=2592000"
  308. if c != want {
  309. t.Fatalf("cookie http:\n got %q\nwant %q", c, want)
  310. }
  311. // X-Forwarded-Proto https → Secure (auto).
  312. r2 := httptest.NewRequest("POST", "http://x/api/auth/login", nil)
  313. r2.Header.Set("X-Forwarded-Proto", "https, http")
  314. if got := BuildSessionCookie(cfg, r2, "id.sig", 2592000); !strings.HasSuffix(got, "; Secure") {
  315. t.Fatalf("auto + X-Forwarded-Proto=https debe añadir Secure: %q", got)
  316. }
  317. // always / never.
  318. cfgAlways := &config.Config{CookieSecure: "always"}
  319. if got := BuildSessionCookie(cfgAlways, r, "i.s", 1); !strings.HasSuffix(got, "; Secure") {
  320. t.Fatal("always debe forzar Secure")
  321. }
  322. cfgNever := &config.Config{CookieSecure: "never"}
  323. r3 := httptest.NewRequest("POST", "https://x/", nil)
  324. if got := BuildSessionCookie(cfgNever, r3, "i.s", 1); strings.Contains(got, "Secure") {
  325. t.Fatal("never debe omitir Secure incluso en https")
  326. }
  327. }
  328. func TestClientIPSinTrustProxyIgnoraXFF(t *testing.T) {
  329. // Auditoría #1: sin TRUST_PROXY, X-Forwarded-For se IGNORA — la IP del
  330. // cliente es la del socket, no se puede falsear para evadir rate-limit.
  331. SetTrustProxy(false)
  332. t.Cleanup(func() { SetTrustProxy(false) })
  333. r := httptest.NewRequest("POST", "/api/auth/login", nil)
  334. r.RemoteAddr = "192.168.1.55:50000"
  335. r.Header.Set("X-Forwarded-For", "10.9.9.9")
  336. if got := ClientIP(r); got != "192.168.1.55" {
  337. t.Fatalf("sin TRUST_PROXY debe usar la IP del socket: %q", got)
  338. }
  339. // Con TRUST_PROXY, XFF es la IP del cliente real (detrás de proxy).
  340. SetTrustProxy(true)
  341. if got := ClientIP(r); got != "10.9.9.9" {
  342. t.Fatalf("con TRUST_PROXY debe usar XFF: %q", got)
  343. }
  344. }
  345. func TestIsSecureRequestSinTrustProxyIgnoraXFP(t *testing.T) {
  346. // Auditoría #1: sin TRUST_PROXY, X-Forwarded-Proto se IGNORA (un cliente
  347. // de la LAN no puede forzar la cookie Secure).
  348. SetTrustProxy(false)
  349. t.Cleanup(func() { SetTrustProxy(false) })
  350. r := httptest.NewRequest("POST", "http://x/", nil)
  351. r.Header.Set("X-Forwarded-Proto", "https")
  352. if IsSecureRequest(r) {
  353. t.Fatal("sin TRUST_PROXY, XFP=https no debe considerarse seguro")
  354. }
  355. SetTrustProxy(true)
  356. if !IsSecureRequest(r) {
  357. t.Fatal("con TRUST_PROXY, XFP=https debe considerarse seguro")
  358. }
  359. }
  360. func TestLoginDummyHashValido(t *testing.T) {
  361. // El dummy de timing del login debe ser un hash bcrypt VÁLIDO: si no lo
  362. // es (p.ej. caracteres ilegales como '_'), CompareHashAndPassword falla
  363. // en microsegundos y el login se convierte en un oráculo de enumeración
  364. // de usuarios (issue #209).
  365. err := bcrypt.CompareHashAndPassword([]byte(dummyPasswordHash), []byte("cualquier-password"))
  366. if err == nil {
  367. t.Fatal("comparar contra el dummy con una password cualquiera no debe acertar")
  368. }
  369. if strings.Contains(err.Error(), "illegal base64 data") {
  370. t.Fatalf("dummyPasswordHash no es un hash bcrypt válido: %v", err)
  371. }
  372. }