npm ignores 'unsafe-perm' and 'user' params when running git as part of install

What I Wanted to Do

I am attempting to build a snap package that contains a nodejs package. The Snapcraft toolchain runs inside VMs where everything runs as root (and the VM is accessed via a sudo command). Since this could lead to errors when scripts are run during the npm install process, I enabled “unsafe-perm” in the npm config.

A package that I have a dependency on has a dependency that is pointed to a github repository, as opposed to a published npm package.

Since I had unsafe-perm=true set, I had expected that any git commands run as part of the npm install process would work fine.

What Happened Instead

The git command fails, with the following error message:

npm ERR! /usr/bin/git ls-remote -h -t ssh://git@github.com/substack/node-mkdirp.git
npm ERR! 
npm ERR! fatal: failed to stat '/root/demonstrate-unsafe-perm-git': Permission denied
npm ERR! 
npm ERR! exited with error code: 128

Monitoring the processes spawned by npm, I noticed that it was spawning the git processes with the uid of the sudoer, rather root. Setting user=0 did not fix this issue either.

Only by unsetting the SUDO_UID env var fixes the issue. If it is not possible to set git to use --unsafe-perm and --user, can you make another flag, such as --really-run-as-root?

Reproduction Steps

Easy to reproduce using this repository:

sudo su
cd ~
git clone https://github.com/NickZ/demonstrate-unsafe-perm-git.git
cd demonstrate-unsafe-perm-git
npm --unsafe-perm=true --user=0 i

Details

2019-10-08T17_46_49_026Z-debug.log (2.5 KB)

Platform Info

$ npm --versions
{ npm: '6.9.0',
  ares: '1.15.0',
  brotli: '1.0.7',
  cldr: '35.1',
  http_parser: '2.8.0',
  icu: '64.2',
  modules: '64',
  napi: '4',
  nghttp2: '1.39.2',
  node: '10.16.3',
  openssl: '1.1.1c',
  tz: '2019a',
  unicode: '12.1',
  uv: '1.28.0',
  v8: '6.8.275.32-node.54',
  zlib: '1.2.11' }

(Also tested with npm 6.4.1 and 6.11.3)

$ node -p process.platform
linux

Seems like I am bumping against this one also:

 $ sudo npm install -g --unsafe-perm 'tkurki/dnssd.js#advertisements-without-network'
npm ERR! code 128
npm ERR! Command failed: git clone --depth=1 -q -b advertisements-without-network git://github.com/tkurki/dnssd.js.git /root/.npm/_cacache/tmp/git-clone-4e061891
npm ERR! fatal: could not create leading directories of '/root/.npm/_cacache/tmp/git-clone-4e061891': Permission denied
$ npm --versions
{ npm: '6.12.0',
  ares: '1.10.1-DEV',
  cldr: '32.0',
  http_parser: '2.8.0',
  icu: '60.1',
  modules: '57',
  napi: '4',
  nghttp2: '1.33.0',
  node: '8.16.0',
  openssl: '1.0.2r',
  tz: '2017c',
  unicode: '10.0',
  uv: '1.23.2',
  v8: '6.2.414.77',
  zlib: '1.2.11' }