auth_test.go 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. package auth
  2. import (
  3. "net/http"
  4. "net/http/httptest"
  5. "strings"
  6. "testing"
  7. "github.com/gnacho/netpulse/server-go/internal/config"
  8. "github.com/gnacho/netpulse/server-go/internal/db"
  9. )
  10. func testDB(t *testing.T) *db.DB {
  11. t.Helper()
  12. d, err := db.Open(t.TempDir())
  13. if err != nil {
  14. t.Fatalf("open db: %v", err)
  15. }
  16. t.Cleanup(func() { d.Close() })
  17. return d
  18. }
  19. func testCfg() *config.Config {
  20. return &config.Config{AuthUser: "admin", AuthPass: "test1234", CookieSecure: "auto"}
  21. }
  22. func TestSignVerifyRoundtrip(t *testing.T) {
  23. secret := strings.Repeat("ab", 32)
  24. id := "f47ac10b-58cc-4372-a567-0e02b2c3d479"
  25. signed := SignSessionID(secret, id)
  26. if got := VerifySessionCookie(secret, signed); got != id {
  27. t.Fatalf("roundtrip: got %q, want %q", got, id)
  28. }
  29. // El id puede contener puntos: el split es por el ÚLTIMO punto.
  30. weird := "id.con.puntos"
  31. if got := VerifySessionCookie(secret, SignSessionID(secret, weird)); got != weird {
  32. t.Fatalf("split último punto: got %q", got)
  33. }
  34. }
  35. func TestVerifyRejects(t *testing.T) {
  36. secret := strings.Repeat("ab", 32)
  37. id := "f47ac10b-58cc-4372-a567-0e02b2c3d479"
  38. signed := SignSessionID(secret, id)
  39. cases := map[string]string{
  40. "vacío": "",
  41. "sin punto": "abcdef",
  42. "punto al inicio": ".abcdef",
  43. "firma alterada": signed[:len(signed)-2] + "00",
  44. "otro secret": SignSessionID(strings.Repeat("cd", 32), id),
  45. "misma longitud, distinta firma": tamperedSignature(secret, id),
  46. }
  47. for name, v := range cases {
  48. if got := VerifySessionCookie(secret, v); got != "" {
  49. t.Errorf("%s: esperaba rechazo, got %q", name, got)
  50. }
  51. }
  52. }
  53. // tamperedSignature cambia el último carácter hex de la firma (misma longitud).
  54. func tamperedSignature(secret, id string) string {
  55. signed := SignSessionID(secret, id)
  56. last := signed[len(signed)-1]
  57. repl := byte('0')
  58. if last == '0' {
  59. repl = '1'
  60. }
  61. return signed[:len(signed)-1] + string(repl)
  62. }
  63. func TestCookieExtraction(t *testing.T) {
  64. d := testDB(t)
  65. secret, err := EnsureSessionSecret(d, testCfg())
  66. if err != nil {
  67. t.Fatal(err)
  68. }
  69. if len(secret) != 64 {
  70. t.Fatalf("secret autogenerado debe ser 64 hex, got %d", len(secret))
  71. }
  72. // Persistido en kv: segunda llamada devuelve el mismo.
  73. again, _ := EnsureSessionSecret(d, testCfg())
  74. if again != secret {
  75. t.Fatal("el secret debe persistirse en kv")
  76. }
  77. if err := EnsureUsers(d, testCfg()); err != nil {
  78. t.Fatal(err)
  79. }
  80. admin := GetUserByName(d, "admin")
  81. if admin == nil {
  82. t.Fatal("seed admin")
  83. }
  84. id := CreateSession(d, "TestAgent/1.0", admin.ID)
  85. signed := SignSessionID(secret, id)
  86. r := httptest.NewRequest("GET", "/api/auth/me", nil)
  87. r.Header.Set("Cookie", "other=1; session="+signed+"; theme=dark")
  88. su := SessionUserFromRequest(d, secret, r)
  89. if su == nil {
  90. t.Fatal("cookie válida debe autenticar")
  91. }
  92. if su.SessionID != id {
  93. t.Fatalf("sessionId: got %q want %q", su.SessionID, id)
  94. }
  95. // Primera ocurrencia gana (regex del JS).
  96. r2 := httptest.NewRequest("GET", "/x", nil)
  97. r2.Header.Set("Cookie", "session="+signed+"; session=garbage.garbage")
  98. if SessionIDFromRequest(d, secret, r2) != id {
  99. t.Fatal("debe usar la primera ocurrencia de session=")
  100. }
  101. }
  102. func TestSessionExpiry(t *testing.T) {
  103. d := testDB(t)
  104. id := CreateSession(d, "", 1)
  105. // Expira la sesión manualmente.
  106. _, _ = d.Exec("UPDATE sessions SET expires_at = ? WHERE id = ?", db.NowMS()-1000, id)
  107. if GetSession(d, id) != nil {
  108. t.Fatal("sesión expirada debe ser inválida")
  109. }
  110. // Y se borra de la tabla.
  111. var n int
  112. _ = d.QueryRow("SELECT COUNT(*) FROM sessions WHERE id = ?", id).Scan(&n)
  113. if n != 0 {
  114. t.Fatal("sesión expirada debe borrarse al leerla")
  115. }
  116. }
  117. func TestSessionWithoutUserIDDoesNotAuthenticate(t *testing.T) {
  118. d := testDB(t)
  119. secret, _ := EnsureSessionSecret(d, testCfg())
  120. // Sesión legacy sin user_id.
  121. _, _ = d.Exec("INSERT INTO sessions (id, created_at, expires_at, ua, user_id) VALUES ('legacy', ?, ?, '', NULL)",
  122. db.NowMS(), db.NowMS()+SessionTTLMS)
  123. r := httptest.NewRequest("GET", "/api/overview", nil)
  124. r.Header.Set("Cookie", "session="+SignSessionID(secret, "legacy"))
  125. if SessionUserFromRequest(d, secret, r) != nil {
  126. t.Fatal("sesión sin user_id NO debe autenticar")
  127. }
  128. }
  129. func TestRateLimitFifthFailArmsLock(t *testing.T) {
  130. d := testDB(t)
  131. newReq := func() *http.Request {
  132. r := httptest.NewRequest("POST", "/api/auth/login", nil)
  133. r.Header.Set("X-Forwarded-For", "10.9.9.9, 10.0.0.1")
  134. return r
  135. }
  136. for i := 1; i <= 5; i++ {
  137. if limited, _ := LoginRateLimited(d, newReq()); limited {
  138. t.Fatalf("fallo %d: no debe estar limitado aún", i)
  139. }
  140. RegisterLoginFail(d, newReq())
  141. }
  142. limited, retry := LoginRateLimited(d, newReq())
  143. if !limited {
  144. t.Fatal("tras el 5º fallo la IP debe estar bloqueada")
  145. }
  146. if retry <= 0 || retry > 300 {
  147. t.Fatalf("retryAfterSec debe estar en (0, 300], got %d", retry)
  148. }
  149. // Persistencia en SQLite.
  150. var attempts int
  151. var lockedUntil int64
  152. if err := d.QueryRow("SELECT attempts, locked_until FROM login_attempts WHERE ip = '10.9.9.9'").
  153. Scan(&attempts, &lockedUntil); err != nil {
  154. t.Fatal(err)
  155. }
  156. if attempts < 5 || lockedUntil <= db.NowMS() {
  157. t.Fatalf("fila esperada attempts>=5 y locked_until futuro: %d %d", attempts, lockedUntil)
  158. }
  159. // LoginOk limpia la fila.
  160. LoginOk(d, newReq())
  161. if limited, _ := LoginRateLimited(d, newReq()); limited {
  162. t.Fatal("LoginOk debe limpiar el bloqueo")
  163. }
  164. }
  165. func TestBuildSessionCookieFlags(t *testing.T) {
  166. cfg := &config.Config{CookieSecure: "auto"}
  167. r := httptest.NewRequest("POST", "http://x/api/auth/login", nil)
  168. c := BuildSessionCookie(cfg, r, "id.sig", 2592000)
  169. want := "session=id.sig; Path=/; HttpOnly; SameSite=Lax; Max-Age=2592000"
  170. if c != want {
  171. t.Fatalf("cookie http:\n got %q\nwant %q", c, want)
  172. }
  173. // X-Forwarded-Proto https → Secure (auto).
  174. r2 := httptest.NewRequest("POST", "http://x/api/auth/login", nil)
  175. r2.Header.Set("X-Forwarded-Proto", "https, http")
  176. if got := BuildSessionCookie(cfg, r2, "id.sig", 2592000); !strings.HasSuffix(got, "; Secure") {
  177. t.Fatalf("auto + X-Forwarded-Proto=https debe añadir Secure: %q", got)
  178. }
  179. // always / never.
  180. cfgAlways := &config.Config{CookieSecure: "always"}
  181. if got := BuildSessionCookie(cfgAlways, r, "i.s", 1); !strings.HasSuffix(got, "; Secure") {
  182. t.Fatal("always debe forzar Secure")
  183. }
  184. cfgNever := &config.Config{CookieSecure: "never"}
  185. r3 := httptest.NewRequest("POST", "https://x/", nil)
  186. if got := BuildSessionCookie(cfgNever, r3, "i.s", 1); strings.Contains(got, "Secure") {
  187. t.Fatal("never debe omitir Secure incluso en https")
  188. }
  189. }