Skip to content
Open
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
76 changes: 49 additions & 27 deletions functions/imagemagick/src/main/java/functions/ImageMagick.java
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,9 @@
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;

Expand Down Expand Up @@ -100,41 +101,62 @@ public void accept(GcsEvent event, Context context) {
// [END functions_imagemagick_analyze]

// [START functions_imagemagick_blur]
private static final Set<String> ALLOWED_EXTENSIONS =
Set.of(".jpg", ".jpeg", ".png", ".gif", ".webp", ".bmp", ".tif", ".tiff");

private static String getSafeExtension(String fileName) {
if (fileName != null) {
int lastDot = fileName.lastIndexOf('.');
if (lastDot >= 0 && lastDot < fileName.length() - 1) {
String ext = fileName.substring(lastDot).toLowerCase(Locale.ROOT);
if (ALLOWED_EXTENSIONS.contains(ext)) {
return ext;
}
}
}
return ".png";
}

// Blurs the file described by blobInfo using ImageMagick,
// and uploads it to the blurred bucket.
private static void blur(BlobInfo blobInfo) throws IOException {
String bucketName = blobInfo.getBucket();
String fileName = blobInfo.getName();
String extension = getSafeExtension(fileName);

// Download image
// Download image to a safely generated temporary file to prevent path traversal
// and ImageMagick argument injection from untrusted object names.
Blob blob = storage.get(BlobId.of(bucketName, fileName));
Path download = Paths.get("/tmp/", fileName);
blob.downloadTo(download);

// Construct the command.
Path upload = Paths.get("/tmp/", "blurred-" + fileName);
List<String> args = List.of("convert", download.toString(), "-blur", "0x8", upload.toString());
Path download = Files.createTempFile("download-", extension);
Path upload = Files.createTempFile("blurred-", extension);
try {
ProcessBuilder pb = new ProcessBuilder(args);
Process process = pb.start();
process.waitFor();
} catch (Exception e) {
logger.info(String.format("Error: %s", e.getMessage()));
}

// Upload image to blurred bucket.
BlobId blurredBlobId = BlobId.of(BLURRED_BUCKET_NAME, fileName);
BlobInfo blurredBlobInfo =
BlobInfo.newBuilder(blurredBlobId).setContentType(blob.getContentType()).build();

byte[] blurredFile = Files.readAllBytes(upload);
storage.create(blurredBlobInfo, blurredFile);
logger.info(
String.format("Blurred image uploaded to: gs://%s/%s", BLURRED_BUCKET_NAME, fileName));
blob.downloadTo(download);

// Construct the command.
List<String> args =
List.of("convert", download.toString(), "-blur", "0x8", upload.toString());
try {
ProcessBuilder pb = new ProcessBuilder(args);
Process process = pb.start();
process.waitFor();
} catch (Exception e) {
logger.info(String.format("Error: %s", e.getMessage()));
}

// Remove images from fileSystem
Files.delete(download);
Files.delete(upload);
// Upload image to blurred bucket.
BlobId blurredBlobId = BlobId.of(BLURRED_BUCKET_NAME, fileName);
BlobInfo blurredBlobInfo =
BlobInfo.newBuilder(blurredBlobId).setContentType(blob.getContentType()).build();

byte[] blurredFile = Files.readAllBytes(upload);
storage.create(blurredBlobInfo, blurredFile);
logger.info(
String.format("Blurred image uploaded to: gs://%s/%s", BLURRED_BUCKET_NAME, fileName));
} finally {
// Remove images from fileSystem
Files.deleteIfExists(download);
Files.deleteIfExists(upload);
}
}
// [END functions_imagemagick_blur]
// [START functions_imagemagick_setup]
Expand Down
80 changes: 51 additions & 29 deletions functions/v2/imagemagick/src/main/java/functions/ImageMagick.java
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,9 @@
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;

