diff --git a/functions/imagemagick/src/main/java/functions/ImageMagick.java b/functions/imagemagick/src/main/java/functions/ImageMagick.java index 97e8483bbc6..6f7f6a51093 100644 --- a/functions/imagemagick/src/main/java/functions/ImageMagick.java +++ b/functions/imagemagick/src/main/java/functions/ImageMagick.java @@ -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; @@ -100,41 +101,62 @@ public void accept(GcsEvent event, Context context) { // [END functions_imagemagick_analyze] // [START functions_imagemagick_blur] + private static final Set 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 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 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] diff --git a/functions/v2/imagemagick/src/main/java/functions/ImageMagick.java b/functions/v2/imagemagick/src/main/java/functions/ImageMagick.java index 546207d26cf..3c7cbc9dff8 100644 --- a/functions/v2/imagemagick/src/main/java/functions/ImageMagick.java +++ b/functions/v2/imagemagick/src/main/java/functions/ImageMagick.java @@ -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; @@ -107,43 +108,64 @@ public void accept(CloudEvent event) throws InvalidProtocolBufferException { // [END functions_imagemagick_analyze] // [START functions_imagemagick_blur] + private static final Set 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 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 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] diff --git a/run/image-processing/README.md b/run/image-processing/README.md index f87e800003f..4dcd83fffd7 100644 --- a/run/image-processing/README.md +++ b/run/image-processing/README.md @@ -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. diff --git a/run/image-processing/src/main/java/com/example/cloudrun/ImageMagick.java b/run/image-processing/src/main/java/com/example/cloudrun/ImageMagick.java index a539f1d7630..5c77f1e8023 100644 --- a/run/image-processing/src/main/java/com/example/cloudrun/ImageMagick.java +++ b/run/image-processing/src/main/java/com/example/cloudrun/ImageMagick.java @@ -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 { @@ -89,48 +90,65 @@ public static void blurOffensiveImages(JsonObject data) { // [END cloudrun_imageproc_handler_analyze] // [START cloudrun_imageproc_handler_blur] + private static final Set 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 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 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] diff --git a/run/image-processing/src/main/java/com/example/cloudrun/PubSubController.java b/run/image-processing/src/main/java/com/example/cloudrun/PubSubController.java index e8e3c72ad69..61fb8f2f3d5 100644 --- a/run/image-processing/src/main/java/com/example/cloudrun/PubSubController.java +++ b/run/image-processing/src/main/java/com/example/cloudrun/PubSubController.java @@ -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)