Why must plaintext secrets stay out of the Store?#
In NixOS, configuration sources and files referenced by builds may be copied into /nix/store.
/nix/storeis world-readable.- Any ordinary user can find your plaintext API key in
/nix/store.
A modern solution: sops-nix#
sops-nix provides runtime secret decryption for NixOS and Home Manager.
1. How it works
- Encrypt
secrets.yamlusing age public-key recipients or another method supported by SOPS. The corresponding private keys are used for decryption and kept outside the Store and public repositories. - In Nix, reference only the encrypted file.
- The NixOS module decrypts secrets into
/run/secrets/during activation or a service phase. Use owner/group/mode to control which services or users can read them.
2. Practical steps
- Install the
sopscommand-line tool. - Generate an age key.
- Integrate it into the configuration:
# flake.nix 加入 inputs.sops-nix # configuration.nix { inputs, ... }: { imports = [ inputs.sops-nix.nixosModules.sops ]; sops.defaultSopsFile = ./secrets.yaml; sops.age.sshKeyPaths = [ "/etc/ssh/ssh_host_ed25519_key" ]; # 定义一个密钥 sops.secrets."github_token" = {}; }
Another option: agenix#
agenix is lighter-weight than sops-nix. It manages secrets as individual age files and supports age recipient types, including supported SSH keys.
Using secrets in Home Manager#
The NixOS module can decrypt secrets for system services, while user configuration references only runtime file paths and explicitly sets read permissions. sops-nix also provides a Home Manager module that uses a user service to decrypt secrets into a runtime directory. User services that depend on those secrets must be ordered correctly. Do not use builtins.readFile to insert decrypted plaintext into Nix configuration, and do not put secret values in home.sessionVariables. Prefer the application’s credential-file options.
Preparing to publish configuration#
If you plan to open-source your Nix configuration, the first step is to remove all passwords and tokens and introduce sops-nix.
Summary#
- Do not write plaintext passwords in
.nixfiles. - Use appropriate encryption recipients and protect the decryption private keys.
- Ensure that private keys and original plaintext never enter Git, the Store, or logs.
.gitignorecannot remove leaked content from history that has already been tracked.
References & further reading
- Home Manager manual ↗
- Home Manager command source ↗
- Home Manager file-option source ↗
- Upstream sops-nix documentation ↗
- Upstream agenix documentation ↗
Adapted from technical notes. Examples use generic names.
Continue along a reading path
Home Manager: managing user configuration
- 01Home Manager integration and modular configuration
- 02Configuring a terminal environment with Home Manager
- 03Desktop and theme configuration with Home Manager
- 04Home Manager files and symbolic links
- 05Secrets management with Home Manager and NixOS
- 06A tutorial on user-level configuration with Home Manager