Private Git Submodule Authentication and Nixos Rebuilds

A Quick Tip

If you are using a private git submodule as an input to a Nix flake and then use that input as part of a NixOS configuration you may end up seeing authentication errors when sudo nixos-rebuild switch is invoked. This is because in a clean working tree, Nix will attempt to resolve those submodules to their Git upstreams and check them out from there. sudo nixos-rebuild switch may drop your environment variable SSH_AUTH_SOCK and thus the private submodule can’t be checked out as your user’s ssh-agent can’t provide the credentials for authentication.

To resolve this you need sudo to include your user’s SSH_AUTH_SOCK environment variable into its execution environment.

Instead of using a plain sudo nixos-rebuild switch, use sudo --preserve-env=SSH_AUTH_SOCK nixos-rebuild switch. That should resolve any authentication issues (assuming your ssh-agent’s auth is valid for the upstream where the Git submodule exists of course).

You could also set this globally in your NixOS configuration without needing to specify --preserve-env for sudo every time via:

{...}
{
  security.sudo.extraConfig = ''
    Defaults env_keep+=SSH_AUTH_SOCK
  '';
}

See sudoers(8) for env_keep.


I ran into this issue and it sent me on a witch hunt to figure out what was wrong. I’m very interested as to why you don’t need to send along SSH_AUTH_SOCK to sudo when the working tree is dirty. My best guess is that the private submodule gets resolved as a path flake reference when the working tree is dirty and otherwise it gets treated as a full on git reference when it’s clean. So Nix doesn’t need authentication for the private repository in the first case (treated as a real path), but does when the input is coerced into a git reference. Annoying.

Anyhow — my hope is I’ve saved someone out there a small headache.