/** * Upload report.json to MongoDB (official driver). * * Install: npm install mongodb * * Run (self-hosted Mongo on Ubuntu host 10.200.25.150): * MONGODB_URI="mongodb://uploader:PASSWORD@10.200.25.150:27017/CICD?authSource=admin&directConnection=true&appName=trivy-uploader" \ * node scripts/upload-report-to-mongodb.js * * Optional env: * REPORT_PATH=../report.json * DB_NAME=CICD * COLLECTION=trivy_reports */ const fs = require("fs"); const path = require("path"); const { MongoClient } = require("mongodb"); const PLACEHOLDER_PWD = "CHANGE_ME_STRONG"; const DEFAULT_URI ="mongodb://uploader:STRONG_UPLOADER_PWD@10.200.25.150:27017/CICD?authSource=admin"; const uri = process.env.MONGODB_URI || DEFAULT_URI; const reportPath = path.resolve( process.env.REPORT_PATH || path.join(__dirname, "..", "report.json") ); const dbName = process.env.DB_NAME || "CICD"; const collectionName = process.env.COLLECTION || "trivy_reports"; function maskUri(u) { return u.replace(/(:\/\/[^:]+:)[^@]+(@)/, "$1****$2"); } async function main() { if (!uri) { console.error("Set MONGODB_URI to your MongoDB connection string."); process.exit(1); } if (uri.includes(PLACEHOLDER_PWD)) { console.error( `Refusing to run: MONGODB_URI is not set and the default URI still has the placeholder password "${PLACEHOLDER_PWD}".\n` + "Export MONGODB_URI before running, e.g.:\n" + " export MONGODB_URI='mongodb://uploader:REAL_PASSWORD@10.200.25.150:27017/CICD?authSource=admin&directConnection=true&appName=trivy-uploader'" ); process.exit(1); } console.log("Using URI:", maskUri(uri)); if (!fs.existsSync(reportPath)) { console.error("Report file not found:", reportPath); process.exit(1); } const raw = fs.readFileSync(reportPath, "utf8"); const doc = JSON.parse(raw); // Single BSON document limit is 16 MB; add size hint const approxBytes = Buffer.byteLength(raw, "utf8"); if (approxBytes > 15 * 1024 * 1024) { console.warn( `Warning: JSON is ~${(approxBytes / 1024 / 1024).toFixed(2)} MB; MongoDB limit is 16 MB per document. Consider splitting Results.` ); } const client = new MongoClient(uri); try { await client.connect(); const coll = client.db(dbName).collection(collectionName); const payload = { ...doc, _uploadedAt: new Date(), _sourceFile: path.basename(reportPath), }; const result = await coll.insertOne(payload); console.log("Inserted _id:", result.insertedId.toString()); } finally { await client.close(); } } main().catch((err) => { console.error(err); process.exit(1); });