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 @@ -23,10 +23,15 @@
import com.google.cloud.teleport.util.GCSUtils;
import com.google.common.annotations.VisibleForTesting;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.PosixFilePermission;
import java.nio.file.attribute.PosixFilePermissions;
import java.security.Security;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.net.ssl.SSLServerSocketFactory;
Expand All @@ -49,6 +54,10 @@ public class CommonTemplateJvmInitializer implements JvmInitializer {
private static final Pattern DEFAULT_SECRET_MANAGER_PATTERN =
Pattern.compile(
"^projects\\/[^\\n\\r\\/]+\\/secrets\\/[^\\n\\r\\/]+\\/versions\\/[^\\n\\r\\/]+$");
private static final Set<PosixFilePermission> OWNER_ONLY_DIRECTORY =
PosixFilePermissions.fromString("rwx------");
private static final Set<PosixFilePermission> OWNER_ONLY_FILE =
PosixFilePermissions.fromString("rw-------");
private Pattern gcsPattern = DEFAULT_GCS_PATTERN;
private Pattern secretManagerPattern = DEFAULT_SECRET_MANAGER_PATTERN;
private String destinationDirectory = "/extra_files";
Expand Down Expand Up @@ -87,9 +96,18 @@ public void beforeProcessing(PipelineOptions options) {
* extraFilesToStage will be stored.
*/
private void createDestinationDirectory() {
File destRoot = new File(destinationDirectory);
if (!destRoot.mkdir()) {
throw new RuntimeException("Could not create destination folder for extraFilesToStage.");
try {
Path destRoot = Paths.get(destinationDirectory);
if (supportsPosix(destRoot)) {
Files.createDirectories(
destRoot, PosixFilePermissions.asFileAttribute(OWNER_ONLY_DIRECTORY));
// Also tightens a pre-existing directory.
Files.setPosixFilePermissions(destRoot, OWNER_ONLY_DIRECTORY);
} else {
Files.createDirectories(destRoot);
}
} catch (IOException e) {
throw new RuntimeException("Could not create destination folder for extraFilesToStage.", e);
}
}
Comment thread
shunping marked this conversation as resolved.
Resolved

Expand Down Expand Up @@ -157,16 +175,31 @@ private SecretVersionName parseSecretVersion(String secret) {

/** Extract secret payload from a secret manager secret. */
private byte[] getSecretPayload(SecretVersionName secretVersionName) throws IOException {
SecretManagerServiceClient client = SecretManagerServiceClient.create();
AccessSecretVersionResponse response = client.accessSecretVersion(secretVersionName);
return response.getPayload().getData().toByteArray();
try (SecretManagerServiceClient client = SecretManagerServiceClient.create()) {
AccessSecretVersionResponse response = client.accessSecretVersion(secretVersionName);
return response.getPayload().getData().toByteArray();
}
}

/** Copies the byte array into the file. */
/**
* Copies the byte array into the file, replacing any existing content. Sets owner-only
* permissions on the file before writing when the file system supports POSIX permissions.
*/
private void copy(byte[] data, File destFile) throws IOException {
FileOutputStream outputStream = new FileOutputStream(destFile);
outputStream.write(data);
outputStream.close();
Path destPath = destFile.toPath();
if (supportsPosix(destPath)) {
try {
Files.createFile(destPath, PosixFilePermissions.asFileAttribute(OWNER_ONLY_FILE));
} catch (FileAlreadyExistsException e) {
// Existing file: tighten permissions before overwriting.
Files.setPosixFilePermissions(destPath, OWNER_ONLY_FILE);
}
}
Files.write(destPath, data);
}
Comment thread
shunping marked this conversation as resolved.
Resolved

private static boolean supportsPosix(Path path) {
return path.getFileSystem().supportedFileAttributeViews().contains("posix");
}

/** Only to be used by tests. */
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,16 @@
package com.google.cloud.teleport.templates.common;

import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assume.assumeTrue;

import com.google.cloud.teleport.options.CommonTemplateOptions;
import com.google.cloud.teleport.util.GCSUtils;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.attribute.PosixFilePermissions;
import java.util.Arrays;
import org.apache.beam.sdk.options.ValueProvider;
import org.apache.beam.sdk.testing.TestPipeline;
import org.junit.Before;
Expand Down Expand Up @@ -74,4 +80,40 @@ public void testBeforeProcessingExtraFilesToStage_throwsExceptionForIllegalFiles
// Act
jvmInitializer.beforeProcessing(options);
}

@Test
public void testBeforeProcessingExtraFilesToStage_overwritesExistingFileInExistingDirectory()
throws IOException {
// Arrange: the directory already holds a longer, different version of the file.
byte[] expected = GCSUtils.getGcsFileAsBytes(filePath);
byte[] existing = new byte[expected.length + 100];
Arrays.fill(existing, (byte) 'x');
Files.createDirectories(Paths.get(destinationDirectory));
Files.write(Paths.get(destinationDirectory, "RootCA.crt"), existing);
CommonTemplateOptions options =
TestPipeline.testingPipelineOptions().as(CommonTemplateOptions.class);
options.setDisabledAlgorithms(null);
options.setExtraFilesToStage(ValueProvider.StaticValueProvider.of(filePath));
// Act
jvmInitializer.beforeProcessing(options);
// Assert
assertThat(Files.readAllBytes(Paths.get(destinationDirectory, "RootCA.crt")))
.isEqualTo(expected);
}

@Test
public void testBeforeProcessingExtraFilesToStage_setsOwnerOnlyPermissions() throws IOException {
assumeTrue(FileSystems.getDefault().supportedFileAttributeViews().contains("posix"));
CommonTemplateOptions options =
TestPipeline.testingPipelineOptions().as(CommonTemplateOptions.class);
options.setDisabledAlgorithms(null);
options.setExtraFilesToStage(ValueProvider.StaticValueProvider.of(filePath));
// Act
jvmInitializer.beforeProcessing(options);
// Assert
assertThat(Files.getPosixFilePermissions(Paths.get(destinationDirectory)))
.isEqualTo(PosixFilePermissions.fromString("rwx------"));
assertThat(Files.getPosixFilePermissions(Paths.get(destinationDirectory, "RootCA.crt")))
.isEqualTo(PosixFilePermissions.fromString("rw-------"));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,15 @@
import com.google.cloud.teleport.v2.utils.GCSUtils;
import com.google.common.annotations.VisibleForTesting;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.PosixFilePermission;
import java.nio.file.attribute.PosixFilePermissions;
import java.security.Security;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.net.ssl.SSLServerSocketFactory;
Expand All @@ -49,6 +54,10 @@ public class CommonTemplateJvmInitializer implements JvmInitializer {
private static final Pattern DEFAULT_SECRET_MANAGER_PATTERN =
Pattern.compile(
"^projects\\/[^\\n\\r\\/]+\\/secrets\\/[^\\n\\r\\/]+\\/versions\\/[^\\n\\r\\/]+$");
private static final Set<PosixFilePermission> OWNER_ONLY_DIRECTORY =
PosixFilePermissions.fromString("rwx------");
private static final Set<PosixFilePermission> OWNER_ONLY_FILE =
PosixFilePermissions.fromString("rw-------");
private Pattern gcsPattern = DEFAULT_GCS_PATTERN;
private Pattern secretManagerPattern = DEFAULT_SECRET_MANAGER_PATTERN;
private String destinationDirectory = "/extra_files";
Expand Down Expand Up @@ -86,9 +95,18 @@ public void beforeProcessing(PipelineOptions options) {
* extraFilesToStage will be stored.
*/
private void createDestinationDirectory() {
File destRoot = new File(destinationDirectory);
if (!destRoot.mkdir()) {
throw new RuntimeException("Could not create destination folder for extraFilesToStage.");
try {
Path destRoot = Paths.get(destinationDirectory);
if (supportsPosix(destRoot)) {
Files.createDirectories(
destRoot, PosixFilePermissions.asFileAttribute(OWNER_ONLY_DIRECTORY));
// Also tightens a pre-existing directory.
Files.setPosixFilePermissions(destRoot, OWNER_ONLY_DIRECTORY);
} else {
Files.createDirectories(destRoot);
}
} catch (IOException e) {
throw new RuntimeException("Could not create destination folder for extraFilesToStage.", e);
}
}
Comment thread
shunping marked this conversation as resolved.
Resolved

Expand Down Expand Up @@ -156,16 +174,31 @@ private SecretVersionName parseSecretVersion(String secret) {

/** Extract secret payload from a secret manager secret. */
private byte[] getSecretPayload(SecretVersionName secretVersionName) throws IOException {
SecretManagerServiceClient client = SecretManagerServiceClient.create();
AccessSecretVersionResponse response = client.accessSecretVersion(secretVersionName);
return response.getPayload().getData().toByteArray();
try (SecretManagerServiceClient client = SecretManagerServiceClient.create()) {
AccessSecretVersionResponse response = client.accessSecretVersion(secretVersionName);
return response.getPayload().getData().toByteArray();
}
}

/** Copies the byte array into the file. */
/**
* Copies the byte array into the file, replacing any existing content. Sets owner-only
* permissions on the file before writing when the file system supports POSIX permissions.
*/
private void copy(byte[] data, File destFile) throws IOException {
FileOutputStream outputStream = new FileOutputStream(destFile);
outputStream.write(data);
outputStream.close();
Path destPath = destFile.toPath();
if (supportsPosix(destPath)) {
try {
Files.createFile(destPath, PosixFilePermissions.asFileAttribute(OWNER_ONLY_FILE));
} catch (FileAlreadyExistsException e) {
// Existing file: tighten permissions before overwriting.
Files.setPosixFilePermissions(destPath, OWNER_ONLY_FILE);
}
}
Files.write(destPath, data);
}
Comment thread
shunping marked this conversation as resolved.
Resolved

private static boolean supportsPosix(Path path) {
return path.getFileSystem().supportedFileAttributeViews().contains("posix");
}

/** Only to be used by tests. */
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,16 @@
package com.google.cloud.teleport.v2.common;

import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assume.assumeTrue;

import com.google.cloud.teleport.v2.options.CommonTemplateOptions;
import com.google.cloud.teleport.v2.utils.GCSUtils;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.attribute.PosixFilePermissions;
import java.util.Arrays;
import org.apache.beam.sdk.testing.TestPipeline;
import org.junit.Before;
import org.junit.Rule;
Expand Down Expand Up @@ -70,4 +77,38 @@ public void testBeforeProcessingExtraFilesToStage_throwsExceptionForIllegalFiles
// Act
jvmInitializer.beforeProcessing(options);
}

@Test
public void testBeforeProcessingExtraFilesToStage_overwritesExistingFileInExistingDirectory()
throws IOException {
// Arrange: the directory already holds a longer, different version of the file.
byte[] expected = GCSUtils.getGcsFileAsBytes(filePath);
byte[] existing = new byte[expected.length + 100];
Arrays.fill(existing, (byte) 'x');
Files.createDirectories(Paths.get(destinationDirectory));
Files.write(Paths.get(destinationDirectory, "test_schema.json"), existing);
CommonTemplateOptions options =
TestPipeline.testingPipelineOptions().as(CommonTemplateOptions.class);
options.setExtraFilesToStage(filePath);
// Act
jvmInitializer.beforeProcessing(options);
// Assert
assertThat(Files.readAllBytes(Paths.get(destinationDirectory, "test_schema.json")))
.isEqualTo(expected);
}

@Test
public void testBeforeProcessingExtraFilesToStage_setsOwnerOnlyPermissions() throws IOException {
assumeTrue(FileSystems.getDefault().supportedFileAttributeViews().contains("posix"));
CommonTemplateOptions options =
TestPipeline.testingPipelineOptions().as(CommonTemplateOptions.class);
options.setExtraFilesToStage(filePath);
// Act
jvmInitializer.beforeProcessing(options);
// Assert
assertThat(Files.getPosixFilePermissions(Paths.get(destinationDirectory)))
.isEqualTo(PosixFilePermissions.fromString("rwx------"));
assertThat(Files.getPosixFilePermissions(Paths.get(destinationDirectory, "test_schema.json")))
.isEqualTo(PosixFilePermissions.fromString("rw-------"));
}
}
Loading