Expand Down Expand Up @@ -107,43 +108,64 @@ public void accept(CloudEvent event) throws InvalidProtocolBufferException {
// [END functions_imagemagick_analyze]

// [START functions_imagemagick_blur]
private static final Set<String> ALLOWED_EXTENSIONS =
Set.of(".jpg", ".jpeg", ".png", ".gif", ".webp", ".bmp", ".tif", ".tiff");

private static String getSafeExtension(String fileName) {
if (fileName != null) {
int lastDot = fileName.lastIndexOf('.');
if (lastDot >= 0 && lastDot < fileName.length() - 1) {
String ext = fileName.substring(lastDot).toLowerCase(Locale.ROOT);
if (ALLOWED_EXTENSIONS.contains(ext)) {
return ext;
}
}
}
return ".png";
}

// Blurs the file described by blobInfo using ImageMagick,
// and uploads it to the blurred bucket.
private static void blur(BlobInfo blobInfo) throws IOException {
String bucketName = blobInfo.getBucket();
String fileName = blobInfo.getName();
String extension = getSafeExtension(fileName);

// Download image
// Download image to a safely generated temporary file to prevent path traversal
// and ImageMagick argument injection from untrusted object names.
Blob blob = storage.get(BlobId.of(bucketName, fileName));
Path download = Paths.get("/tmp/", fileName);
blob.downloadTo(download);

// Construct the command.
Path upload = Paths.get("/tmp/", "blurred-" + fileName);
List<String> args = List.of("convert", download.toString(), "-blur", "0x8", upload.toString());
Path download = Files.createTempFile("download-", extension);
Path upload = Files.createTempFile("blurred-", extension);
try {
ProcessBuilder pb = new ProcessBuilder(args);
Process process = pb.start();
process.waitFor();
} catch (Exception e) {
logger.info(String.format("Error: %s", e.getMessage()));
}

// Upload image to blurred bucket.
BlobId blurredBlobId = BlobId.of(BLURRED_BUCKET_NAME, fileName);
BlobInfo blurredBlobInfo = BlobInfo
.newBuilder(blurredBlobId)
.setContentType(blob.getContentType())
.build();

byte[] blurredFile = Files.readAllBytes(upload);
storage.create(blurredBlobInfo, blurredFile);
logger.info(
String.format("Blurred image uploaded to: gs://%s/%s", BLURRED_BUCKET_NAME, fileName));
blob.downloadTo(download);

// Construct the command.
List<String> args =
List.of("convert", download.toString(), "-blur", "0x8", upload.toString());
try {
ProcessBuilder pb = new ProcessBuilder(args);
Process process = pb.start();
process.waitFor();
} catch (Exception e) {
logger.info(String.format("Error: %s", e.getMessage()));
}

// Remove images from fileSystem
Files.delete(download);
Files.delete(upload);
// Upload image to blurred bucket.
BlobId blurredBlobId = BlobId.of(BLURRED_BUCKET_NAME, fileName);
BlobInfo blurredBlobInfo = BlobInfo
.newBuilder(blurredBlobId)
.setContentType(blob.getContentType())
.build();

byte[] blurredFile = Files.readAllBytes(upload);
storage.create(blurredBlobInfo, blurredFile);
logger.info(
String.format("Blurred image uploaded to: gs://%s/%s", BLURRED_BUCKET_NAME, fileName));
} finally {
// Remove images from fileSystem
Files.deleteIfExists(download);
Files.deleteIfExists(upload);
}
}
// [END functions_imagemagick_blur]

