Search code examples
javatomcatpermissionsdelete-filewindows-server-2012-r2

Able to delete a file without permissions


Why am I able to delete a file in my Java code despite the Tomcat user not having the deletion permissions?

My server is running the following code, which deletes and recreates a file if it exists:

File fileCSV = new File(filePath);
    try {
        if (fileCSV.exists()) {
            fileCSV.delete();
        }
        fileCSV.createNewFile();
    } catch (IOException ex) {
        throw new FooImportException("Error creating new file");
    }

It is able to delete the file despite the user used by the server not having deletion permissions - only read and write permissions.

enter image description here

I am certain that these are the relevant permissions, as the code fails on the file creation line without the "Create files / Write data" permissions. However, it does not fail on the deletion line when lacking the "Delete" permission. What might be the reasoning for this?


Solution

  • According to the JavaDocs for File#delete

    public boolean delete()
    Deletes the file or directory denoted by this abstract pathname. If this pathname denotes a directory, then the directory must be empty in order to be deleted.

    Note that the Files class defines the delete method to throw an IOException when a file cannot be deleted. This is useful for error reporting and to diagnose why a file cannot be deleted.

    Returns:
    true if and only if the file or directory is successfully deleted; false otherwise
    Throws:
    SecurityException - If a security manager exists and its SecurityManager.checkDelete(java.lang.String) method denies delete access to the file

    So, File#delete does not actually throw an Exception when the file can't be deleted, but instead returns a boolean based on the success of the operation.

    If the Exception is important to you, then you should use Files#delete instead.

    It's important to note - this only solves the question of "why does it not fail" based on the available code, not the question of "would it fail" based on the available file permissions