auth.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  1. // Package auth — autenticación multiusuario (paridad con server/src/auth.js):
  2. // - Cookie `session` = `id.hmac` (UUID v4 . hex(HMAC-SHA256)), httpOnly,
  3. // SameSite=Lax, 30 días; Secure según COOKIE_SECURE / X-Forwarded-Proto.
  4. // - Verificación: split por el ÚLTIMO punto, comparación timing-safe.
  5. // - Secret HMAC: SESSION_SECRET o autogenerado persistido en kv.
  6. // - Sesiones en SQLite (30 d), rotación tras login.
  7. // - Rate-limit persistente (login_attempts): bloqueo 5 min armado cuando
  8. // attempts previos >= 4 (5º fallo), 429 con retryAfterSec.
  9. // - bcrypt cost 10 (hashes bcryptjs $2a/$2b verificables con x/crypto).
  10. package auth
  11. import (
  12. "crypto/hmac"
  13. "crypto/rand"
  14. "crypto/sha256"
  15. "database/sql"
  16. "encoding/hex"
  17. "fmt"
  18. "log"
  19. "net"
  20. "net/http"
  21. "regexp"
  22. "strings"
  23. "golang.org/x/crypto/bcrypt"
  24. "github.com/gnacho/netpulse/server-go/internal/config"
  25. "github.com/gnacho/netpulse/server-go/internal/db"
  26. )
  27. const (
  28. // SessionCookie es el nombre de la cookie de sesión.
  29. SessionCookie = "session"
  30. // SessionTTLMS = 30 días en ms (Max-Age=2592000).
  31. SessionTTLMS = 30 * 24 * 60 * 60 * 1000
  32. // LockMS = 5 minutos en ms.
  33. LockMS = 5 * 60 * 1000
  34. )
  35. // ---------------------------------------------------------------------------
  36. // Usuarios
  37. // ---------------------------------------------------------------------------
  38. // User fila pública de users (sin pass_hash).
  39. type User struct {
  40. ID int64
  41. Username string
  42. Role string
  43. }
  44. // EnsureUsers crea el admin inicial (AUTH_USER/AUTH_PASS) si users está vacía.
  45. func EnsureUsers(d *db.DB, cfg *config.Config) error {
  46. var count int
  47. if err := d.QueryRow("SELECT COUNT(*) FROM users").Scan(&count); err != nil {
  48. return err
  49. }
  50. if count > 0 {
  51. return nil
  52. }
  53. hash, err := bcrypt.GenerateFromPassword([]byte(cfg.AuthPass), 10)
  54. if err != nil {
  55. return err
  56. }
  57. if _, err := d.Exec(
  58. "INSERT INTO users (username, pass_hash, role, created_at) VALUES (?, ?, 'admin', ?)",
  59. cfg.AuthUser, string(hash), db.NowMS(),
  60. ); err != nil {
  61. return err
  62. }
  63. log.Printf("[netpulse] usuario admin inicial creado: %s", cfg.AuthUser)
  64. return nil
  65. }
  66. type userRow struct {
  67. ID int64
  68. Username string
  69. PassHash string
  70. Role string
  71. }
  72. // GetUserByName devuelve la fila de login (con pass_hash) o nil.
  73. func GetUserByName(d *db.DB, username string) *userRow {
  74. var u userRow
  75. err := d.QueryRow("SELECT id, username, pass_hash, role FROM users WHERE username = ?", username).
  76. Scan(&u.ID, &u.Username, &u.PassHash, &u.Role)
  77. if err != nil {
  78. return nil
  79. }
  80. return &u
  81. }
  82. // GetUserByID devuelve {id, username, role} o nil.
  83. func GetUserByID(d *db.DB, id int64) *User {
  84. var u User
  85. err := d.QueryRow("SELECT id, username, role FROM users WHERE id = ?", id).
  86. Scan(&u.ID, &u.Username, &u.Role)
  87. if err != nil {
  88. return nil
  89. }
  90. return &u
  91. }
  92. // CheckPassword verifica bcrypt (cost 10; hashes bcryptjs $2a/$2b portables).
  93. func CheckPassword(password, hash string) bool {
  94. return bcrypt.CompareHashAndPassword([]byte(hash), []byte(password)) == nil
  95. }
  96. // HashPassword genera un hash bcrypt cost 10.
  97. func HashPassword(password string) (string, error) {
  98. h, err := bcrypt.GenerateFromPassword([]byte(password), 10)
  99. return string(h), err
  100. }
  101. // ---------------------------------------------------------------------------
  102. // Secret HMAC
  103. // ---------------------------------------------------------------------------
  104. // EnsureSessionSecret: SESSION_SECRET del env si existe; si no, kv
  105. // `session_secret`; si no existe, se genera (64 chars hex) y se persiste.
  106. func EnsureSessionSecret(d *db.DB, cfg *config.Config) (string, error) {
  107. if cfg.SessionSecret != "" {
  108. return cfg.SessionSecret, nil
  109. }
  110. var value string
  111. err := d.QueryRow("SELECT value FROM kv WHERE key = 'session_secret'").Scan(&value)
  112. if err == nil && value != "" {
  113. return value, nil
  114. }
  115. buf := make([]byte, 32)
  116. if _, err := rand.Read(buf); err != nil {
  117. return "", err
  118. }
  119. secret := hex.EncodeToString(buf)
  120. if _, err := d.Exec(
  121. "INSERT INTO kv (key, value) VALUES ('session_secret', ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value",
  122. secret,
  123. ); err != nil {
  124. return "", err
  125. }
  126. return secret, nil
  127. }
  128. // ---------------------------------------------------------------------------
  129. // Cookie id.hmac
  130. // ---------------------------------------------------------------------------
  131. func hmacHex(secret, id string) string {
  132. m := hmac.New(sha256.New, []byte(secret))
  133. m.Write([]byte(id))
  134. return hex.EncodeToString(m.Sum(nil))
  135. }
  136. // SignSessionID devuelve `${id}.${hmac}`.
  137. func SignSessionID(secret, id string) string {
  138. return id + "." + hmacHex(secret, id)
  139. }
  140. // VerifySessionCookie valida `id.hmac`: split por el ÚLTIMO punto y
  141. // comparación timing-safe. Devuelve el id o "".
  142. func VerifySessionCookie(secret, value string) string {
  143. if value == "" {
  144. return ""
  145. }
  146. dot := strings.LastIndex(value, ".")
  147. if dot <= 0 {
  148. return ""
  149. }
  150. id := value[:dot]
  151. sig := value[dot+1:]
  152. expected := hmacHex(secret, id)
  153. // hmac.Equal es constant-time para entradas de la misma longitud
  154. // (paridad con safeEqual de auth.js:88-92).
  155. if !hmac.Equal([]byte(sig), []byte(expected)) {
  156. return ""
  157. }
  158. return id
  159. }
  160. // cookieRe replica /(?:^|;\s*)session=([^;]+)/ (primera ocurrencia).
  161. var cookieRe = regexp.MustCompile(`(?:^|;\s*)session=([^;]+)`)
  162. func sessionCookieValue(r *http.Request) string {
  163. m := cookieRe.FindStringSubmatch(r.Header.Get("Cookie"))
  164. if m == nil {
  165. return ""
  166. }
  167. return m[1]
  168. }
  169. // IsSecureRequest: URL https o primer X-Forwarded-Proto == "https".
  170. func IsSecureRequest(r *http.Request) bool {
  171. if r.TLS != nil || r.URL.Scheme == "https" {
  172. return true
  173. }
  174. proto := r.Header.Get("X-Forwarded-Proto")
  175. if proto == "" {
  176. return false
  177. }
  178. first := strings.TrimSpace(strings.Split(proto, ",")[0])
  179. return first == "https"
  180. }
  181. // CookieSecureFlag: always→true, never→false, auto→IsSecureRequest.
  182. func CookieSecureFlag(cfg *config.Config, r *http.Request) bool {
  183. switch cfg.CookieSecure {
  184. case "always":
  185. return true
  186. case "never":
  187. return false
  188. default:
  189. return IsSecureRequest(r)
  190. }
  191. }
  192. // BuildSessionCookie compone el header Set-Cookie (literal de auth.js:119-129).
  193. func BuildSessionCookie(cfg *config.Config, r *http.Request, signedID string, maxAgeSec int64) string {
  194. parts := []string{
  195. fmt.Sprintf("%s=%s", SessionCookie, signedID),
  196. "Path=/",
  197. "HttpOnly",
  198. "SameSite=Lax",
  199. fmt.Sprintf("Max-Age=%d", maxAgeSec),
  200. }
  201. if CookieSecureFlag(cfg, r) {
  202. parts = append(parts, "Secure")
  203. }
  204. return strings.Join(parts, "; ")
  205. }
  206. // ClearSessionCookie borra la cookie (literal, SIN Secure aunque sea HTTPS).
  207. const ClearSessionCookie = "session=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0"
  208. // ---------------------------------------------------------------------------
  209. // Sesiones en SQLite
  210. // ---------------------------------------------------------------------------
  211. // newUUIDv4 genera un UUID v4 canónico (8-4-4-4-12 hex) con crypto/rand.
  212. func newUUIDv4() string {
  213. var b [16]byte
  214. if _, err := rand.Read(b[:]); err != nil {
  215. panic(err)
  216. }
  217. b[6] = (b[6] & 0x0f) | 0x40 // versión 4
  218. b[8] = (b[8] & 0x3f) | 0x80 // variante RFC 4122
  219. return fmt.Sprintf("%x-%x-%x-%x-%x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:16])
  220. }
  221. // CreateSession crea una sesión (UUID v4, TTL 30 d, ua truncado a 255).
  222. func CreateSession(d *db.DB, ua string, userID int64) string {
  223. id := newUUIDv4()
  224. now := db.NowMS()
  225. if len(ua) > 255 {
  226. ua = ua[:255]
  227. }
  228. _, _ = d.Exec(
  229. "INSERT INTO sessions (id, created_at, expires_at, ua, user_id) VALUES (?, ?, ?, ?, ?)",
  230. id, now, now+SessionTTLMS, ua, userID,
  231. )
  232. return id
  233. }
  234. // DestroySession borra una sesión por id.
  235. func DestroySession(d *db.DB, id string) {
  236. if id != "" {
  237. _, _ = d.Exec("DELETE FROM sessions WHERE id = ?", id)
  238. }
  239. }
  240. // DestroyUserSessions borra todas las sesiones de un usuario (re-login forzado).
  241. func DestroyUserSessions(d *db.DB, userID int64) {
  242. _, _ = d.Exec("DELETE FROM sessions WHERE user_id = ?", userID)
  243. }
  244. // Session es la fila viva de sessions.
  245. type Session struct {
  246. ID string
  247. ExpiresAt int64
  248. UserID sql.NullInt64
  249. }
  250. // GetSession devuelve la sesión si existe y no expiró (si expiró, la borra).
  251. func GetSession(d *db.DB, id string) *Session {
  252. if id == "" {
  253. return nil
  254. }
  255. var s Session
  256. err := d.QueryRow("SELECT id, expires_at, user_id FROM sessions WHERE id = ?", id).
  257. Scan(&s.ID, &s.ExpiresAt, &s.UserID)
  258. if err != nil {
  259. return nil
  260. }
  261. if s.ExpiresAt < db.NowMS() {
  262. DestroySession(d, id)
  263. return nil
  264. }
  265. return &s
  266. }
  267. // SessionUser es el resultado de sessionUserFromRequest.
  268. type SessionUser struct {
  269. SessionID string
  270. User *User
  271. }
  272. // SessionUserFromRequest: cookie válida + sesión en DB con user_id NO nulo +
  273. // usuario existente (una sesión legacy sin user_id NO autentica).
  274. func SessionUserFromRequest(d *db.DB, secret string, r *http.Request) *SessionUser {
  275. id := VerifySessionCookie(secret, sessionCookieValue(r))
  276. sess := GetSession(d, id)
  277. if sess == nil || !sess.UserID.Valid {
  278. return nil
  279. }
  280. user := GetUserByID(d, sess.UserID.Int64)
  281. if user == nil {
  282. return nil
  283. }
  284. return &SessionUser{SessionID: id, User: user}
  285. }
  286. // SessionIDFromRequest devuelve el id de sesión válida (sin exigir user_id).
  287. func SessionIDFromRequest(d *db.DB, secret string, r *http.Request) string {
  288. id := VerifySessionCookie(secret, sessionCookieValue(r))
  289. if GetSession(d, id) == nil {
  290. return ""
  291. }
  292. return id
  293. }
  294. // ---------------------------------------------------------------------------
  295. // Rate-limit en SQLite (persiste tras reinicios)
  296. // ---------------------------------------------------------------------------
  297. // ClientIP: primer X-Forwarded-For o la IP remota o 'unknown'.
  298. func ClientIP(r *http.Request) string {
  299. if xff := r.Header.Get("X-Forwarded-For"); xff != "" {
  300. if first := strings.TrimSpace(strings.Split(xff, ",")[0]); first != "" {
  301. return first
  302. }
  303. }
  304. if host, _, err := net.SplitHostPort(r.RemoteAddr); err == nil && host != "" {
  305. return host
  306. }
  307. if r.RemoteAddr != "" {
  308. return r.RemoteAddr
  309. }
  310. return "unknown"
  311. }
  312. // LoginRateLimited: si la IP está bloqueada → retryAfterSec = ceil(rest/1000).
  313. func LoginRateLimited(d *db.DB, r *http.Request) (limited bool, retryAfterSec int64) {
  314. ip := ClientIP(r)
  315. var lockedUntil int64
  316. err := d.QueryRow("SELECT locked_until FROM login_attempts WHERE ip = ?", ip).Scan(&lockedUntil)
  317. if err != nil {
  318. return false, 0
  319. }
  320. remaining := lockedUntil - db.NowMS()
  321. if remaining > 0 {
  322. return true, (remaining + 999) / 1000
  323. }
  324. return false, 0
  325. }
  326. // RegisterLoginFail registra un fallo: bloquea 5 min cuando el valor ANTERIOR
  327. // de attempts >= 4 (el bloqueo se arma en el 5º fallo — UPSERT literal).
  328. func RegisterLoginFail(d *db.DB, r *http.Request) {
  329. ip := ClientIP(r)
  330. _, _ = d.Exec(`
  331. INSERT INTO login_attempts (ip, attempts, locked_until)
  332. VALUES (?, 1, 0)
  333. ON CONFLICT(ip) DO UPDATE SET
  334. attempts = attempts + 1,
  335. locked_until = CASE
  336. WHEN attempts >= 4 THEN ?
  337. ELSE locked_until
  338. END
  339. `, ip, db.NowMS()+LockMS)
  340. }
  341. // LoginOk borra la fila de login_attempts de la IP.
  342. func LoginOk(d *db.DB, r *http.Request) {
  343. _, _ = d.Exec("DELETE FROM login_attempts WHERE ip = ?", ClientIP(r))
  344. }
  345. // ---------------------------------------------------------------------------
  346. // Login / logout
  347. // ---------------------------------------------------------------------------
  348. // LoginResult es el resultado de HandleLogin.
  349. type LoginResult struct {
  350. SessionID string
  351. User *User
  352. }
  353. // HandleLogin valida credenciales y crea sesión nueva (rotación: invalida la
  354. // sesión previa de la cookie si existía). Nil si credenciales inválidas.
  355. func HandleLogin(d *db.DB, secret string, r *http.Request, username, password string) *LoginResult {
  356. if username == "" || password == "" {
  357. return nil
  358. }
  359. u := GetUserByName(d, username)
  360. if u == nil || !CheckPassword(password, u.PassHash) {
  361. return nil
  362. }
  363. // Rotación de sesión
  364. if prevID := SessionIDFromRequest(d, secret, r); prevID != "" {
  365. DestroySession(d, prevID)
  366. }
  367. id := CreateSession(d, r.Header.Get("User-Agent"), u.ID)
  368. return &LoginResult{SessionID: id, User: &User{ID: u.ID, Username: u.Username, Role: u.Role}}
  369. }
  370. // HandleLogout destruye la sesión de la cookie (si existe y es válida).
  371. func HandleLogout(d *db.DB, secret string, r *http.Request) {
  372. if id := SessionIDFromRequest(d, secret, r); id != "" {
  373. DestroySession(d, id)
  374. }
  375. }