All files / src/lib session-rotation.ts

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

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   
/**
 * Session Rotation on Privilege Escalation
 *
 * Invalidates all user sessions when privileges change to prevent
 * session fixation and privilege escalation attacks
 *
 * OWASP: A01:2021 - Broken Access Control
 * OWASP: A07:2021 - Session Fixation
 * NIST: SP 800-63B Section 7.1
 *
 * Architecture:
 * - Uses Redis for distributed session invalidation
 * - Falls back to database when Redis unavailable
 * - Integrates with Better Auth organization plugin
 */
 
import { logger } from "@snapback/infrastructure";
import { trackEvent } from "./audit";
 
/**
 * Rotate all sessions for a user when their role changes
 *
 * This prevents session fixation attacks where an attacker with a valid
 * low-privilege session tries to exploit a privilege escalation.
 *
 * @param userId User ID whose sessions should be invalidated
 * @param oldRole Previous role
 * @param newRole New role
 */
export async function rotateSessionsOnRoleChange(userId: string, oldRole: string, newRole: string): Promise<void> {
	// Skip if role hasn't actually changed
	if (oldRole === newRole) {
		logger.debug("Role unchanged, skipping session rotation", {
			userId,
			role: oldRole,
		});
		return;
	}
 
	logger.info("Rotating sessions due to role change", {
		userId,
		oldRole,
		newRole,
	});
 
	try {
		// Attempt Redis-based invalidation first
		const count = await invalidateSessionsRedis(userId);
 
		if (count !== null) {
			// Redis invalidation successful
			await trackEvent("session.rotated" as any, {
				userId,
				oldRole,
				newRole,
				reason: "privilege_change",
				sessionsInvalidated: count,
				method: "redis",
			});
 
			logger.info("Sessions rotated successfully", {
				userId,
				count,
				method: "redis",
			});
		} else {
			// Fallback to database invalidation
			const dbCount = await invalidateSessionsDatabase(userId);
 
			await trackEvent("session.rotated" as any, {
				userId,
				oldRole,
				newRole,
				reason: "privilege_change",
				sessionsInvalidated: dbCount,
				method: "database",
			});
 
			logger.info("Sessions rotated successfully (database fallback)", {
				userId,
				count: dbCount,
				method: "database",
			});
		}
	} catch (error) {
		logger.error("Failed to rotate sessions", {
			userId,
			error: error instanceof Error ? error.message : String(error),
		});
		throw error;
	}
}
 
/**
 * Rotate sessions for a specific organization context
 * Only invalidates sessions associated with the given organization
 *
 * @param userId User ID
 * @param organizationId Organization ID
 * @param oldRole Previous role in this organization
 * @param newRole New role in this organization
 */
export async function rotateSessionsOnOrgRoleChange(
	userId: string,
	organizationId: string,
	oldRole: string,
	newRole: string,
): Promise<void> {
	if (oldRole === newRole) {
		return;
	}
 
	logger.info("Rotating organization-scoped sessions", {
		userId,
		organizationId,
		oldRole,
		newRole,
	});
 
	try {
		// For organization-scoped rotation, we invalidate sessions that have
		// activeOrganizationId === organizationId
		const count = await invalidateOrgSessionsRedis(userId, organizationId);
 
		if (count !== null) {
			await trackEvent("session.rotated" as any, {
				userId,
				organizationId,
				oldRole,
				newRole,
				reason: "org_privilege_change",
				sessionsInvalidated: count,
			});
		} else {
			// Database fallback
			const dbCount = await invalidateOrgSessionsDatabase(userId, organizationId);
 
			await trackEvent("session.rotated" as any, {
				userId,
				organizationId,
				oldRole,
				newRole,
				reason: "org_privilege_change",
				sessionsInvalidated: dbCount,
			});
		}
	} catch (error) {
		logger.error("Failed to rotate organization sessions", {
			userId,
			organizationId,
			error: error instanceof Error ? error.message : String(error),
		});
		throw error;
	}
}
 
// =============================================================================
// Redis Implementation
// =============================================================================
 
/**
 * Invalidate all sessions for a user using Redis
 * Returns null if Redis is unavailable
 */
async function invalidateSessionsRedis(userId: string): Promise<number | null> {
	try {
		const { redisClient, redisAvailable } = await import("../auth.js");
 
		if (!redisAvailable || !redisClient) {
			logger.debug("Redis not available for session rotation");
			return null;
		}
 
		// Find all session keys for this user
		// Better Auth stores sessions with pattern: session:{userId}:*
		const pattern = `snapback:session:${userId}:*`;
		const keys = await redisClient.keys(pattern);
 
		if (keys.length === 0) {
			logger.debug("No Redis sessions found for user", { userId });
			return 0;
		}
 
		// Delete all session keys
		await redisClient.del(keys);
 
		logger.debug("Invalidated Redis sessions", {
			userId,
			count: keys.length,
		});
 
		return keys.length;
	} catch (error) {
		logger.warn("Redis session invalidation failed", {
			userId,
			error: error instanceof Error ? error.message : String(error),
		});
		return null;
	}
}
 
/**
 * Invalidate organization-scoped sessions using Redis
 */
async function invalidateOrgSessionsRedis(userId: string, organizationId: string): Promise<number | null> {
	try {
		const { redisClient, redisAvailable } = await import("../auth.js");
 
		if (!redisAvailable || !redisClient) {
			return null;
		}
 
		// Find sessions with this organization context
		const pattern = `snapback:session:${userId}:org:${organizationId}:*`;
		const keys = await redisClient.keys(pattern);
 
		if (keys.length > 0) {
			await redisClient.del(keys);
		}
 
		return keys.length;
	} catch (error) {
		logger.warn("Redis org session invalidation failed", {
			userId,
			organizationId,
			error,
		});
		return null;
	}
}
 
// =============================================================================
// Database Fallback Implementation
// =============================================================================
 
/**
 * Invalidate all sessions for a user using database
 */
async function invalidateSessionsDatabase(userId: string): Promise<number> {
	try {
		const { db } = await import("@snapback/platform");
		const { sql } = await import("drizzle-orm");
 
		if (!db) {
			logger.warn("Database not available for session invalidation");
			return 0;
		}
 
		// Delete all sessions for this user
		const result = await db.execute(sql`
			DELETE FROM session
			WHERE "userId" = ${userId}
		`);
 
		const count = result.rowCount || 0;
 
		logger.debug("Invalidated database sessions", { userId, count });
 
		return count;
	} catch (error) {
		logger.error("Database session invalidation failed", {
			userId,
			error: error instanceof Error ? error.message : String(error),
		});
		return 0;
	}
}
 
/**
 * Invalidate organization-scoped sessions using database
 */
async function invalidateOrgSessionsDatabase(userId: string, organizationId: string): Promise<number> {
	try {
		const { db } = await import("@snapback/platform");
		const { sql } = await import("drizzle-orm");
 
		if (!db) {
			return 0;
		}
 
		// Delete sessions where activeOrganizationId matches
		const result = await db.execute(sql`
			DELETE FROM session
			WHERE "userId" = ${userId}
			AND "activeOrganizationId" = ${organizationId}
		`);
 
		return result.rowCount || 0;
	} catch (error) {
		logger.error("Database org session invalidation failed", {
			userId,
			organizationId,
			error,
		});
		return 0;
	}
}