Skip to content

Commit 8b85eaa

Browse files
committed
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.
1 parent 0260572 commit 8b85eaa

File tree

1 file changed

+15
-11
lines changed

1 file changed

+15
-11
lines changed

lib/config/core.js

+15-11
Original file line numberDiff line numberDiff line change
@@ -31,10 +31,8 @@ enumerable: true })
3131

3232
exports.validate = validate
3333

34-
var myUid = process.env.SUDO_UID !== undefined
35-
? process.env.SUDO_UID : (process.getuid && process.getuid())
36-
var myGid = process.env.SUDO_GID !== undefined
37-
? process.env.SUDO_GID : (process.getgid && process.getgid())
34+
var myUid = process.getuid && process.getuid()
35+
var myGid = process.getgid && process.getgid()
3836

3937
var loading = false
4038
var loadCbs = []
@@ -283,15 +281,21 @@ Conf.prototype.save = function (where, cb) {
283281
done(null)
284282
})
285283
} else {
286-
mkdirp(path.dirname(target.path), function (er) {
284+
// we don't have to use inferOwner here, because gentle-fs will
285+
// mkdir with the correctly inferred ownership. Just preserve it.
286+
const dir = path.dirname(target.path)
287+
mkdirp(dir, function (er) {
287288
if (er) return then(er)
288-
fs.writeFile(target.path, data, 'utf8', function (er) {
289+
fs.stat(dir, (er, st) => {
289290
if (er) return then(er)
290-
if (where === 'user' && myUid && myGid) {
291-
fs.chown(target.path, +myUid, +myGid, then)
292-
} else {
293-
then()
294-
}
291+
fs.writeFile(target.path, data, 'utf8', function (er) {
292+
if (er) return then(er)
293+
if (myUid === 0 && (myUid !== st.uid || myGid !== st.gid)) {
294+
fs.chown(target.path, st.uid, st.gid, then)
295+
} else {
296+
then()
297+
}
298+
})
295299
})
296300
})
297301
}

0 commit comments

Comments
 (0)