Do not delete /tmp or /home directories


ID: go-best-practices/prevent-delete-directories

Language: Go

Severity: Info

Category: Best Practices


Using os.RemoveAll() with os.TempDir() can be considered to be bad practice for the following reasons:

  1. Potential loss of data: os.RemoveAll() recursively removes all files and directories within a given directory. Using os.TempDir() as the argument means that all files and directories within the system’s temporary directory are to be deleted. This can result in the unintended deletion of important files or data that other processes or applications rely on.
  2. Shared resource interference: The system’s temporary directory is often shared among different applications and processes. Using os.RemoveAll() with os.TempDir() can interfere with other running programs or cause conflicts with files/directories used by other components. This can lead to a loss of data integrity or unexpected behavior in the system.
  3. Security risks: The system’s temporary directory often contains files that have not yet been processed or cleaned up by other applications or services. By using os.RemoveAll() with os.TempDir(), there is a possibility of deleting sensitive or temporary files that are actively being used. This can introduce security vulnerabilities or disrupt the functioning of other processes relying on those files.
  4. Lack of control and specificity: Using os.RemoveAll() with os.TempDir() removes all contents of the system’s temporary directory without discretion. It does not allow for selective deletion or filtering based on specific criteria. This lack of control can lead to unintended consequences and the removal of files or directories that should be preserved.

To avoid these issues, it is recommended to avoid using os.RemoveAll() directly with os.TempDir(). If you need to delete specific files or directories within the temporary directory, it is better to identify and target them explicitly. Be cautious when deleting files or directories and ensure that the operation is performed safely and in a controlled manner. If necessary, consider implementing granular file management or cleanup logic specific to your application’s needs, rather than relying on a blanket directory removal approach.

Non-Compliant Code Examples

func main() {
    x := os.TempDir()
	defer os.RemoveAll(x) //@ diag(`deletes the user's entire temporary directory`)


Compliant Code Examples

func main() {
    x := os.TempDir()
    x = filepath.Join(x, "foo")
	defer os.RemoveAll(x) //@ diag(`deletes the user's entire temporary directory`)

} jetbrains

Seamless integrations. Try Datadog Code Analysis