-
Notifications
You must be signed in to change notification settings - Fork 73k
Expand file tree
/
Copy pathproduction-safety.js
More file actions
175 lines (156 loc) · 6.08 KB
/
production-safety.js
File metadata and controls
175 lines (156 loc) · 6.08 KB
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
'use strict';
/**
* Production Safety Check for Test Suite
*
* GAP-SYNC-047: Prevents tests from running against production databases
* by checking multiple safety signals:
*
* 1. Database name should contain "test" (configurable)
* 2. Entry count should be below threshold (default: 100)
*
* Environment Variables:
* - TEST_SAFETY_MAX_ENTRIES: Max entries before refusing (default: 100, 0 to disable)
* - TEST_SAFETY_REQUIRE_TEST_DB: Require "test" in DB name (default: true)
* - TEST_SAFETY_SKIP: Emergency bypass for all checks (default: false)
*/
const DEFAULT_MAX_ENTRIES = 100;
/**
* Extract database name from MongoDB connection string
* @param {string} connectionString - MongoDB URI
* @returns {string} Database name
*/
function extractDbName(connectionString) {
try {
// Handle both mongodb:// and mongodb+srv:// formats
const url = new URL(connectionString);
// pathname is /dbname or /dbname?options
let dbName = url.pathname.slice(1); // Remove leading /
// Remove query string if present
const queryIndex = dbName.indexOf('?');
if (queryIndex > -1) {
dbName = dbName.slice(0, queryIndex);
}
return dbName || 'nightscout';
} catch (err) {
// Fallback for non-standard connection strings
const match = connectionString.match(/\/([^/?]+)(\?|$)/);
return match ? match[1] : 'unknown';
}
}
/**
* Check if database name indicates a test database
* @param {string} dbName - Database name
* @returns {boolean} True if looks like test database
*/
function isTestDatabaseName(dbName) {
const lower = dbName.toLowerCase();
return lower.includes('test') ||
lower.includes('_test') ||
lower.startsWith('test_') ||
lower.endsWith('_test');
}
/**
* Run production safety checks
*
* @param {Object} ctx - Boot context with entries collection
* @param {Object} env - Environment with storageURI
* @returns {Promise<void>} Resolves if safe, rejects with error if not
*/
async function checkProductionSafety(ctx, env) {
// Emergency bypass
if (process.env.TEST_SAFETY_SKIP === 'true') {
console.warn('[SAFETY] ⚠️ TEST_SAFETY_SKIP=true - All safety checks bypassed!');
return;
}
const errors = [];
const warnings = [];
// Check 1: Database name should indicate test
const requireTestDb = process.env.TEST_SAFETY_REQUIRE_TEST_DB !== 'false';
const dbName = extractDbName(env.storageURI || env.mongo_connection || '');
if (requireTestDb && !isTestDatabaseName(dbName)) {
errors.push({
check: 'Database Name',
message: `Database "${dbName}" doesn't contain "test" in its name`,
hint: 'Use a database name like "nightscout_test" or set TEST_SAFETY_REQUIRE_TEST_DB=false'
});
} else if (isTestDatabaseName(dbName)) {
console.log(`[SAFETY] ✅ Database name "${dbName}" looks like a test database`);
}
// Check 2: Entry count threshold
const maxEntries = parseInt(process.env.TEST_SAFETY_MAX_ENTRIES || String(DEFAULT_MAX_ENTRIES), 10);
if (maxEntries > 0 && ctx.store && ctx.store.db) {
try {
// Access entries collection directly via store
const entriesCol = ctx.store.db.collection('entries');
// Use limit+1 pattern for efficiency - we only need to know if it exceeds threshold
const count = await entriesCol.countDocuments({}, {
limit: maxEntries + 1,
maxTimeMS: 5000 // Don't hang on slow connections
});
if (count > maxEntries) {
errors.push({
check: 'Entry Count',
message: `Database has ${count}+ entries (threshold: ${maxEntries})`,
hint: `This looks like a production database. Set TEST_SAFETY_MAX_ENTRIES=${count + 100} to override`
});
} else {
console.log(`[SAFETY] ✅ Database has ${count} entries (threshold: ${maxEntries})`);
}
} catch (err) {
warnings.push({
check: 'Entry Count',
message: `Could not count entries: ${err.message}`,
hint: 'Entry count check skipped'
});
}
} else if (maxEntries === 0) {
console.log('[SAFETY] ⚠️ Entry count check disabled (TEST_SAFETY_MAX_ENTRIES=0)');
}
// Report warnings
warnings.forEach(w => {
console.warn(`[SAFETY] ⚠️ ${w.check}: ${w.message}`);
});
// Report errors and fail
if (errors.length > 0) {
console.error('\n' + '='.repeat(70));
console.error('🛡️ PRODUCTION SAFETY CHECK ACTIVATED');
console.error('='.repeat(70));
console.error('\nThis database appears to contain real data.');
console.error('Running the test suite WILL DELETE all data in this database.');
console.error('\nThis safety check exists to prevent accidental destruction of');
console.error('production data. If this is truly a test database, you can override.\n');
errors.forEach((e, i) => {
console.error(`${i + 1}. ${e.check}:`);
console.error(` ${e.message}`);
console.error(` 💡 ${e.hint}\n`);
});
console.error('Override options:');
console.error(' • Set TEST_SAFETY_MAX_ENTRIES to a higher value (e.g., 1000)');
console.error(' • Set TEST_SAFETY_REQUIRE_TEST_DB=false to allow any DB name');
console.error(' • Set TEST_SAFETY_SKIP=true to bypass ALL checks (dangerous!)');
console.error('='.repeat(70) + '\n');
throw new Error('Production safety check activated: ' + errors.map(e => e.check).join(', '));
}
console.log('[SAFETY] ✅ All production safety checks passed');
}
/**
* Synchronous pre-flight check (no DB required)
* Run this before booting the application
*/
function preflightCheck() {
// Check NODE_ENV
if (process.env.NODE_ENV !== 'test') {
console.error('\n❌ SAFETY ERROR: NODE_ENV must be "test" to run tests.');
console.error(' Current value: ' + (process.env.NODE_ENV || '(not set)'));
console.error(' Tests use deleteMany({}) which could destroy production data.');
console.error(' Fix: Use "npm test" which loads my.test.env, or set NODE_ENV=test\n');
process.exit(1);
}
}
module.exports = {
checkProductionSafety,
preflightCheck,
extractDbName,
isTestDatabaseName,
DEFAULT_MAX_ENTRIES
};