diff --git a/modules/sops/default.nix b/modules/sops/default.nix index b7e1e2d..d163473 100644 --- a/modules/sops/default.nix +++ b/modules/sops/default.nix @@ -140,7 +140,6 @@ in { example = "/var/lib/sops-nix/key.txt"; description = '' Path to age key file used for sops decryption. - Setting this to a non-null value causes the ssh keys to be ignored. ''; }; @@ -159,7 +158,6 @@ in { default = if config.services.openssh.enable then map (e: e.path) (lib.filter (e: e.type == "ed25519") config.services.openssh.hostKeys) else []; description = '' Paths to ssh keys added as age keys during sops description. - This setting is ignored when the keyFile is set to a non-null value. ''; }; }; diff --git a/pkgs/sops-install-secrets/main.go b/pkgs/sops-install-secrets/main.go index 0d847d8..b098734 100644 --- a/pkgs/sops-install-secrets/main.go +++ b/pkgs/sops-install-secrets/main.go @@ -519,14 +519,7 @@ func importSSHKeys(keyPaths []string, gpgHome string) error { return nil } -func importAgeSSHKeys(keyPaths []string, ageFilePath string) error { - ageFile, err := os.OpenFile(ageFilePath, os.O_WRONLY|os.O_CREATE, 0600) - if err != nil { - return fmt.Errorf("Cannot create '%s': %w", ageFilePath, err) - } - defer ageFile.Close() - fmt.Fprintf(ageFile, "# generated by sops-nix at %s\n", time.Now().Format(time.RFC3339)) - +func importAgeSSHKeys(keyPaths []string, ageFile os.File) error { for _, p := range keyPaths { // Read the key sshKey, err := ioutil.ReadFile(p) @@ -645,15 +638,38 @@ func installSecrets(args []string) error { os.Setenv("GNUPGHOME", manifest.GnupgHome) } - if manifest.AgeKeyFile != "" { - os.Setenv("SOPS_AGE_KEY_FILE", manifest.AgeKeyFile) - } else if len(manifest.AgeSshKeyPaths) != 0 { + // Import age keys + if len(manifest.AgeSshKeyPaths) != 0 || manifest.AgeKeyFile != "" { keyfile := filepath.Join(manifest.SecretsMountPoint, "age-keys.txt") - err = importAgeSSHKeys(manifest.AgeSshKeyPaths, keyfile) - if err != nil { - return err - } os.Setenv("SOPS_AGE_KEY_FILE", keyfile) + // Create the keyfile + ageFile, err := os.OpenFile(keyfile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600) + if err != nil { + return fmt.Errorf("Cannot create '%s': %w", keyfile, err) + } + defer ageFile.Close() + fmt.Fprintf(ageFile, "# generated by sops-nix at %s\n", time.Now().Format(time.RFC3339)) + + // Import SSH keys + if len(manifest.AgeSshKeyPaths) != 0 { + err = importAgeSSHKeys(manifest.AgeSshKeyPaths, *ageFile) + if err != nil { + return err + } + } + // Import the keyfile + if manifest.AgeKeyFile != "" { + // Read the keyfile + contents, err := ioutil.ReadFile(manifest.AgeKeyFile) + if err != nil { + return fmt.Errorf("Cannot read keyfile '%s': %w", manifest.AgeKeyFile, err) + } + // Append it to the file + _, err = ageFile.WriteString(string(contents) + "\n") + if err != nil { + return fmt.Errorf("Cannot write key to age file: %w", err) + } + } } if err := decryptSecrets(manifest.Secrets); err != nil {