1

I am trying to write a unit test to test IOException handling in some code. I thought I would be able to create an IOException by removing permissions from a file and trying to delete it. But it looks like the file gets deleted anyway. 1st question is that the expected behavior? If so it seems like a big security hole to me. Second question is anyone have a suggestion on how to create an IOException on either of the two methods Files.delete() or commons.io FileUtils.deleteDirectory(). Following is the unit test code, I have tried both Files.delete on a file and FileUtils.deleteDirectory on a directory. In the latter case I get a fileNotFound exception. The second assertion always fails. Using a debugger I stopped the code and made sure the permissions on unwriteable were 000. I am running java 11 on Redhat 7.

   public void testIOException() throws IOException {
        binPath.toFile().mkdirs();
        Path unwriteablePath =  Paths.get(binPath.toString(), "unwriteable");
        Path writeablePath = Paths.get(binPath.toString(),"writeable");
        File unwriteable = unwriteablePath.toFile();
        unwriteable.createNewFile();
        File writeable = unwriteablePath.toFile();
        writeable.createNewFile();
        Assertions.assertTrue(unwriteable.exists());
        Assertions.assertTrue(writeable.exists());
        Set<PosixFilePermission> perms =
                Files.readAttributes( unwriteablePath, PosixFileAttributes.class).permissions();
        //make file unwriteable
        perms.remove(PosixFilePermission.OWNER_WRITE);
        perms.remove(PosixFilePermission.GROUP_WRITE);
        perms.remove(PosixFilePermission.OTHERS_WRITE);
        perms.remove(PosixFilePermission.OWNER_READ);
        perms.remove(PosixFilePermission.GROUP_READ);
        perms.remove(PosixFilePermission.OTHERS_READ);
        Files.setPosixFilePermissions(unwriteablePath, perms);
        Assertions.assertFalse(unwriteable.canWrite());
       // Deleter deleter = new Deleter(mockConfig);
       // deleter.run();
        try {
            Files.delete(Paths.get(unwriteable.getAbsolutePath()));
        } catch (IOException e) {
            System.out.println("Got expected exception");
        }
        Assertions.assertFalse(writeable.exists());
        Assertions.assertTrue(unwriteable.exists());
    }
} 
Jeff Gaer
  • 351
  • 3
  • 21
  • 1
    *"does java Files.delete remove files without write permission?"* ... Java doesn't delete files, your OS does, Java just tells it to do so and it is your OS's responsibility to verify the permissions. And no, Java doesn't has root access, unless you're running it as root. – Tom Jul 15 '21 at 15:58
  • Also, I consider this question either a duplicate or at least very related to [What permissions are needed to delete a file in unix?](//stackoverflow.com/q/54622606). It tells you why your approach doesn't work. – Tom Jul 15 '21 at 16:01

0 Answers0