Prevent creating files with illegal characters in name (#7)

This commit is contained in:
Paul Campbell 2020-12-29 10:16:54 +00:00 committed by GitHub
parent 5ac2e219c4
commit 6aeb8165f6
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 37 additions and 2 deletions

View file

@ -17,19 +17,22 @@ public class AttachmentDirectoryImpl implements AttachmentDirectory {
private static final Logger LOG = private static final Logger LOG =
Logger.getLogger( Logger.getLogger(
AttachmentDirectoryImpl.class.getName()); AttachmentDirectoryImpl.class.getName());
private static final String ILLEGAL_CHARS = "[\\\\/:*?\"<>|]";
private Path dir; private Path dir;
private List<File> toDelete = new ArrayList<>(); private List<File> toDelete = new ArrayList<>();
@PostConstruct @PostConstruct
void init() throws IOException { public void init() throws IOException {
dir = Files.createTempDirectory("attachments"); dir = Files.createTempDirectory("attachments");
LOG.info("Attachments directory: " + dir); LOG.info("Attachments directory: " + dir);
} }
@Override @Override
public File createFile(File fileName) { 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); LOG.info("Created attachment: " + file);
toDelete.add(file); toDelete.add(file);
return file; return file;

View file

@ -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");
}
}