import clear from 'clear'; import { spawn, ChildProcess } from 'child_process'; // Import helpers import showChooser from '../helpers/showChooser'; import print from '../helpers/print'; import exec from '../helpers/exec'; import config from '../helpers/config'; import prompt from '../helpers/prompt'; import waitForPort from '../helpers/waitForPort'; import portIsFree from '../helpers/portIsFree'; // Import shared types import Deployment from '../types/Deployment'; // Import constants import LOCAL_DB_PORT from '../constants/LOCAL_DB_PORT'; import BASTION_TTL_ENV_VAR from '../constants/BASTION_TTL_ENV_VAR'; import DEFAULT_BASTION_TTL_MINUTES from '../constants/DEFAULT_BASTION_TTL_MINUTES'; import MAX_BASTION_TTL_MINUTES from '../constants/MAX_BASTION_TTL_MINUTES'; // The active tunnel process (caccl-deploy connect), if any. It persists // through multiple connect operations and main menu returns. It is only cleaned up when the wizard exits. let tunnel: { child: ChildProcess, app: string } | null = null; // Register the exit cleanup only once let exitHandlerRegistered = false; const registerExitHandler = () => { if (exitHandlerRegistered) { return; } exitHandlerRegistered = true; process.on('exit', () => { if (tunnel && tunnel.child.exitCode === null) { tunnel.child.kill('SIGINT'); } }); }; /** * Connect/tunnel into a db via an ephemeral bastion (provisioned by * `caccl-deploy connect`) * @author Gabe Abrams * @author Jay Luker * @param deployment the currently selected deployment */ const connectToDatabase = async (deployment: Deployment) => { // Get dbName const { dbName } = config; // Make sure the deployment has a db if (!dbName) { clear(); print.title('No Database!'); console.log(''); console.log('This deployment does not have a database.'); console.log(''); print.enterToContinue(); return; } // Destructure const { name, app, profile, } = deployment; registerExitHandler(); clear(); print.title('Connect to database'); console.log(''); const stackName = `CacclDeploy-${app}`; // > Allow for alternate stack names // > Arn of the secretsmanager secret where the db master password is stored const dbPasswordSecretCommand = `aws cloudformation describe-stacks --stack-name ${stackName} --query "Stacks[].Outputs[?ExportName=='${stackName}-db-password-secret-arn'].OutputValue" --profile ${profile} --output text`; console.log(`\nGetting DB Password Secret:\n${dbPasswordSecretCommand}\n`); const dbPasswordSecret = exec( dbPasswordSecretCommand, false, ).trim(); console.log(`> ${dbPasswordSecret}`); // > Get DB password const dbPasswordCommand = `aws secretsmanager get-secret-value --secret-id ${dbPasswordSecret} --query 'SecretString' --profile ${profile} --output text`; console.log(`\nGetting DB Password:\n${dbPasswordCommand}\n`); const dbPassword = exec( dbPasswordCommand, false, ).trim(); console.log('> [password retrieved]'); // Reuse the existing tunnel if it's still alive and for the same app. const tunnelIsLive = ( tunnel && tunnel.app === app && tunnel.child.exitCode === null && await waitForPort(LOCAL_DB_PORT, { timeoutMs: 2000 }) ); if (!tunnelIsLive) { // possible dead ssm session: tunnel looks ok but socket not available if (tunnel && tunnel.child.exitCode === null) { tunnel.child.kill('SIGINT'); tunnel = null; } // Kill orphaned sessions on the local port (e.g. from older wizard // versions or a crashed run), but only if something is actually // occupying the port const portBusy = !(await portIsFree(LOCAL_DB_PORT)); if (portBusy) { console.log('\nEnter sudo to cleanup existing sessions:'); exec( `sudo lsof -ti tcp:${LOCAL_DB_PORT} | xargs -r kill`, true, ); } clear(); print.title('Connect to database'); console.log(''); // How long the bastion should live, overridable via the environment let ttlMinutes = DEFAULT_BASTION_TTL_MINUTES; const ttlOverride = (process.env[BASTION_TTL_ENV_VAR] ?? '').trim(); if (ttlOverride) { if ( /^\d+$/.test(ttlOverride) && Number(ttlOverride) > 0 && Number(ttlOverride) <= MAX_BASTION_TTL_MINUTES ) { ttlMinutes = Number(ttlOverride); } else { console.log(`Ignoring ${BASTION_TTL_ENV_VAR}="${ttlOverride}": expected a whole number of minutes between 1 and ${MAX_BASTION_TTL_MINUTES} (24 hours).`); } } console.log(`\nThe bastion will self-terminate after ${ttlMinutes} minutes (set ${BASTION_TTL_ENV_VAR} to change this).`); // Establish the tunnel via caccl-deploy, which provisions an ephemeral // bastion and runs an SSM port-forwarding session in the foreground console.log('\nEstablishing tunnel via caccl-deploy connect (an ephemeral bastion will be provisioned; this usually takes < 1 minute)...\n'); const child = spawn( './node_modules/.bin/caccl-deploy', [ 'connect', '--app', app, '--profile', profile, '--service', 'docdb', '--local-port', String(LOCAL_DB_PORT), '--ttl', String(ttlMinutes * 60), ], { stdio: ['ignore', 'pipe', 'pipe'] }, ); let childOutput = ''; child.stdout?.on('data', (data) => { childOutput += data; process.stdout.write(data); }); child.stderr?.on('data', (data) => { childOutput += data; process.stderr.write(data); }); // spawn failures (e.g. ENOENT) surface only via the error event and // leave exitCode null, so track them separately to fail fast let spawnError: Error | null = null; child.on('error', (err) => { spawnError = err; const message = `\nFailed to start caccl-deploy: ${err.message}\n`; childOutput += message; process.stderr.write(message); }); const tunnelUp = await waitForPort(LOCAL_DB_PORT, { // caccl-deploy itself waits up to 300s for the bastion's SSM agent plus // 60s for the tunnel, so outlast it rather than killing a connect that // is still legitimately working timeoutMs: 360000, giveUp: () => { return spawnError !== null || child.exitCode !== null; }, }); if (!tunnelUp) { if (child.exitCode === null) { child.kill('SIGINT'); } console.log('\nThe tunnel could not be established.'); if (childOutput.includes('AccessDenied')) { console.log('This looks like a permissions issue: ask for the TempBastionUserAccess IAM policy to be attached to your user/role.'); } console.log('Scroll up for errors or more details.'); console.log(''); await print.enterToContinue(); return; } tunnel = { child, app }; } // Finished console.log('\nTunnel is up! It closes when the wizard exits or the bastion reaches its TTL.'); /** * Run a mongo tooling command without letting a failure crash the wizard * @param command the shell command to run * @returns true if the command succeeded */ const runMongoCommand = (command: string): boolean => { try { exec(command, true); return true; } catch (err) { console.log('\nThe command failed.'); console.log('If the error above says "connection refused" the tunnel has probably died (SSM sessions are terminated after ~60 idle minutes); return to the main menu and re-enter this screen to re-establish it.'); return false; } }; // Choose an operation const { tag } = showChooser({ question: 'Operation:', options: [ { description: 'Robo 3T Setup Instructions', tag: 'R', }, { description: 'Studio 3T Setup Instructions', tag: 'S', }, { description: 'Export Collection', tag: 'E', }, { description: 'Insert Items in Collection', tag: 'I', }, { description: 'Upsert Items in Collection', tag: 'U', }, { description: 'Back to Main Menu', tag: 'B', }, ], title: 'Choose an operation:', }); // Robo 3T if (tag === 'R') { clear(); print.title('Robo 3T Setup Instructions'); console.log( [ '1. Open Robo 3T, create a new connection', '2. Fill out the "Connection" tab:', ` Name = ${name}`, ` Address = localhost`, ` Port = ${LOCAL_DB_PORT}`, '3. Fill out the "Authentication" tab:', ' Check the "Perform authentication" box', ` Database = ${dbName}`, ` Username = root`, ` Password = ${dbPassword}`, '4. Fill out the "SSL" tab:', ' Check the "Use SSL protocol" box', ' Authentication Method = Self-signed certificate', ' Check the "Advanced Options" box', ' Invalid Hostnames = Allowed', '5. Click "Test"', '6. If the test is successful, click "Save"', ].join('\n'), ); console.log(''); print.enterToContinue(); } // Studio 3T if (tag === 'S') { clear(); print.title('Studio 3T Setup Instructions'); console.log( [ '1. Open Studio 3T, create a new connection', '2. Choose "Manually configure my connection settings", then click "Next"', `3. Set the "Connection name" to ${name}`, '4. Fill out the "Server" tab:', ' Connection Type = Standalone', ' Address = localhost', ` Port = ${LOCAL_DB_PORT}`, '5. Fill out the "Authentication" tab:', ' Authentication Mode = Legacy', ` Username = root`, ` Password = ${dbPassword}`, ` Authentication DB = ${dbName}`, '6. Fill out the "SSL" tab:', ' Check the "Use SSL protocol to connect" box', ' Check the "Allow invalid hostnames" box', '5. Click "Test Connection"', '6. If the test is successful, click "Save"', ].join('\n'), ); console.log(''); await print.enterToContinue(); } // Export Collection if (tag === 'E') { clear(); print.title('Export Collection'); // Get the collection name const collectionName = prompt('Collection Name: '); const outFilename = `${collectionName}-${new Date().toISOString()}.json`; console.log(`\nExporting collection to ${outFilename}\n`); if (runMongoCommand( `mongoexport --collection=${collectionName} --host="localhost:${LOCAL_DB_PORT}" --db=${dbName} --out="${outFilename}" --username=root --password=${dbPassword} --ssl --sslAllowInvalidHostnames --sslAllowInvalidCertificates`, )) { console.log(`\nExported to ${outFilename}\n`); } await print.enterToContinue(); } // Insert Items in Collection if (tag === 'I') { clear(); print.title('Insert Items in Collection'); // Get the collection name const collectionName = prompt('Collection Name: '); console.log('\nCreate a JSON file (one entry per line), drop the file here, then press enter.'); const jsonPath = prompt('Path: ').trim(); console.log(`\nInserting items into collection "${collectionName}"\n`); if (runMongoCommand( `mongoimport --collection=${collectionName} --host="localhost:${LOCAL_DB_PORT}" --db=${dbName} --username=root --password=${dbPassword} --ssl --sslAllowInvalidHostnames --sslAllowInvalidCertificates --file="${jsonPath}"`, )) { print.title('Inserted Successfully'); } await print.enterToContinue(); } // Upsert Items in Collection if (tag === 'U') { clear(); print.title('Upsert Items in Collection'); // Get the collection name const collectionName = prompt('Collection Name: '); console.log('\nCreate a JSON file (one entry per line), drop the file here, then press enter.'); const jsonPath = prompt('Path: ').trim(); console.log(`\nUpserting items into collection "${collectionName}"\n`); if (runMongoCommand( `mongoimport --upsert --collection=${collectionName} --host="localhost:${LOCAL_DB_PORT}" --db=${dbName} --username=root --password=${dbPassword} --ssl --sslAllowInvalidHostnames --sslAllowInvalidCertificates --file="${jsonPath}"`, )) { print.title('Upsert Successful'); } await print.enterToContinue(); } }; export default connectToDatabase;