Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,20 @@
package org.apache.hc.client5.http.impl.cache;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.channels.Channels;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.OpenOption;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.nio.file.attribute.FileAttribute;
import java.nio.file.attribute.PosixFilePermissions;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.EnumSet;
import java.util.Set;

import org.apache.hc.client5.http.cache.Resource;
import org.apache.hc.client5.http.cache.ResourceFactory;
Expand All @@ -49,6 +59,21 @@
@Contract(threading = ThreadingBehavior.STATELESS)
public class FileResourceFactory implements ResourceFactory {

/**
* Permissions of the cache files created by this factory. A cache file holds a response
* body verbatim, so it must not be readable by other users of the system. Empty on file
* systems without POSIX file permissions, where the file inherits the directory's ACL.
*/
private static final FileAttribute<?>[] OWNER_ONLY = ownerOnlyAttributes();

/**
* Cache files are always created anew. {@code CREATE_NEW} fails if anything, including a
* symbolic link, exists at the path, so a write can never land in a file this factory did
* not create.
*/
private static final Set<? extends OpenOption> CREATE_EXCLUSIVE =
EnumSet.of(StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE);

private final File cacheDir;

public FileResourceFactory(final File cacheDir) {
Expand Down Expand Up @@ -87,16 +112,36 @@ public Resource generate(
Args.notNull(requestId, "Request id");
final String filename = generateUniqueCacheFileName(requestId, eTag, content, off, len);
final File file = new File(cacheDir, filename);
try (FileOutputStream outStream = new FileOutputStream(file, false)) {
if (content != null) {
outStream.write(content, off, len);
}
try {
writeCacheFile(file.toPath(), content, off, len);
} catch (final IOException ex) {
throw new ResourceIOException(ex.getMessage(), ex);
}
return new FileResource(file);
}

private static FileAttribute<?>[] ownerOnlyAttributes() {
if (FileSystems.getDefault().supportedFileAttributeViews().contains("posix")) {
return new FileAttribute<?>[] {
PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rw-------")) };
}
return new FileAttribute<?>[0];
}

private static void writeCacheFile(
final Path file, final byte[] content, final int off, final int len) throws IOException {
// Whatever is at the path is not reused: a pre-existing file keeps its own mode and may be
// a hard link to a file outside the cache directory. Remove it (a symbolic link is removed,
// not followed) and create the cache file exclusively with owner-only permissions.
Files.deleteIfExists(file);
try (OutputStream outStream = Channels.newOutputStream(
Files.newByteChannel(file, CREATE_EXCLUSIVE, OWNER_ONLY))) {
if (content != null) {
outStream.write(content, off, len);
}
}
}

@Override
public Resource generate(final String requestId, final byte[] content, final int off, final int len) throws ResourceIOException {
if (content != null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,19 @@
package org.apache.hc.client5.http.impl.cache;


import java.io.IOException;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.PosixFilePermissions;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;

class TestFileResourceFactory {

Expand Down Expand Up @@ -66,4 +74,80 @@ void testViaValueLookup() throws Exception {
FileResourceFactory.generateUniqueCacheFileName(requestId, null, null, 0, 0));
}

@Test
void testGeneratedCacheFileIsOwnerOnly(@TempDir final Path cacheDir) throws Exception {
Assumptions.assumeTrue(FileSystems.getDefault().supportedFileAttributeViews().contains("posix"));
final String requestId = keyGenerator.generateKey(new URI("http://localhost/stuff"));
final byte[] content = "secret".getBytes(StandardCharsets.US_ASCII);

new FileResourceFactory(cacheDir.toFile()).generate(requestId, "\"v1\"", content, 0, content.length);

final Path file = cacheDir.resolve(
FileResourceFactory.generateUniqueCacheFileName(requestId, "\"v1\"", content, 0, content.length));
Assertions.assertEquals("rw-------",
PosixFilePermissions.toString(Files.getPosixFilePermissions(file)));
}

@Test
void testGenerateDoesNotFollowSymlink(@TempDir final Path cacheDir, @TempDir final Path otherDir) throws Exception {
final String requestId = keyGenerator.generateKey(new URI("http://localhost/stuff"));
final byte[] content = "response body".getBytes(StandardCharsets.US_ASCII);
final Path outside = otherDir.resolve("outside");
Files.write(outside, "untouched".getBytes(StandardCharsets.US_ASCII));
final Path link = cacheDir.resolve(
FileResourceFactory.generateUniqueCacheFileName(requestId, "\"v1\"", content, 0, content.length));
try {
Files.createSymbolicLink(link, outside);
} catch (final IOException | UnsupportedOperationException ex) {
Assumptions.abort("symbolic links are not supported here");
}

new FileResourceFactory(cacheDir.toFile()).generate(requestId, "\"v1\"", content, 0, content.length);

Assertions.assertEquals("untouched",
new String(Files.readAllBytes(outside), StandardCharsets.US_ASCII));
Assertions.assertFalse(Files.isSymbolicLink(link));
Assertions.assertEquals("response body",
new String(Files.readAllBytes(link), StandardCharsets.US_ASCII));
}

@Test
void testGenerateReplacesPreexistingFile(@TempDir final Path cacheDir) throws Exception {
Assumptions.assumeTrue(FileSystems.getDefault().supportedFileAttributeViews().contains("posix"));
final String requestId = keyGenerator.generateKey(new URI("http://localhost/stuff"));
final byte[] content = "secret".getBytes(StandardCharsets.US_ASCII);
final Path file = cacheDir.resolve(
FileResourceFactory.generateUniqueCacheFileName(requestId, "\"v1\"", content, 0, content.length));
Files.write(file, "planted".getBytes(StandardCharsets.US_ASCII));
Files.setPosixFilePermissions(file, PosixFilePermissions.fromString("rw-rw-rw-"));

new FileResourceFactory(cacheDir.toFile()).generate(requestId, "\"v1\"", content, 0, content.length);

Assertions.assertEquals("rw-------",
PosixFilePermissions.toString(Files.getPosixFilePermissions(file)));
Assertions.assertEquals("secret", new String(Files.readAllBytes(file), StandardCharsets.US_ASCII));
}

@Test
void testGenerateDoesNotWriteThroughHardLink(@TempDir final Path cacheDir, @TempDir final Path otherDir) throws Exception {
final String requestId = keyGenerator.generateKey(new URI("http://localhost/stuff"));
final byte[] content = "response body".getBytes(StandardCharsets.US_ASCII);
final Path outside = otherDir.resolve("outside");
Files.write(outside, "untouched".getBytes(StandardCharsets.US_ASCII));
final Path link = cacheDir.resolve(
FileResourceFactory.generateUniqueCacheFileName(requestId, "\"v1\"", content, 0, content.length));
try {
Files.createLink(link, outside);
} catch (final IOException | UnsupportedOperationException ex) {
Assumptions.abort("hard links are not supported here");
}

new FileResourceFactory(cacheDir.toFile()).generate(requestId, "\"v1\"", content, 0, content.length);

Assertions.assertEquals("untouched",
new String(Files.readAllBytes(outside), StandardCharsets.US_ASCII));
Assertions.assertEquals("response body",
new String(Files.readAllBytes(link), StandardCharsets.US_ASCII));
}

}
Loading