Prevent unauthorized access to temporary files
File.mkdir("/tmp/my_temp_dir")
File.write!({"/tmp/my_temp_dir", "my_temp_file"}, "sensitive data")
This code is vulnerable because it creates a temporary file in the default '/tmp' directory and writes sensitive data into it. Any other user on the same system can read the file and potentially misuse the data.
File.mkdir_p!({:ok, path} = File.mktemp(System.tmp_dir(), "my_temp_dir"))
File.chmod!(path, 0o600)
File.write!({path, "my_temp_file"}, "sensitive data")
This secure code example creates a temporary directory in a way that respects the operating system’s conventions. It then sets the file permissions to 0600, making the file only readable and writable by the owner. Finally, it writes the sensitive data to the file.