All files / src/lib/security security-logger.ts

0% Statements 0/342
100% Branches 0/0
0% Functions 0/1
0% Lines 0/342

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             
/**
 * Security Event Logger
 *
 * Logs security-related events for monitoring and alerting.
 * Tracks login attempts, suspicious activity, and security violations.
 */

import { prisma } from '@/lib/prisma';
import { logger } from '@/lib/logging';

// ============================================================================
// Types
// ============================================================================

export type SecurityEventType =
  | 'LOGIN_SUCCESS'
  | 'LOGIN_FAILURE'
  | 'LOGIN_BLOCKED'
  | 'LOGOUT'
  | 'PASSWORD_CHANGED'
  | 'PASSWORD_RESET_REQUESTED'
  | 'PASSWORD_RESET_COMPLETED'
  | 'TWO_FACTOR_ENABLED'
  | 'TWO_FACTOR_DISABLED'
  | 'TWO_FACTOR_VERIFIED'
  | 'TWO_FACTOR_FAILED'
  | 'SESSION_CREATED'
  | 'SESSION_REVOKED'
  | 'ALL_SESSIONS_REVOKED'
  | 'SUSPICIOUS_ACTIVITY'
  | 'RATE_LIMIT_EXCEEDED'
  | 'CSRF_VIOLATION'
  | 'XSS_ATTEMPT'
  | 'SQL_INJECTION_ATTEMPT'
  | 'UNAUTHORIZED_ACCESS'
  | 'PERMISSION_DENIED'
  | 'ADMIN_ACTION'
  | 'API_KEY_CREATED'
  | 'API_KEY_REVOKED'
  | 'ACCOUNT_LOCKED'
  | 'ACCOUNT_UNLOCKED';

export type SecuritySeverity = 'LOW' | 'MEDIUM' | 'HIGH' | 'CRITICAL';

export interface SecurityEvent {
  type: SecurityEventType;
  userId?: string | number;
  ipAddress: string;
  userAgent: string;
  details?: Record<string, unknown>;
  severity: SecuritySeverity;
}

// ============================================================================
// Security Event Logger
// ============================================================================

/**
 * Log a security event
 */
export async function logSecurityEvent(event: SecurityEvent): Promise<void> {
  try {
    // Store in database
    await prisma.securityLog.create({
      data: {
        type: event.type,
        userId: event.userId ? Number(event.userId) : null,
        ipAddress: event.ipAddress,
        userAgent: event.userAgent,
        details: event.details ? JSON.parse(JSON.stringify(event.details)) : undefined,
        severity: event.severity,
        timestamp: new Date(),
      },
    });

    // Log to observability system
    logger.security(event.type, {
      userId: event.userId,
      ipAddress: event.ipAddress,
      severity: event.severity,
      ...event.details,
    }, event.severity.toLowerCase() as 'low' | 'medium' | 'high' | 'critical');

    // Alert on high/critical events
    if (event.severity === 'HIGH' || event.severity === 'CRITICAL') {
      await sendSecurityAlert(event);
    }

    // Track failed logins for blocking
    if (event.type === 'LOGIN_FAILURE') {
      await trackFailedLogin(event.ipAddress, event.userId?.toString());
    }
  } catch (error) {
    // Don't throw - security logging should not break the app
    logger.error('Failed to log security event', error instanceof Error ? error : new Error(String(error)), { category: 'SECURITY' });
  }
}

/**
 * Send security alert for high/critical events
 */
async function sendSecurityAlert(event: SecurityEvent): Promise<void> {
  // Log as alert
  logger.warn('Security Alert', {
    type: event.type,
    severity: event.severity,
    ipAddress: event.ipAddress,
    userId: event.userId,
    details: event.details,
  });

  // TODO: Add email/Slack/PagerDuty notifications
  // For now, just log the alert
}

/**
 * Track failed login attempts
 */
async function trackFailedLogin(
  ipAddress: string,
  userId?: string
): Promise<void> {
  const windowMs = 15 * 60 * 1000; // 15 minutes
  const maxAttempts = 5;
  const since = new Date(Date.now() - windowMs);

  try {
    // Count recent failures for this IP
    const ipFailures = await prisma.securityLog.count({
      where: {
        type: 'LOGIN_FAILURE',
        ipAddress,
        timestamp: { gte: since },
      },
    });

    if (ipFailures >= maxAttempts) {
      // Block the IP
      await blockIp(ipAddress, 'Too many failed login attempts', 60 * 60 * 1000); // 1 hour

      await logSecurityEvent({
        type: 'LOGIN_BLOCKED',
        ipAddress,
        userAgent: '',
        severity: 'HIGH',
        details: { failedAttempts: ipFailures, reason: 'IP blocked' },
      });
    }

    // Also check user-specific failures if userId provided
    if (userId) {
      const userFailures = await prisma.securityLog.count({
        where: {
          type: 'LOGIN_FAILURE',
          userId: Number(userId),
          timestamp: { gte: since },
        },
      });

      if (userFailures >= maxAttempts) {
        await logSecurityEvent({
          type: 'ACCOUNT_LOCKED',
          userId,
          ipAddress,
          userAgent: '',
          severity: 'HIGH',
          details: { failedAttempts: userFailures, reason: 'Account locked' },
        });
      }
    }
  } catch (error) {
    logger.error('Failed to track login failure', error instanceof Error ? error : new Error(String(error)), { category: 'SECURITY' });
  }
}

