package auth import ( "context" "crypto/rand" "crypto/sha256" "encoding/hex" "encoding/json" "errors" "fmt" "net/http" "regexp" "slices" "strconv" "strings" "sync" "time" "cotizador/internal/audit" "cotizador/internal/domain" "github.com/golang-jwt/jwt/v5" "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgxpool" "golang.org/x/crypto/bcrypt" ) const ( SessionCookieName = "cotizador-session" SessionTTL = 7 * 24 * time.Hour APIKeyPrefix = "ujc_live_" ) // Exact 9 allowed agent scopes. NEVER add an approval scope. var AgentScopes = []string{ "catalogo:leer", "clientes:leer", "clientes:escribir", "cotizaciones:leer", "cotizaciones:leer_aceptadas", "cotizaciones:borrador", "cotizaciones:enviar", "cobros:leer", "cobros:registrar", } func IsValidScope(s string) bool { return slices.Contains(AgentScopes, s) } type SessionPayload struct { UserID string `json:"userId"` Email string `json:"email"` Name string `json:"name"` Role string `json:"role"` ClienteID string `json:"clienteId,omitempty"` } type jwtClaims struct { UserID string `json:"userId"` Email string `json:"email"` Name string `json:"name"` Role string `json:"role"` ClienteID string `json:"clienteId,omitempty"` jwt.RegisteredClaims } type Actor struct { Type string // "user" | "agent" UserID string Email string Name string Role string // "admin" | "asesor" | "cliente" ClienteID string KeyID string KeyNombre string Scopes []string RateLimitPerMin int RateHeaders map[string]string } func (a *Actor) ToDomainActor() domain.ActorInfo { return domain.ActorInfo{ Type: a.Type, Role: a.Role, Scopes: a.Scopes, } } func (a *Actor) AuditActor() (tipo, id, nombre string) { if a.Type == "agent" { return "agent", a.KeyID, a.KeyNombre } return "user", a.UserID, a.Email } func (a *Actor) IsAdmin() bool { return a.Type == "user" && a.Role == "admin" } func (a *Actor) IsStaff() bool { return a.Type == "user" && a.Role != "cliente" } func (a *Actor) IsCliente() bool { return a.Type == "user" && a.Role == "cliente" } func (a *Actor) IsAgent() bool { return a.Type == "agent" } func (a *Actor) HasScopes(required []string, mode string) bool { if a.IsStaff() { return true } if !a.IsAgent() { return false } if len(required) == 0 { return true } if mode == "all" { for _, req := range required { if !slices.Contains(a.Scopes, req) { return false } } return true } for _, req := range required { if slices.Contains(a.Scopes, req) { return true } } return false } // EsAgenteSoloAceptadas returns true when agent has cotizaciones:leer_aceptadas and NOT cotizaciones:leer. func (a *Actor) EsAgenteSoloAceptadas() bool { return a.IsAgent() && slices.Contains(a.Scopes, "cotizaciones:leer_aceptadas") && !slices.Contains(a.Scopes, "cotizaciones:leer") } func (a *Actor) ApplyHeaders(w http.ResponseWriter) { for k, v := range a.RateHeaders { w.Header().Set(k, v) } } func HashPassword(plain string) (string, error) { b, err := bcrypt.GenerateFromPassword([]byte(plain), 10) return string(b), err } func ComparePassword(hash, plain string) bool { return bcrypt.CompareHashAndPassword([]byte(hash), []byte(plain)) == nil } func HashSecret(raw string) string { sum := sha256.Sum256([]byte(raw)) return hex.EncodeToString(sum[:]) } func GenerateAPIKey() (rawKey, prefijo, keyHash string) { var b [32]byte _, _ = rand.Read(b[:]) rawKey = APIKeyPrefix + hex.EncodeToString(b[:]) prefijo = rawKey[:14] keyHash = HashSecret(rawKey) return } func GenerateRandomToken(numBytes int) (raw, hash string) { b := make([]byte, numBytes) _, _ = rand.Read(b) raw = hex.EncodeToString(b) hash = HashSecret(raw) return } var nonDigitsRe = regexp.MustCompile(`\D+`) // CoincideContacto matches exact email (case-insensitive) or last 10 digits of phone. func CoincideContacto(verificar string, clienteEmail, clienteTelefono string) bool { v := strings.TrimSpace(verificar) if v == "" { return false } if strings.Contains(v, "@") { return clienteEmail != "" && strings.EqualFold(v, strings.TrimSpace(clienteEmail)) } digitsV := nonDigitsRe.ReplaceAllString(v, "") digitsC := nonDigitsRe.ReplaceAllString(clienteTelefono, "") if len(digitsV) < 7 || len(digitsC) < 7 { return false } if len(digitsV) > 10 { digitsV = digitsV[len(digitsV)-10:] } if len(digitsC) > 10 { digitsC = digitsC[len(digitsC)-10:] } return digitsV == digitsC } // RateLimiter implements an in-memory 60-second sliding window per API key. type RateLimiter struct { mu sync.Mutex buckets map[string][]time.Time } func NewRateLimiter() *RateLimiter { return &RateLimiter{buckets: make(map[string][]time.Time)} } type RateLimitResult struct { Allowed bool Limit int Remaining int ResetUnix int64 RetryAfter int } func (rl *RateLimiter) Check(keyID string, limit int, now time.Time) RateLimitResult { if limit < 1 { limit = 60 } windowStart := now.Add(-60 * time.Second) rl.mu.Lock() defer rl.mu.Unlock() existing := rl.buckets[keyID] kept := existing[:0] for _, ts := range existing { if ts.After(windowStart) { kept = append(kept, ts) } } if len(kept) >= limit { rl.buckets[keyID] = kept oldest := kept[0] resetAt := oldest.Add(60 * time.Second) retrySec := int(time.Until(resetAt).Seconds()) if now != (time.Time{}) { retrySec = int(resetAt.Sub(now).Seconds()) } if retrySec < 1 { retrySec = 1 } return RateLimitResult{ Allowed: false, Limit: limit, Remaining: 0, ResetUnix: resetAt.Unix(), RetryAfter: retrySec, } } kept = append(kept, now) rl.buckets[keyID] = kept resetAt := kept[0].Add(60 * time.Second) return RateLimitResult{ Allowed: true, Limit: limit, Remaining: limit - len(kept), ResetUnix: resetAt.Unix(), } } func BuildRateLimitHeaders(res RateLimitResult) map[string]string { h := map[string]string{ "X-RateLimit-Limit": strconv.Itoa(res.Limit), "X-RateLimit-Remaining": strconv.Itoa(res.Remaining), "X-RateLimit-Reset": strconv.FormatInt(res.ResetUnix, 10), } if !res.Allowed { retry := res.RetryAfter if retry < 1 { retry = 1 } h["Retry-After"] = strconv.Itoa(retry) } return h } type Service struct { jwtSecret []byte isProduction bool pool *pgxpool.Pool limiter *RateLimiter } func NewService(jwtSecret string, isProduction bool, pool *pgxpool.Pool) *Service { return &Service{ jwtSecret: []byte(jwtSecret), isProduction: isProduction, pool: pool, limiter: NewRateLimiter(), } } func (s *Service) SignSession(p SessionPayload) (string, error) { now := time.Now() claims := jwtClaims{ UserID: p.UserID, Email: p.Email, Name: p.Name, Role: p.Role, ClienteID: p.ClienteID, RegisteredClaims: jwt.RegisteredClaims{ IssuedAt: jwt.NewNumericDate(now), ExpiresAt: jwt.NewNumericDate(now.Add(SessionTTL)), }, } tok := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) return tok.SignedString(s.jwtSecret) } func (s *Service) VerifySession(tokenStr string) (*SessionPayload, error) { if tokenStr == "" { return nil, errors.New("empty token") } tok, err := jwt.ParseWithClaims(tokenStr, &jwtClaims{}, func(t *jwt.Token) (any, error) { if t.Method.Alg() != jwt.SigningMethodHS256.Alg() { return nil, fmt.Errorf("unexpected signing method: %v", t.Header["alg"]) } return s.jwtSecret, nil }) if err != nil || !tok.Valid { return nil, errors.New("invalid token") } c, ok := tok.Claims.(*jwtClaims) if !ok || c.UserID == "" { return nil, errors.New("invalid claims") } role := c.Role if role == "" { role = "asesor" } return &SessionPayload{ UserID: c.UserID, Email: c.Email, Name: c.Name, Role: role, ClienteID: c.ClienteID, }, nil } func (s *Service) SetSessionCookie(w http.ResponseWriter, token string) { http.SetCookie(w, &http.Cookie{ Name: SessionCookieName, Value: token, Path: "/", MaxAge: int(SessionTTL.Seconds()), HttpOnly: true, SameSite: http.SameSiteLaxMode, Secure: s.isProduction, }) } func (s *Service) ClearSessionCookie(w http.ResponseWriter) { http.SetCookie(w, &http.Cookie{ Name: SessionCookieName, Value: "", Path: "/", MaxAge: -1, HttpOnly: true, SameSite: http.SameSiteLaxMode, Secure: s.isProduction, }) } func (s *Service) SessionFromRequest(r *http.Request) (*SessionPayload, bool) { c, err := r.Cookie(SessionCookieName) if err != nil || c.Value == "" { return nil, false } p, err := s.VerifySession(c.Value) if err != nil { return nil, false } return p, true } func ExtractAPIKey(r *http.Request) string { if k := strings.TrimSpace(r.Header.Get("X-API-Key")); k != "" { return k } authz := strings.TrimSpace(r.Header.Get("Authorization")) if len(authz) > 7 && strings.EqualFold(authz[:7], "bearer ") { return strings.TrimSpace(authz[7:]) } return "" } type RequireOptions struct { AdminOnly bool StaffOnly bool AllowCliente bool Scopes []string ScopeMode string // "any" (default) | "all" AccionBloqueo string RecursoTipo string RecursoID string } // RequireActor authenticates either cookie session (priority) or AgentApiKey, // enforces role/scope/rate-limit rules, logs failures to AuditLog, and writes the HTTP error response if denied. func (s *Service) RequireActor(w http.ResponseWriter, r *http.Request, opts RequireOptions) (*Actor, bool) { var actor *Actor // 1. Cookie JWT takes priority if sess, ok := s.SessionFromRequest(r); ok { actor = &Actor{ Type: "user", UserID: sess.UserID, Email: sess.Email, Name: sess.Name, Role: sess.Role, ClienteID: sess.ClienteID, } } else if rawKey := ExtractAPIKey(r); rawKey != "" { // 2. Agent API Key lookup via SHA-256 keyHash := HashSecret(rawKey) var id, nombre string var scopes []string var rateLimit int var lastUsedAt *time.Time err := s.pool.QueryRow(r.Context(), ` SELECT "id", "nombre", "scopes", "rateLimitPerMin", "lastUsedAt" FROM "AgentApiKey" WHERE "keyHash" = $1 AND "activo" = true AND "revokedAt" IS NULL `, keyHash).Scan(&id, &nombre, &scopes, &rateLimit, &lastUsedAt) if err != nil { if !errors.Is(err, pgx.ErrNoRows) { writeAuthJSON(w, http.StatusInternalServerError, map[string]any{"error": "Error validando credenciales"}) return nil, false } audit.Registrar(r.Context(), s.pool, audit.Entry{ ActorTipo: "agent", ActorNombre: "clave_invalida", Accion: "auth.api_key_invalida", RecursoTipo: firstOr(opts.RecursoTipo, "auth"), RecursoID: opts.RecursoID, IP: audit.ClientIP(r), RequestID: audit.RequestID(r), Exito: false, Detalle: map[string]any{"path": r.URL.Path, "method": r.Method}, }) writeAuthJSON(w, http.StatusUnauthorized, map[string]any{"error": "API key invalida o revocada"}) return nil, false } // Rate limit check rlRes := s.limiter.Check(id, rateLimit, time.Now()) headers := BuildRateLimitHeaders(rlRes) if !rlRes.Allowed { for k, v := range headers { w.Header().Set(k, v) } audit.Registrar(r.Context(), s.pool, audit.Entry{ ActorTipo: "agent", ActorID: id, ActorNombre: nombre, Accion: "auth.rate_limit", RecursoTipo: firstOr(opts.RecursoTipo, "auth"), RecursoID: opts.RecursoID, IP: audit.ClientIP(r), RequestID: audit.RequestID(r), Exito: false, Detalle: map[string]any{"limit": rateLimit, "path": r.URL.Path}, }) writeAuthJSON(w, http.StatusTooManyRequests, map[string]any{"error": "Limite de peticiones por minuto excedido"}) return nil, false } // Throttled async lastUsedAt update (>60s) if lastUsedAt == nil || time.Since(*lastUsedAt) > 60*time.Second { go func(keyID string) { ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) defer cancel() _, _ = s.pool.Exec(ctx, `UPDATE "AgentApiKey" SET "lastUsedAt" = NOW(), "updatedAt" = NOW() WHERE "id" = $1`, keyID) }(id) } actor = &Actor{ Type: "agent", KeyID: id, KeyNombre: nombre, Scopes: scopes, RateLimitPerMin: rateLimit, RateHeaders: headers, } } else { writeAuthJSON(w, http.StatusUnauthorized, map[string]any{"error": "No autenticado"}) return nil, false } // Role / Scope enforcement if opts.AdminOnly && !actor.IsAdmin() { tipo, aid, anombre := actor.AuditActor() audit.Registrar(r.Context(), s.pool, audit.Entry{ ActorTipo: tipo, ActorID: aid, ActorNombre: anombre, Accion: firstOr(opts.AccionBloqueo, "auth.admin_requerido"), RecursoTipo: firstOr(opts.RecursoTipo, "auth"), RecursoID: opts.RecursoID, IP: audit.ClientIP(r), RequestID: audit.RequestID(r), Exito: false, Detalle: map[string]any{"path": r.URL.Path, "method": r.Method}, }) writeAuthJSON(w, http.StatusForbidden, map[string]any{"error": "Solo un administrador humano puede realizar esta accion"}) return nil, false } if opts.StaffOnly && !actor.IsStaff() { tipo, aid, anombre := actor.AuditActor() audit.Registrar(r.Context(), s.pool, audit.Entry{ ActorTipo: tipo, ActorID: aid, ActorNombre: anombre, Accion: firstOr(opts.AccionBloqueo, "auth.staff_requerido"), RecursoTipo: firstOr(opts.RecursoTipo, "auth"), RecursoID: opts.RecursoID, IP: audit.ClientIP(r), RequestID: audit.RequestID(r), Exito: false, Detalle: map[string]any{"path": r.URL.Path, "method": r.Method}, }) writeAuthJSON(w, http.StatusForbidden, map[string]any{"error": "Acceso exclusivo para equipo interno"}) return nil, false } if actor.IsCliente() && !opts.AllowCliente { writeAuthJSON(w, http.StatusForbidden, map[string]any{"error": "Acceso no permitido para cuentas de cliente"}) return nil, false } if len(opts.Scopes) > 0 && !actor.IsCliente() { mode := opts.ScopeMode if mode == "" { mode = "any" } if !actor.HasScopes(opts.Scopes, mode) { tipo, aid, anombre := actor.AuditActor() audit.Registrar(r.Context(), s.pool, audit.Entry{ ActorTipo: tipo, ActorID: aid, ActorNombre: anombre, Accion: firstOr(opts.AccionBloqueo, "auth.scope_insuficiente"), RecursoTipo: firstOr(opts.RecursoTipo, "auth"), RecursoID: opts.RecursoID, IP: audit.ClientIP(r), RequestID: audit.RequestID(r), Exito: false, Detalle: map[string]any{"requiredScopes": opts.Scopes, "path": r.URL.Path}, }) writeAuthJSON(w, http.StatusForbidden, map[string]any{ "error": "Alcance insuficiente para esta operacion", "requiredScopes": opts.Scopes, }) return nil, false } } actor.ApplyHeaders(w) return actor, true } // RequireCliente enforces a valid cookie session with role == "cliente" and non-empty clienteId. func (s *Service) RequireCliente(w http.ResponseWriter, r *http.Request) (*SessionPayload, bool) { sess, ok := s.SessionFromRequest(r) if !ok { writeAuthJSON(w, http.StatusUnauthorized, map[string]any{"error": "No autenticado"}) return nil, false } if sess.Role != "cliente" || sess.ClienteID == "" { writeAuthJSON(w, http.StatusForbidden, map[string]any{"error": "Acceso exclusivo para clientes"}) return nil, false } return sess, true } func firstOr(v, fallback string) string { if v != "" { return v } return fallback } func writeAuthJSON(w http.ResponseWriter, status int, payload any) { w.Header().Set("Content-Type", "application/json; charset=utf-8") w.WriteHeader(status) _ = json.NewEncoder(w).Encode(payload) }