Tuesday 14 March 2017

Node as non su, use fs

I'm using a VPS with Debian 8 and:
node v7.7.1
npm 4.1.2
Node was installed only for the non super user "nodejs".
The user "nodejs" starts some instances of express servers using PM2.
Among the tasks of this particular express server is that to receive uploaded files and create directories according to what is needed using fs.
When I try to upload files however I receive this error:

{
  "errno": -2,
  "code": "ENOENT",
  "syscall": "mkdir",
  "path": "./public/public/backgroundImage_1482260147312"
}

The double "public" is intentional.
It goes without saying that the server works as intended locally on my OSX machine as my normal user, but obviously the privileges for a OSX user are not the same.
The express server is located in the /var/www/path/to/installation directory.
Since there are only express servers (there is no Apache or Nginx) the permission are 700 for node:node.
Permissions were given as:

chown -R nodejs:nodejs /var/www
chmod -R 700 /var/www

Checking "top" I confirm that the express installation are run as the nodejs user.

So, if the directory and all subdirectory have permissions set to 700 for the correct user, how come that nodejs is unable to create files, even if not su?

The only function that uses "mkdir", and therefore the one I suspect creating this error is:

const publicDir = path.join(__dirname, "../public/public/");

createDirectory = (id) => {
  return new Promise(
    (resolve, reject) => {
      if (!id || !id.match(/^[a-zA-Z]+_[0-9]+$/g)) {
        reject("Not valid ID");
      }
      if (!fs.existsSync(publicDir + id)) {
        fs.mkdir(publicDir + id,
          (err) => {
            if (err) {
              reject(err);
            } else {
              resolve();
            }
          }
        );
      // if the directory already exists
      } else {
        resolve();
      }
    }
  );
},

I already know about "existsSync", please keep it out of topic.

The directories "public" and "public/public" already exists.
In fact there are other directories besides "backgroundImage_1482260147312" in public/public that I had created manually during development.
I even tried to create "backgroundImage_1482260147312" manually and give permissions, but the error is the same.



via Netscreever

No comments:

Post a Comment