Expand Down
6 changes: 6 additions & 0 deletions run/image-processing/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,12 @@ For more details on how to work with this sample read the [Google Cloud Run Java

[![Run in Google Cloud][run_img]][run_link]

## Security

Deploy this Cloud Run service with `--no-allow-unauthenticated` and configure a
[Pub/Sub push subscription with IAM authentication](https://cloud.google.com/run/docs/tutorials/image-processing#ship_the_code)
so unauthenticated callers cannot invoke the push endpoint.

## Dependencies

* **Spring Boot**: Web server framework.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,10 @@
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Set;

public class ImageMagick {

Expand Down Expand Up @@ -89,48 +90,65 @@ public static void blurOffensiveImages(JsonObject data) {
// [END cloudrun_imageproc_handler_analyze]

// [START cloudrun_imageproc_handler_blur]
private static final Set<String> ALLOWED_EXTENSIONS =
Set.of(".jpg", ".jpeg", ".png", ".gif", ".webp", ".bmp", ".tif", ".tiff");

private static String getSafeExtension(String fileName) {
if (fileName != null) {
int lastDot = fileName.lastIndexOf('.');
if (lastDot >= 0 && lastDot < fileName.length() - 1) {
String ext = fileName.substring(lastDot).toLowerCase(Locale.ROOT);
if (ALLOWED_EXTENSIONS.contains(ext)) {
return ext;
}
}
}
return ".png";
}

// Blurs the file described by blobInfo using ImageMagick,
// and uploads it to the blurred bucket.
public static void blur(BlobInfo blobInfo) throws IOException {
String bucketName = blobInfo.getBucket();
String fileName = blobInfo.getName();
// Download image
Blob blob = storage.get(BlobId.of(bucketName, fileName));
Path download = Paths.get("/tmp/", fileName);
blob.downloadTo(download);
String extension = getSafeExtension(fileName);

// Construct the command.
List<String> args = new ArrayList<>();
args.add("convert");
args.add(download.toString());
args.add("-blur");
args.add("0x8");
Path upload = Paths.get("/tmp/", "blurred-" + fileName);
args.add(upload.toString());
// Download image to a safely generated temporary file to prevent path traversal
// and ImageMagick argument injection from untrusted object names.
Blob blob = storage.get(BlobId.of(bucketName, fileName));
Path download = Files.createTempFile("download-", extension);
Path upload = Files.createTempFile("blurred-", extension);
try {
ProcessBuilder pb = new ProcessBuilder(args);
Process process = pb.start();
process.waitFor();
} catch (Exception e) {
System.out.println(String.format("Error: %s", e.getMessage()));
}
blob.downloadTo(download);

// Upload image to blurred bucket.
BlobId blurredBlobId = BlobId.of(BLURRED_BUCKET_NAME, fileName);
BlobInfo blurredBlobInfo =
BlobInfo.newBuilder(blurredBlobId).setContentType(blob.getContentType()).build();
try {
byte[] blurredFile = Files.readAllBytes(upload);
Blob blurredBlob = storage.create(blurredBlobInfo, blurredFile);
System.out.println(
String.format("Blurred image uploaded to: gs://%s/%s", BLURRED_BUCKET_NAME, fileName));
} catch (Exception e) {
System.out.println(String.format("Error in upload: %s", e.getMessage()));
}
// Construct the command.
List<String> args =
List.of("convert", download.toString(), "-blur", "0x8", upload.toString());
try {
ProcessBuilder pb = new ProcessBuilder(args);
Process process = pb.start();
process.waitFor();
} catch (Exception e) {
System.out.println(String.format("Error: %s", e.getMessage()));
}

// Remove images from fileSystem
Files.delete(download);
Files.delete(upload);
// Upload image to blurred bucket.
BlobId blurredBlobId = BlobId.of(BLURRED_BUCKET_NAME, fileName);
BlobInfo blurredBlobInfo =
BlobInfo.newBuilder(blurredBlobId).setContentType(blob.getContentType()).build();
try {
byte[] blurredFile = Files.readAllBytes(upload);
Blob blurredBlob = storage.create(blurredBlobInfo, blurredFile);
System.out.println(
String.format("Blurred image uploaded to: gs://%s/%s", BLURRED_BUCKET_NAME, fileName));
} catch (Exception e) {
System.out.println(String.format("Error in upload: %s", e.getMessage()));
}
} finally {
// Remove images from fileSystem
Files.deleteIfExists(download);
Files.deleteIfExists(upload);
}
}
}
// [END cloudrun_imageproc_handler_blur]
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@
import org.springframework.web.bind.annotation.RestController;

// PubsubController consumes a Pub/Sub message.
// Deploy this Cloud Run service with --no-allow-unauthenticated so Cloud Run IAM
// authenticates Pub/Sub push requests before they reach this controller.
@RestController
public class PubSubController {
@RequestMapping(value = "/", method = RequestMethod.POST)
Expand Down