|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +/** |
| 4 | + * Production Safety Check for Test Suite |
| 5 | + * |
| 6 | + * GAP-SYNC-047: Prevents tests from running against production databases |
| 7 | + * by checking multiple safety signals: |
| 8 | + * |
| 9 | + * 1. Database name should contain "test" (configurable) |
| 10 | + * 2. Entry count should be below threshold (default: 100) |
| 11 | + * |
| 12 | + * Environment Variables: |
| 13 | + * - TEST_SAFETY_MAX_ENTRIES: Max entries before refusing (default: 100, 0 to disable) |
| 14 | + * - TEST_SAFETY_REQUIRE_TEST_DB: Require "test" in DB name (default: true) |
| 15 | + * - TEST_SAFETY_SKIP: Emergency bypass for all checks (default: false) |
| 16 | + */ |
| 17 | + |
| 18 | +const DEFAULT_MAX_ENTRIES = 100; |
| 19 | + |
| 20 | +/** |
| 21 | + * Extract database name from MongoDB connection string |
| 22 | + * @param {string} connectionString - MongoDB URI |
| 23 | + * @returns {string} Database name |
| 24 | + */ |
| 25 | +function extractDbName(connectionString) { |
| 26 | + try { |
| 27 | + // Handle both mongodb:// and mongodb+srv:// formats |
| 28 | + const url = new URL(connectionString); |
| 29 | + // pathname is /dbname or /dbname?options |
| 30 | + let dbName = url.pathname.slice(1); // Remove leading / |
| 31 | + // Remove query string if present |
| 32 | + const queryIndex = dbName.indexOf('?'); |
| 33 | + if (queryIndex > -1) { |
| 34 | + dbName = dbName.slice(0, queryIndex); |
| 35 | + } |
| 36 | + return dbName || 'nightscout'; |
| 37 | + } catch (err) { |
| 38 | + // Fallback for non-standard connection strings |
| 39 | + const match = connectionString.match(/\/([^/?]+)(\?|$)/); |
| 40 | + return match ? match[1] : 'unknown'; |
| 41 | + } |
| 42 | +} |
| 43 | + |
| 44 | +/** |
| 45 | + * Check if database name indicates a test database |
| 46 | + * @param {string} dbName - Database name |
| 47 | + * @returns {boolean} True if looks like test database |
| 48 | + */ |
| 49 | +function isTestDatabaseName(dbName) { |
| 50 | + const lower = dbName.toLowerCase(); |
| 51 | + return lower.includes('test') || |
| 52 | + lower.includes('_test') || |
| 53 | + lower.startsWith('test_') || |
| 54 | + lower.endsWith('_test'); |
| 55 | +} |
| 56 | + |
| 57 | +/** |
| 58 | + * Run production safety checks |
| 59 | + * |
| 60 | + * @param {Object} ctx - Boot context with entries collection |
| 61 | + * @param {Object} env - Environment with storageURI |
| 62 | + * @returns {Promise<void>} Resolves if safe, rejects with error if not |
| 63 | + */ |
| 64 | +async function checkProductionSafety(ctx, env) { |
| 65 | + // Emergency bypass |
| 66 | + if (process.env.TEST_SAFETY_SKIP === 'true') { |
| 67 | + console.warn('[SAFETY] ⚠️ TEST_SAFETY_SKIP=true - All safety checks bypassed!'); |
| 68 | + return; |
| 69 | + } |
| 70 | + |
| 71 | + const errors = []; |
| 72 | + const warnings = []; |
| 73 | + |
| 74 | + // Check 1: Database name should indicate test |
| 75 | + const requireTestDb = process.env.TEST_SAFETY_REQUIRE_TEST_DB !== 'false'; |
| 76 | + const dbName = extractDbName(env.storageURI || env.mongo_connection || ''); |
| 77 | + |
| 78 | + if (requireTestDb && !isTestDatabaseName(dbName)) { |
| 79 | + errors.push({ |
| 80 | + check: 'Database Name', |
| 81 | + message: `Database "${dbName}" doesn't contain "test" in its name`, |
| 82 | + hint: 'Use a database name like "nightscout_test" or set TEST_SAFETY_REQUIRE_TEST_DB=false' |
| 83 | + }); |
| 84 | + } else if (isTestDatabaseName(dbName)) { |
| 85 | + console.log(`[SAFETY] ✅ Database name "${dbName}" looks like a test database`); |
| 86 | + } |
| 87 | + |
| 88 | + // Check 2: Entry count threshold |
| 89 | + const maxEntries = parseInt(process.env.TEST_SAFETY_MAX_ENTRIES || String(DEFAULT_MAX_ENTRIES), 10); |
| 90 | + |
| 91 | + if (maxEntries > 0 && ctx.store && ctx.store.db) { |
| 92 | + try { |
| 93 | + // Access entries collection directly via store |
| 94 | + const entriesCol = ctx.store.db.collection('entries'); |
| 95 | + // Use limit+1 pattern for efficiency - we only need to know if it exceeds threshold |
| 96 | + const count = await entriesCol.countDocuments({}, { |
| 97 | + limit: maxEntries + 1, |
| 98 | + maxTimeMS: 5000 // Don't hang on slow connections |
| 99 | + }); |
| 100 | + |
| 101 | + if (count > maxEntries) { |
| 102 | + errors.push({ |
| 103 | + check: 'Entry Count', |
| 104 | + message: `Database has ${count}+ entries (threshold: ${maxEntries})`, |
| 105 | + hint: `This looks like a production database. Set TEST_SAFETY_MAX_ENTRIES=${count + 100} to override` |
| 106 | + }); |
| 107 | + } else { |
| 108 | + console.log(`[SAFETY] ✅ Database has ${count} entries (threshold: ${maxEntries})`); |
| 109 | + } |
| 110 | + } catch (err) { |
| 111 | + warnings.push({ |
| 112 | + check: 'Entry Count', |
| 113 | + message: `Could not count entries: ${err.message}`, |
| 114 | + hint: 'Entry count check skipped' |
| 115 | + }); |
| 116 | + } |
| 117 | + } else if (maxEntries === 0) { |
| 118 | + console.log('[SAFETY] ⚠️ Entry count check disabled (TEST_SAFETY_MAX_ENTRIES=0)'); |
| 119 | + } |
| 120 | + |
| 121 | + // Report warnings |
| 122 | + warnings.forEach(w => { |
| 123 | + console.warn(`[SAFETY] ⚠️ ${w.check}: ${w.message}`); |
| 124 | + }); |
| 125 | + |
| 126 | + // Report errors and fail |
| 127 | + if (errors.length > 0) { |
| 128 | + console.error('\n' + '='.repeat(70)); |
| 129 | + console.error('🛡️ PRODUCTION SAFETY CHECK ACTIVATED'); |
| 130 | + console.error('='.repeat(70)); |
| 131 | + console.error('\nThis database appears to contain real data.'); |
| 132 | + console.error('Running the test suite WILL DELETE all data in this database.'); |
| 133 | + console.error('\nThis safety check exists to prevent accidental destruction of'); |
| 134 | + console.error('production data. If this is truly a test database, you can override.\n'); |
| 135 | + |
| 136 | + errors.forEach((e, i) => { |
| 137 | + console.error(`${i + 1}. ${e.check}:`); |
| 138 | + console.error(` ${e.message}`); |
| 139 | + console.error(` 💡 ${e.hint}\n`); |
| 140 | + }); |
| 141 | + |
| 142 | + console.error('Override options:'); |
| 143 | + console.error(' • Set TEST_SAFETY_MAX_ENTRIES to a higher value (e.g., 1000)'); |
| 144 | + console.error(' • Set TEST_SAFETY_REQUIRE_TEST_DB=false to allow any DB name'); |
| 145 | + console.error(' • Set TEST_SAFETY_SKIP=true to bypass ALL checks (dangerous!)'); |
| 146 | + console.error('='.repeat(70) + '\n'); |
| 147 | + |
| 148 | + throw new Error('Production safety check activated: ' + errors.map(e => e.check).join(', ')); |
| 149 | + } |
| 150 | + |
| 151 | + console.log('[SAFETY] ✅ All production safety checks passed'); |
| 152 | +} |
| 153 | + |
| 154 | +/** |
| 155 | + * Synchronous pre-flight check (no DB required) |
| 156 | + * Run this before booting the application |
| 157 | + */ |
| 158 | +function preflightCheck() { |
| 159 | + // Check NODE_ENV |
| 160 | + if (process.env.NODE_ENV !== 'test') { |
| 161 | + console.error('\n❌ SAFETY ERROR: NODE_ENV must be "test" to run tests.'); |
| 162 | + console.error(' Current value: ' + (process.env.NODE_ENV || '(not set)')); |
| 163 | + console.error(' Tests use deleteMany({}) which could destroy production data.'); |
| 164 | + console.error(' Fix: Use "npm test" which loads my.test.env, or set NODE_ENV=test\n'); |
| 165 | + process.exit(1); |
| 166 | + } |
| 167 | +} |
| 168 | + |
| 169 | +module.exports = { |
| 170 | + checkProductionSafety, |
| 171 | + preflightCheck, |
| 172 | + extractDbName, |
| 173 | + isTestDatabaseName, |
| 174 | + DEFAULT_MAX_ENTRIES |
| 175 | +}; |
0 commit comments