From 6aeb8165f6aa5d23e12f1d4985aeff74921b5b1c Mon Sep 17 00:00:00 2001 From: Paul Campbell Date: Tue, 29 Dec 2020 10:16:54 +0000 Subject: [PATCH] Prevent creating files with illegal characters in name (#7) --- .../trello/AttachmentDirectoryImpl.java | 7 ++-- .../trello/AttachmentDirectoryImplTest.java | 32 +++++++++++++++++++ 2 files changed, 37 insertions(+), 2 deletions(-) create mode 100644 src/test/java/net/kemitix/trello/AttachmentDirectoryImplTest.java diff --git a/src/main/java/net/kemitix/trello/AttachmentDirectoryImpl.java b/src/main/java/net/kemitix/trello/AttachmentDirectoryImpl.java index aefe73b..44b7a4a 100644 --- a/src/main/java/net/kemitix/trello/AttachmentDirectoryImpl.java +++ b/src/main/java/net/kemitix/trello/AttachmentDirectoryImpl.java @@ -17,19 +17,22 @@ public class AttachmentDirectoryImpl implements AttachmentDirectory { private static final Logger LOG = Logger.getLogger( AttachmentDirectoryImpl.class.getName()); + private static final String ILLEGAL_CHARS = "[\\\\/:*?\"<>|]"; private Path dir; private List toDelete = new ArrayList<>(); @PostConstruct - void init() throws IOException { + public void init() throws IOException { dir = Files.createTempDirectory("attachments"); LOG.info("Attachments directory: " + dir); } @Override public File createFile(File fileName) { - File file = dir.resolve(fileName.getName()).toFile(); + String cleanFilename = fileName.getName() + .replaceAll(ILLEGAL_CHARS, ""); + File file = dir.resolve(cleanFilename).toFile(); LOG.info("Created attachment: " + file); toDelete.add(file); return file; diff --git a/src/test/java/net/kemitix/trello/AttachmentDirectoryImplTest.java b/src/test/java/net/kemitix/trello/AttachmentDirectoryImplTest.java new file mode 100644 index 0000000..4b63e86 --- /dev/null +++ b/src/test/java/net/kemitix/trello/AttachmentDirectoryImplTest.java @@ -0,0 +1,32 @@ +package net.kemitix.trello; + +import org.assertj.core.api.WithAssertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.io.File; +import java.io.IOException; + +public class AttachmentDirectoryImplTest + implements WithAssertions { + + AttachmentDirectoryImpl attachmentDirectory = + new AttachmentDirectoryImpl(); + + @BeforeEach + public void setUp() throws IOException { + attachmentDirectory.init(); + } + + @Test + @DisplayName("Creates safe filenames") + public void createsSafeFilenames() { + //given + String filename = "x\\y"; + //when + File result = attachmentDirectory.createFile(new File(filename)); + //then + assertThat(result.getName()).isEqualTo("xy"); + } +}