From 8b85eaa47da3abaacc90fe23162a68cc6e1f0404 Mon Sep 17 00:00:00 2001 From: isaacs Date: Thu, 15 Aug 2019 11:13:26 -0700 Subject: [PATCH] config: save files with inferred ownership Don't use SUDO_UID and SUDO_GID. Just make the file match the folder it's being written into. The vast majority of the time, this will be the user's home directory, but if it's not, then we should not leave a user-owned file in a root-owned location. And, if running as root without SUDO_UID/SUDO_GID environs, but putting a config file in the user's home dir, then it's quite rude to leave it root-owned. --- lib/config/core.js | 26 +++++++++++++++----------- 1 file changed, 15 insertions(+), 11 deletions(-) diff --git a/lib/config/core.js b/lib/config/core.js index 18658842175f0..36420b3450163 100644 --- a/lib/config/core.js +++ b/lib/config/core.js @@ -31,10 +31,8 @@ enumerable: true }) exports.validate = validate -var myUid = process.env.SUDO_UID !== undefined - ? process.env.SUDO_UID : (process.getuid && process.getuid()) -var myGid = process.env.SUDO_GID !== undefined - ? process.env.SUDO_GID : (process.getgid && process.getgid()) +var myUid = process.getuid && process.getuid() +var myGid = process.getgid && process.getgid() var loading = false var loadCbs = [] @@ -283,15 +281,21 @@ Conf.prototype.save = function (where, cb) { done(null) }) } else { - mkdirp(path.dirname(target.path), function (er) { + // we don't have to use inferOwner here, because gentle-fs will + // mkdir with the correctly inferred ownership. Just preserve it. + const dir = path.dirname(target.path) + mkdirp(dir, function (er) { if (er) return then(er) - fs.writeFile(target.path, data, 'utf8', function (er) { + fs.stat(dir, (er, st) => { if (er) return then(er) - if (where === 'user' && myUid && myGid) { - fs.chown(target.path, +myUid, +myGid, then) - } else { - then() - } + fs.writeFile(target.path, data, 'utf8', function (er) { + if (er) return then(er) + if (myUid === 0 && (myUid !== st.uid || myGid !== st.gid)) { + fs.chown(target.path, st.uid, st.gid, then) + } else { + then() + } + }) }) }) }