These minimum restrictions should be applied when handling file uploads:

Also the size of the uploaded file should be limited to prevent denial of service attacks. This requirement is covered by the rule S5693.

Noncompliant Code Example

formidable module:

const Formidable = require('formidable');

const form = new Formidable(); // Noncompliant, this form is not safe
form.uploadDir = ""; // because upload dir is not defined (by default os temp dir: /var/tmp or /tmp)
form.keepExtensions = true; // and file extensions are kept

multer (Express.js middleware) module:

const multer = require('multer');

let diskStorage = multer.diskStorage({ // Noncompliant: no destination specified
  filename: (req, file, cb) => {
    const buf = crypto.randomBytes(20);
    cb(null, buf.toString('hex'))
  }
});

// This upload is not safe as no destination specified, /var/tmp or /tmp will be used
let diskupload = multer({
  storage: diskStorage,
});

Compliant Solution

formidable module:

const Formidable = require('formidable');

const form = new Formidable(); // Compliant
form.uploadDir = "./uploads/";
form.keepExtensions = false;

multer (Express.js middleware) module:

const multer = require('multer');

let diskStorage = multer.diskStorage({  // Compliant
  filename: (req, file, cb) => {
    const buf = crypto.randomBytes(20);
    cb(null, buf.toString('hex'))
  },
  destination: (req, file, cb) => {
    cb(null, './uploads/')
  }
});

let diskupload = multer({
  storage: diskStorage,
});

See