/**
 * Block an IP address
 */
export async function blockIp(
  ipAddress: string,
  reason: string,
  durationMs: number
): Promise<void> {
  try {
    await prisma.blockedIp.upsert({
      where: { ipAddress },
      update: {
        reason,
        expiresAt: new Date(Date.now() + durationMs),
      },
      create: {
        ipAddress,
        reason,
        expiresAt: new Date(Date.now() + durationMs),
      },
    });
  } catch (error) {
    logger.error('Failed to block IP', error instanceof Error ? error : new Error(String(error)), { category: 'SECURITY', ipAddress });
  }
}

/**
 * Unblock an IP address
 */
export async function unblockIp(ipAddress: string): Promise<void> {
  try {
    await prisma.blockedIp.delete({
      where: { ipAddress },
    });
  } catch {
    // IP might not be blocked
  }
}

/**
 * Check if an IP is blocked
 */
export async function isIpBlocked(ipAddress: string): Promise<boolean> {
  try {
    const blocked = await prisma.blockedIp.findUnique({
      where: { ipAddress },
    });

    if (!blocked) return false;

    // Check if block has expired
    if (blocked.expiresAt < new Date()) {
      await unblockIp(ipAddress);
      return false;
    }

    return true;
  } catch {
    return false;
  }
}

/**
 * Get recent security events for dashboard
 */
export async function getRecentSecurityEvents(options: {
  limit?: number;
  severity?: SecuritySeverity[];
  type?: SecurityEventType[];
  userId?: number;
  since?: Date;
} = {}): Promise<Array<{
  id: string;
  type: string;
  userId: number | null;
  ipAddress: string;
  userAgent: string;
  details: unknown;
  severity: string;
  timestamp: Date;
}>> {
  const {
    limit = 50,
    severity,
    type,
    userId,
    since = new Date(Date.now() - 24 * 60 * 60 * 1000),
  } = options;

  return prisma.securityLog.findMany({
    where: {
      timestamp: { gte: since },
      ...(severity && { severity: { in: severity } }),
      ...(type && { type: { in: type } }),
      ...(userId && { userId }),
    },
    orderBy: { timestamp: 'desc' },
    take: limit,
  });
}

/**
 * Get security event counts for dashboard
 */
export async function getSecurityEventCounts(since?: Date): Promise<Record<string, number>> {
  const startDate = since || new Date(Date.now() - 24 * 60 * 60 * 1000);

  const counts = await prisma.securityLog.groupBy({
    by: ['type'],
    where: { timestamp: { gte: startDate } },
    _count: { type: true },
  });

  return counts.reduce((acc, { type, _count }) => {
    acc[type] = _count.type;
    return acc;
  }, {} as Record<string, number>);
}

/**
 * Get blocked IPs
 */
export async function getBlockedIps(): Promise<Array<{
  id: string;
  ipAddress: string;
  reason: string;
  expiresAt: Date;
  createdAt: Date;
}>> {
  return prisma.blockedIp.findMany({
    where: { expiresAt: { gt: new Date() } },
    orderBy: { createdAt: 'desc' },
  });
}

/**
 * Clean up expired blocked IPs
 */
export async function cleanupExpiredBlocks(): Promise<number> {
  const result = await prisma.blockedIp.deleteMany({
    where: { expiresAt: { lt: new Date() } },
  });
  return result.count;
}

/**
 * Get failed login stats by IP
 */
export async function getFailedLoginStats(since?: Date): Promise<Array<{
  ipAddress: string;
  _count: { ipAddress: number };
}>> {
  const startDate = since || new Date(Date.now() - 24 * 60 * 60 * 1000);

  const results = await prisma.securityLog.groupBy({
    by: ['ipAddress'],
    where: {
      type: 'LOGIN_FAILURE',
      timestamp: { gte: startDate },
    },
    _count: { ipAddress: true },
    orderBy: { _count: { ipAddress: 'desc' } },
    take: 20,
  });

  return results;
}