Working with awkward key files (secret-management)

I’m writing my first non-trivial derivation/flake/nixosModule and have come across a very specific problem of which I am not sure if nix can solve it:

My service will use meilisearch under the hood. This, in turn, exists as a service in nixpkgs. The thing is, I don’t want to expose the implementation detail “meilisearch” in my service. However, I do want the user to provide a keyFile, which will be used to secure meilisearch. The problem: meilisearch expects this kind of keyfile: MEILI_MASTER_KEY=my_secret_key. So either my service has a breaking change when I decide to replace meilisearch, or I need a way to transform a simpler keyFile into this specific one, without the secret being leaked to the /nix/store.

Can this be done?

Something like this could do it:

{ pkgs, ... }: {
  services.meilisearch.masterKeyEnvironmentFile = "/var/run/secrets/meili-env";

  systemd.services.meili-key-setup = {
    wantedBy = [ "meilisearch.service" ];
    before = [ "meilisearch.service" ];
    script = ''
      echo "MEILI_MASTER_KEY=$(cat ${config.<your-service>.keyFile})" > /var/run/secrets/meili-env
    '';
    serviceConfig.UMask = "077";
  };
}

I’m pretty sure echo in bash won’t leak the secret, but double check.

Uuuuuhhh, that’s very nice, thank you. Quick question: Would it be required to change the file mode on the generated file to something like 600?

Probably can’t hurt, unsure if /var/run/secrets has any magic to ensure that already. Probably best to do that with a umask in case something crashes or such, I’ve added that to my original answer.

1 Like

(/var/run is a symlink to /run btw).

The problem with this solution is that /run can be swapped to disk, which may or may not be insecure depending on your setup. This is usually where systemd credentials would come in handy, but I’m actually struggling to see how to use it in this case, given that you need to make modifications to the file…

EDIT: I guess you used /run/secrets, which I guess must be an agenix thing or something? That’s not there on my system. NixOS does set up /run/keys though, which uses ramfs which doesn’t swap.

1 Like