NodeJS:检测用户是否具有对文件的读取权限

NodeJS: Detecting if a user would have read access to a file

在 NodeJS 脚本 运行 作为 非根 user1,我如何检测指定的 user2 是否具有对磁盘上文件的读取权限?

请注意,root 访问权限对于此进程不可用,并且用户 2 的登录凭据不可用,因此 sudo -u user2 namei /path/to/file 之类的东西是不行的。

根据 Node.js 文档,fs.access() 可用于确定访问权限:

// Check if the file is readable.
fs.access(file, fs.constants.R_OK, (err) => {
  console.log(`${file} ${err ? 'is not readable' : 'is readable'}`);
});

这样 err 的存在表示该文件不可读。

这是我用来(不是特定于 NodeJS)来查找 user1 是否可以访问现有文件的解决方案:

  1. 文件是否全局可读?如果是,return true,否则转到 2
  2. 文件组是否可读?如果是则转3,否则转4
  3. user1 的 group 是否包含文件的组 ID?如果是,return true,否则转到 4
  4. 文件用户可读吗?如果是,转5,否则returnfalse
  5. 文件所有者是user1吗?如果是,returntrue,否则returnfalse

这会检查文件的所有常见访问权限和组限制。