diff --git a/CHANGELOG.md b/CHANGELOG.md index 735831f2f98..28975c13ff0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ ### Fixes - Session Replay: Mask Compose images loaded with Coil 3.1+ `AsyncImage` when `maskAllImages` is enabled ([#6759](https://github.com/getsentry/sentry-java/pull/6759)) +- Attachments: A file attachment added by path is now streamed into the envelope when it's sent or cached, instead of being read into memory and held until the envelope is gone. If the file is missing when the envelope is sent, only that attachment is dropped. If it changes while it's being sent, the whole envelope is dropped instead of sending a corrupt one. Both cases are recorded in client reports with the reason `invalid`. `SentryEnvelopeItem.getData()` still returns its bytes, but reads the file on each call. Spotlight now serializes the envelope on the capturing thread before the SDK sends it ([#6777](https://github.com/getsentry/sentry-java/pull/6777)) - Profiling: No longer crash on API 35+ devices whose framework can't load `ProfilingManager`. Perfetto profiling is turned off on those devices instead ([#6742](https://github.com/getsentry/sentry-java/pull/6742)) - Android: Out-of-process crash reporting now supports Android 5.0 (API level 21) and later, previously required Android 11 (API level 30) ([#6614](https://github.com/getsentry/sentry-java/pull/6614)) - Android profiling: Uploading a Perfetto profile chunk now keeps the trace in memory once instead of up to three times, lowering peak memory use for traces up to 50 MB ([#6743](https://github.com/getsentry/sentry-java/pull/6743)) diff --git a/sentry-spotlight/src/main/java/io/sentry/spotlight/SpotlightIntegration.java b/sentry-spotlight/src/main/java/io/sentry/spotlight/SpotlightIntegration.java index ac8916cd08c..44d5f0643d4 100644 --- a/sentry-spotlight/src/main/java/io/sentry/spotlight/SpotlightIntegration.java +++ b/sentry-spotlight/src/main/java/io/sentry/spotlight/SpotlightIntegration.java @@ -17,6 +17,7 @@ import io.sentry.SentryIntegrationPackageStorage; import io.sentry.SentryOptions; import io.sentry.util.Platform; +import java.io.ByteArrayOutputStream; import java.io.Closeable; import java.io.IOException; import java.io.OutputStream; @@ -59,27 +60,48 @@ public void register(@NotNull IScopes scopes, @NotNull SentryOptions options) { } } + /** + * Serializes the envelope on the calling thread, so it is done before the transport serializes + * the same envelope, and posts it to Spotlight on a background thread. + */ @Override @SuppressWarnings("FutureReturnValueIgnored") public void execute(final @NotNull SentryEnvelope envelope, final @Nullable Hint hint) { + if (options == null) { + return; + } + final @NotNull byte[] body; + try { + body = serializeEnvelope(options, envelope); + } catch (Exception e) { + // ISerializer.serialize declares Exception. On failure the envelope isn't sent to Spotlight. + logger.log(ERROR, "Failed to serialize the envelope for Spotlight.", e); + return; + } try { - executorService.submit(() -> sendEnvelope(envelope)); + executorService.submit(() -> sendEnvelope(body)); } catch (RejectedExecutionException e) { logger.log(WARNING, "Spotlight envelope submission rejected.", e); } } - private void sendEnvelope(final @NotNull SentryEnvelope envelope) { + private static @NotNull byte[] serializeEnvelope( + final @NotNull SentryOptions options, final @NotNull SentryEnvelope envelope) + throws Exception { + final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + try (final GZIPOutputStream gzip = new GZIPOutputStream(outputStream)) { + options.getSerializer().serialize(envelope, gzip); + } + return outputStream.toByteArray(); + } + + private void sendEnvelope(final @NotNull byte[] body) { try { - if (options == null) { - throw new IllegalArgumentException("SentryOptions are required to send envelopes."); - } final String spotlightConnectionUrl = getSpotlightConnectionUrl(); final HttpURLConnection connection = createConnection(spotlightConnectionUrl); - try (final OutputStream outputStream = connection.getOutputStream(); - final GZIPOutputStream gzip = new GZIPOutputStream(outputStream)) { - options.getSerializer().serialize(envelope, gzip); + try (final OutputStream outputStream = connection.getOutputStream()) { + outputStream.write(body); } catch (Throwable e) { logger.log( ERROR, "An exception occurred while submitting the envelope to the Sentry server.", e); diff --git a/sentry-spotlight/src/test/java/io/sentry/spotlight/SpotlightIntegrationTest.kt b/sentry-spotlight/src/test/java/io/sentry/spotlight/SpotlightIntegrationTest.kt index 19fda229e95..484c4071fb8 100644 --- a/sentry-spotlight/src/test/java/io/sentry/spotlight/SpotlightIntegrationTest.kt +++ b/sentry-spotlight/src/test/java/io/sentry/spotlight/SpotlightIntegrationTest.kt @@ -1,13 +1,20 @@ package io.sentry.spotlight import io.sentry.IScopes +import io.sentry.ISerializer +import io.sentry.SentryEnvelope import io.sentry.SentryOptions import io.sentry.SentryOptions.BeforeEnvelopeCallback +import io.sentry.protocol.SentryId import io.sentry.util.SpotlightPlatformTestManipulator +import java.io.OutputStream import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertNull +import org.mockito.kotlin.any import org.mockito.kotlin.mock +import org.mockito.kotlin.same +import org.mockito.kotlin.verify class SpotlightIntegrationTest { @Test @@ -71,4 +78,24 @@ class SpotlightIntegrationTest { assertEquals("http://example.com:1234/stream", spotlight.spotlightConnectionUrl) } + + @Test + fun `serializes the envelope before execute returns`() { + val serializer = mock() + val options = + SentryOptions().apply { + isEnableSpotlight = true + // Nothing listens there, so the background post fails fast. + spotlightConnectionUrl = "http://localhost:1/stream" + setSerializer(serializer) + } + val envelope = SentryEnvelope(SentryId(), null, emptyList()) + val spotlight = SpotlightIntegration() + spotlight.register(mock(), options) + + spotlight.execute(envelope, null) + + verify(serializer).serialize(same(envelope), any()) + spotlight.close() + } } diff --git a/sentry/api/sentry.api b/sentry/api/sentry.api index 8dd75b41add..56cabc63b80 100644 --- a/sentry/api/sentry.api +++ b/sentry/api/sentry.api @@ -5183,6 +5183,7 @@ public final class io/sentry/clientreport/DiscardReason : java/lang/Enum { public static final field CACHE_OVERFLOW Lio/sentry/clientreport/DiscardReason; public static final field CALLBACK_ERROR Lio/sentry/clientreport/DiscardReason; public static final field EVENT_PROCESSOR Lio/sentry/clientreport/DiscardReason; + public static final field INVALID Lio/sentry/clientreport/DiscardReason; public static final field NETWORK_ERROR Lio/sentry/clientreport/DiscardReason; public static final field QUEUE_OVERFLOW Lio/sentry/clientreport/DiscardReason; public static final field RATELIMIT_BACKOFF Lio/sentry/clientreport/DiscardReason; @@ -5270,6 +5271,11 @@ public final class io/sentry/exception/InvalidSentryTraceHeaderException : java/ public fun getSentryTraceHeader ()Ljava/lang/String; } +public final class io/sentry/exception/SentryEnvelopeAbortedException : java/io/IOException { + public fun (Ljava/lang/String;)V + public fun (Ljava/lang/String;Ljava/lang/Throwable;)V +} + public final class io/sentry/exception/SentryEnvelopeException : java/lang/Exception { public fun (Ljava/lang/String;)V public fun (Ljava/lang/String;Ljava/lang/Throwable;)V @@ -7984,6 +7990,7 @@ public final class io/sentry/util/FileUtils { public fun ()V public static fun createDirectory (Ljava/io/File;)Z public static fun deleteRecursively (Ljava/io/File;)Z + public static fun ensureReadableFile (Ljava/io/File;J)V public static fun inputStreamToByteArray (Ljava/io/InputStream;J)[B public static fun readBytesFromFile (Ljava/lang/String;J)[B public static fun readText (Ljava/io/File;)Ljava/lang/String; diff --git a/sentry/src/main/java/io/sentry/JsonSerializer.java b/sentry/src/main/java/io/sentry/JsonSerializer.java index 79a1c72bef3..775fd317e16 100644 --- a/sentry/src/main/java/io/sentry/JsonSerializer.java +++ b/sentry/src/main/java/io/sentry/JsonSerializer.java @@ -1,6 +1,7 @@ package io.sentry; import io.sentry.clientreport.ClientReport; +import io.sentry.clientreport.DiscardReason; import io.sentry.profilemeasurements.ProfileMeasurement; import io.sentry.profilemeasurements.ProfileMeasurementValue; import io.sentry.protocol.App; @@ -245,22 +246,34 @@ public void serialize(@NotNull SentryEnvelope envelope, @NotNull OutputStream ou writer.write("\n"); for (final SentryEnvelopeItem item : envelope.getItems()) { + final @NotNull SentryEnvelopeItem.Payload payload; + try { + payload = item.openPayload(); + } catch (Exception exception) { + // Nothing of the item is written yet, so the rest of the envelope stays valid. + options + .getLogger() + .log(SentryLevel.ERROR, "Failed to create envelope item. Dropping it.", exception); + if (item.markDropRecorded()) { + options.getClientReportRecorder().recordLostEnvelopeItem(DiscardReason.INVALID, item); + } + continue; + } + // Once the item header is written, a failure leaves the envelope invalid, so it propagates. try { - // When this throws we don't write anything and continue with the next item. - final byte[] data = item.getData(); - item.getHeader() - .serialize(new JsonObjectWriter(writer, options.getMaxDepth()), options.getLogger()); + .serialize( + new JsonObjectWriter(writer, options.getMaxDepth()), + options.getLogger(), + payload.getLength()); writer.write("\n"); writer.flush(); - outputStream.write(data); + payload.writeTo(outputStream); writer.write("\n"); - } catch (Exception exception) { - options - .getLogger() - .log(SentryLevel.ERROR, "Failed to create envelope item. Dropping it.", exception); + } finally { + payload.close(); } } } finally { diff --git a/sentry/src/main/java/io/sentry/SentryEnvelopeItem.java b/sentry/src/main/java/io/sentry/SentryEnvelopeItem.java index b754e169ba7..a86e2696984 100644 --- a/sentry/src/main/java/io/sentry/SentryEnvelopeItem.java +++ b/sentry/src/main/java/io/sentry/SentryEnvelopeItem.java @@ -5,6 +5,7 @@ import static io.sentry.vendor.Base64.NO_WRAP; import io.sentry.clientreport.ClientReport; +import io.sentry.exception.SentryEnvelopeAbortedException; import io.sentry.exception.SentryEnvelopeException; import io.sentry.protocol.SentryTransaction; import io.sentry.protocol.profiling.SentryProfile; @@ -16,10 +17,13 @@ import java.io.BufferedWriter; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; +import java.io.Closeable; import java.io.File; import java.io.FileInputStream; import java.io.IOException; +import java.io.InputStream; import java.io.InputStreamReader; +import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Reader; import java.io.Writer; @@ -29,6 +33,7 @@ import java.util.LinkedHashMap; import java.util.Map; import java.util.concurrent.Callable; +import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; @@ -45,16 +50,27 @@ public final class SentryEnvelopeItem { private static final int WRITER_BUFFER_SIZE = 512; + // Copy buffer for streaming file payloads, same as BufferedInputStream's default. + private static final int FILE_COPY_BUFFER_SIZE = 8192; + private final SentryEnvelopeItemHeader header; - // Either dataFactory is set or data needs to be set. + // Exactly one of dataFactory, data or file is set. private final @Nullable Callable dataFactory; // TODO: Can we have a slice or a reader here instead? private @Nullable byte[] data; + // The payload is read from this file each time the item is serialized and is never kept in + // memory. + private final @Nullable File file; + private final long maxFileSize; + // The same envelope is serialized more than once, for the disk cache and for sending. + private final @NotNull AtomicBoolean dropRecorded = new AtomicBoolean(false); SentryEnvelopeItem(final @NotNull SentryEnvelopeItemHeader header, final byte[] data) { this.header = Objects.requireNonNull(header, "SentryEnvelopeItemHeader is required."); this.data = data; this.dataFactory = null; + this.file = null; + this.maxFileSize = 0; } SentryEnvelopeItem( @@ -63,6 +79,19 @@ public final class SentryEnvelopeItem { this.header = Objects.requireNonNull(header, "SentryEnvelopeItemHeader is required."); this.dataFactory = Objects.requireNonNull(dataFactory, "DataFactory is required."); this.data = null; + this.file = null; + this.maxFileSize = 0; + } + + private SentryEnvelopeItem( + final @NotNull SentryEnvelopeItemHeader header, + final @NotNull File file, + final long maxFileSize) { + this.header = Objects.requireNonNull(header, "SentryEnvelopeItemHeader is required."); + this.file = file; + this.maxFileSize = maxFileSize; + this.dataFactory = null; + this.data = null; } // TODO: Should be a Stream @@ -70,12 +99,128 @@ public final class SentryEnvelopeItem { // always provide non-null values. @SuppressWarnings("NullAway") public @NotNull byte[] getData() throws Exception { + if (file != null) { + // Not cached, so the file content isn't held for the lifetime of the envelope. + return readBytesFromFile(file.getPath(), maxFileSize); + } if (data == null && dataFactory != null) { data = dataFactory.call(); } return data; } + /** + * Opens the payload for one serialization of this item. A file payload is checked and its size is + * taken here, so a missing, unreadable or too large file fails before anything is written. + */ + @NotNull + Payload openPayload() throws Exception { + if (file == null) { + return new BytesPayload(getData()); + } + final int length = checkedFileLength(file, maxFileSize); + return new FilePayload(file, length, new FileInputStream(file)); + } + + /** Returns true only for the first call, so an item that is dropped is recorded once. */ + boolean markDropRecorded() { + return dropRecorded.compareAndSet(false, true); + } + + private static int checkedFileLength(final @NotNull File file, final long maxFileSize) + throws IOException { + FileUtils.ensureReadableFile(file, maxFileSize); + return (int) Math.min(file.length(), maxFileSize); + } + + interface Payload extends Closeable { + int getLength(); + + /** + * Writes exactly {@link #getLength()} bytes. + * + * @throws SentryEnvelopeAbortedException if that's no longer possible, for example because a + * file changed. The item header was already written with the length, so the envelope is + * invalid. + */ + void writeTo(@NotNull OutputStream outputStream) throws IOException; + } + + private static final class BytesPayload implements Payload { + private final @NotNull byte[] bytes; + + BytesPayload(final @NotNull byte[] bytes) { + this.bytes = bytes; + } + + @Override + public int getLength() { + return bytes.length; + } + + @Override + public void writeTo(final @NotNull OutputStream outputStream) throws IOException { + outputStream.write(bytes); + } + + @Override + public void close() {} + } + + private static final class FilePayload implements Payload { + private final @NotNull File file; + private final int length; + private final @NotNull InputStream inputStream; + + FilePayload( + final @NotNull File file, final int length, final @NotNull InputStream inputStream) { + this.file = file; + this.length = length; + this.inputStream = inputStream; + } + + @Override + public int getLength() { + return length; + } + + @Override + public void writeTo(final @NotNull OutputStream outputStream) throws IOException { + final byte[] buffer = new byte[FILE_COPY_BUFFER_SIZE]; + int remaining = length; + while (remaining > 0) { + final int read = read(buffer, Math.min(buffer.length, remaining)); + if (read < 0) { + throw new SentryEnvelopeAbortedException( + String.format( + "File '%s' shrank by at least %d bytes while it was written to the envelope.", + file.getName(), remaining)); + } + outputStream.write(buffer, 0, read); + remaining -= read; + } + if (read(buffer, 1) >= 0) { + throw new SentryEnvelopeAbortedException( + String.format("File '%s' grew while it was written to the envelope.", file.getName())); + } + } + + private int read(final @NotNull byte[] buffer, final int count) + throws SentryEnvelopeAbortedException { + try { + return inputStream.read(buffer, 0, count); + } catch (IOException e) { + throw new SentryEnvelopeAbortedException( + String.format("Failed to read file '%s'.", file.getName()), e); + } + } + + @Override + public void close() throws IOException { + inputStream.close(); + } + } + public @NotNull SentryEnvelopeItemHeader getHeader() { return header; } @@ -231,6 +376,11 @@ public static SentryEnvelopeItem fromAttachment( final @NotNull Attachment attachment, final long maxAttachmentSize) { + final @Nullable String pathname = attachment.getPathname(); + if (attachment.getBytes() == null && attachment.getSerializable() == null && pathname != null) { + return fromAttachmentFile(attachment, new File(pathname), maxAttachmentSize); + } + final CachedItem cachedItem = new CachedItem(() -> { if (attachment.getBytes() != null) { @@ -247,8 +397,6 @@ public static SentryEnvelopeItem fromAttachment( ensureAttachmentSizeLimit(data.length, maxAttachmentSize, attachment.getFilename()); return data; } - } else if (attachment.getPathname() != null) { - return readBytesFromFile(attachment.getPathname(), maxAttachmentSize); } else if (attachment.getByteProvider() != null) { @SuppressWarnings("NullableProblems") final @Nullable byte[] data = attachment.getByteProvider().call(); @@ -277,6 +425,23 @@ public static SentryEnvelopeItem fromAttachment( return new SentryEnvelopeItem(itemHeader, () -> cachedItem.getBytes()); } + private static @NotNull SentryEnvelopeItem fromAttachmentFile( + final @NotNull Attachment attachment, + final @NotNull File file, + final long maxAttachmentSize) { + // The item header stores the length as an int. + final long maxFileSize = Math.min(maxAttachmentSize, Integer.MAX_VALUE); + final SentryEnvelopeItemHeader itemHeader = + new SentryEnvelopeItemHeader( + SentryItemType.Attachment, + () -> checkedFileLength(file, maxFileSize), + attachment.getContentType(), + attachment.getFilename(), + attachment.getAttachmentType()); + + return new SentryEnvelopeItem(itemHeader, file, maxFileSize); + } + private static void ensureAttachmentSizeLimit( final long size, final long maxAttachmentSize, final @NotNull String filename) throws SentryEnvelopeException { diff --git a/sentry/src/main/java/io/sentry/SentryEnvelopeItemHeader.java b/sentry/src/main/java/io/sentry/SentryEnvelopeItemHeader.java index eaacee9957a..3aaaf794ab9 100644 --- a/sentry/src/main/java/io/sentry/SentryEnvelopeItemHeader.java +++ b/sentry/src/main/java/io/sentry/SentryEnvelopeItemHeader.java @@ -203,6 +203,13 @@ public static final class JsonKeys { @Override public void serialize(final @NotNull ObjectWriter writer, final @NotNull ILogger logger) throws IOException { + serialize(writer, logger, getLength()); + } + + /** Serializes this header with the length of the payload that is written after it. */ + void serialize( + final @NotNull ObjectWriter writer, final @NotNull ILogger logger, final int length) + throws IOException { writer.beginObject(); if (contentType != null) { writer.name(JsonKeys.CONTENT_TYPE).value(contentType); @@ -220,7 +227,7 @@ public void serialize(final @NotNull ObjectWriter writer, final @NotNull ILogger if (itemCount != null) { writer.name(JsonKeys.ITEM_COUNT).value(itemCount); } - writer.name(JsonKeys.LENGTH).value(getLength()); + writer.name(JsonKeys.LENGTH).value(length); final @Nullable Integer resolvedMetaLength = getMetaLength(); if (resolvedMetaLength != null) { writer.name(JsonKeys.META_LENGTH).value(resolvedMetaLength); diff --git a/sentry/src/main/java/io/sentry/cache/EnvelopeCache.java b/sentry/src/main/java/io/sentry/cache/EnvelopeCache.java index d3f473cfbc9..89e9d07f19d 100644 --- a/sentry/src/main/java/io/sentry/cache/EnvelopeCache.java +++ b/sentry/src/main/java/io/sentry/cache/EnvelopeCache.java @@ -363,6 +363,10 @@ private boolean writeEnvelopeToDisk( options .getLogger() .log(ERROR, e, "Error writing Envelope %s to offline storage", file.getAbsolutePath()); + // A partially written envelope can't be read back, so it must not stay in the cache. + if (file.exists() && !file.delete()) { + options.getLogger().log(ERROR, "Failed to delete: %s", file.getAbsolutePath()); + } return false; } return true; diff --git a/sentry/src/main/java/io/sentry/clientreport/DiscardReason.java b/sentry/src/main/java/io/sentry/clientreport/DiscardReason.java index 4fc424dfa1a..d3d9b8773be 100644 --- a/sentry/src/main/java/io/sentry/clientreport/DiscardReason.java +++ b/sentry/src/main/java/io/sentry/clientreport/DiscardReason.java @@ -10,7 +10,8 @@ public enum DiscardReason { BEFORE_SEND("before_send"), CALLBACK_ERROR("callback_error"), EVENT_PROCESSOR("event_processor"), // also for ignored exceptions - BACKPRESSURE("backpressure"); + BACKPRESSURE("backpressure"), + INVALID("invalid"); private final String reason; diff --git a/sentry/src/main/java/io/sentry/exception/SentryEnvelopeAbortedException.java b/sentry/src/main/java/io/sentry/exception/SentryEnvelopeAbortedException.java new file mode 100644 index 00000000000..cd99c70a130 --- /dev/null +++ b/sentry/src/main/java/io/sentry/exception/SentryEnvelopeAbortedException.java @@ -0,0 +1,25 @@ +package io.sentry.exception; + +import java.io.IOException; +import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.Nullable; + +/** + * Thrown when an envelope can't be serialized completely after part of it was written, for example + * because a file payload changed or became unreadable. The partial output is invalid and must not + * be sent or kept. + */ +@ApiStatus.Internal +public final class SentryEnvelopeAbortedException extends IOException { + + private static final long serialVersionUID = 4370390935163224155L; + + public SentryEnvelopeAbortedException(final @Nullable String message) { + super(message); + } + + public SentryEnvelopeAbortedException( + final @Nullable String message, final @Nullable Throwable cause) { + super(message, cause); + } +} diff --git a/sentry/src/main/java/io/sentry/transport/AsyncHttpTransport.java b/sentry/src/main/java/io/sentry/transport/AsyncHttpTransport.java index adf9f749d5c..9a8d1625f83 100644 --- a/sentry/src/main/java/io/sentry/transport/AsyncHttpTransport.java +++ b/sentry/src/main/java/io/sentry/transport/AsyncHttpTransport.java @@ -12,6 +12,7 @@ import io.sentry.UncaughtExceptionHandlerIntegration; import io.sentry.cache.IEnvelopeCache; import io.sentry.clientreport.DiscardReason; +import io.sentry.exception.SentryEnvelopeAbortedException; import io.sentry.hints.Cached; import io.sentry.hints.DiskFlushNotification; import io.sentry.hints.Enqueable; @@ -321,6 +322,13 @@ public void run() { throw new IllegalStateException(message); } + } catch (SentryEnvelopeAbortedException e) { + // A file payload changed or became unreadable mid-write, so the envelope is dropped. + envelopeCache.discard(envelope); + options + .getClientReportRecorder() + .recordLostEnvelope(DiscardReason.INVALID, envelopeWithClientReport); + throw new IllegalStateException("The envelope could not be serialized.", e); } catch (IOException e) { // Failure due to IO is allowed to retry the event HintUtils.runIfHasType( diff --git a/sentry/src/main/java/io/sentry/transport/HttpConnection.java b/sentry/src/main/java/io/sentry/transport/HttpConnection.java index 34abeb31835..e57f1585ce6 100644 --- a/sentry/src/main/java/io/sentry/transport/HttpConnection.java +++ b/sentry/src/main/java/io/sentry/transport/HttpConnection.java @@ -7,6 +7,7 @@ import io.sentry.RequestDetails; import io.sentry.SentryEnvelope; import io.sentry.SentryOptions; +import io.sentry.exception.SentryEnvelopeAbortedException; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; @@ -151,11 +152,16 @@ HttpURLConnection open() throws IOException { public @NotNull TransportResult send(final @NotNull SentryEnvelope envelope) throws IOException { options.getSocketTagger().tagSockets(); final HttpURLConnection connection = createConnection(); - TransportResult result; try (final OutputStream outputStream = connection.getOutputStream(); final GZIPOutputStream gzip = new GZIPOutputStream(outputStream)) { options.getSerializer().serialize(envelope, gzip); + } catch (SentryEnvelopeAbortedException e) { + // Without a streaming mode the request body is buffered until the response is read, so + // disconnecting now sends nothing. + connection.disconnect(); + options.getSocketTagger().untagSockets(); + throw e; } catch (Throwable e) { options .getLogger() @@ -163,11 +169,12 @@ HttpURLConnection open() throws IOException { ERROR, e, "An exception occurred while submitting the envelope to the Sentry server."); + } + try { + return readAndLog(connection); } finally { - result = readAndLog(connection); options.getSocketTagger().untagSockets(); } - return result; } /** diff --git a/sentry/src/main/java/io/sentry/util/FileUtils.java b/sentry/src/main/java/io/sentry/util/FileUtils.java index 827d83a0399..794b02a2f57 100644 --- a/sentry/src/main/java/io/sentry/util/FileUtils.java +++ b/sentry/src/main/java/io/sentry/util/FileUtils.java @@ -92,7 +92,24 @@ public static boolean createDirectory(final @NotNull File directory) { */ public static byte[] readBytesFromFile(String pathname, long maxFileLength) throws IOException, SecurityException { - File file = new File(pathname); + ensureReadableFile(new File(pathname), maxFileLength); + + try (FileInputStream fileInputStream = new FileInputStream(pathname); + BufferedInputStream inputStream = new BufferedInputStream(fileInputStream); ) { + return inputStreamToByteArray(inputStream, maxFileLength); + } + } + + /** + * Checks that a path exists, is a readable file and is not larger than the max size allowed. + * + * @param file file to check + * @param maxFileLength the maximum allowed file size in bytes + * @throws IOException if any of the checks fails + */ + public static void ensureReadableFile(final @NotNull File file, final long maxFileLength) + throws IOException, SecurityException { + final @NotNull String pathname = file.getPath(); if (!file.exists()) { throw new IOException(String.format("File '%s' doesn't exists", file.getName())); @@ -115,11 +132,6 @@ public static byte[] readBytesFromFile(String pathname, long maxFileLength) + "than the maximum allowed size of %d bytes.", pathname, file.length(), maxFileLength)); } - - try (FileInputStream fileInputStream = new FileInputStream(pathname); - BufferedInputStream inputStream = new BufferedInputStream(fileInputStream); ) { - return inputStreamToByteArray(inputStream, maxFileLength); - } } /** diff --git a/sentry/src/test/java/io/sentry/SentryEnvelopeItemTest.kt b/sentry/src/test/java/io/sentry/SentryEnvelopeItemTest.kt index 702b052b7c2..bfb05333cac 100644 --- a/sentry/src/test/java/io/sentry/SentryEnvelopeItemTest.kt +++ b/sentry/src/test/java/io/sentry/SentryEnvelopeItemTest.kt @@ -1,6 +1,9 @@ package io.sentry import com.google.common.truth.Truth.assertThat +import io.sentry.clientreport.DiscardReason +import io.sentry.clientreport.IClientReportRecorder +import io.sentry.exception.SentryEnvelopeAbortedException import io.sentry.exception.SentryEnvelopeException import io.sentry.protocol.ReplayRecordingSerializationTest import io.sentry.protocol.SentryId @@ -34,6 +37,7 @@ import org.junit.Rule import org.junit.rules.TemporaryFolder import org.mockito.kotlin.any import org.mockito.kotlin.mock +import org.mockito.kotlin.times import org.mockito.kotlin.verify import org.mockito.kotlin.whenever import org.msgpack.core.MessagePack @@ -164,6 +168,133 @@ class SentryEnvelopeItemTest { assertAttachment(attachment, fixture.bytesAllowed, item) } + @Test + fun `fromAttachment with file sets the header length to the file size`() { + val file = tmpDir.newFile("attachment.txt") + file.writeBytes(fixture.bytes) + + val item = + SentryEnvelopeItem.fromAttachment( + fixture.serializer, + fixture.options.logger, + Attachment(file.path), + fixture.maxAttachmentSize, + ) + + assertThat(item.header.length).isEqualTo(fixture.bytes.size) + } + + @Test + fun `fromAttachment with file reads the file each time the envelope is serialized`() { + val file = tmpDir.newFile("attachment.txt") + file.writeText("first") + val item = + SentryEnvelopeItem.fromAttachment( + fixture.serializer, + fixture.options.logger, + Attachment(file.path), + fixture.maxAttachmentSize, + ) + val envelope = SentryEnvelope(SentryEnvelopeHeader(SentryId()), listOf(item)) + + val first = serializeEnvelope(envelope) + file.writeText("second!") + val second = serializeEnvelope(envelope) + + assertThat(first).contains("\"length\":5}\nfirst\n") + assertThat(second).contains("\"length\":7}\nsecond!\n") + } + + @Test + fun `fromAttachment with file deleted before serialization drops only that item`() { + val file = tmpDir.newFile("attachment.txt") + file.writeBytes(fixture.bytes) + val fileItem = + SentryEnvelopeItem.fromAttachment( + fixture.serializer, + fixture.options.logger, + Attachment(file.path), + fixture.maxAttachmentSize, + ) + val bytesItem = + SentryEnvelopeItem.fromAttachment( + fixture.serializer, + fixture.options.logger, + Attachment("bytes".toByteArray(), "bytes.txt"), + fixture.maxAttachmentSize, + ) + val envelope = SentryEnvelope(SentryEnvelopeHeader(SentryId()), listOf(fileItem, bytesItem)) + + file.delete() + val serialized = serializeEnvelope(envelope) + + assertThat(serialized).doesNotContain("attachment.txt") + assertThat(serialized).contains("\"filename\":\"bytes.txt\"") + assertThat(serialized).contains("\"length\":5}\nbytes\n") + } + + @Test + fun `fromAttachment with file deleted before serialization records it as invalid once`() { + val recorder = mock() + fixture.options.clientReportRecorder = recorder + val file = tmpDir.newFile("attachment.txt") + file.writeBytes(fixture.bytes) + val item = fileAttachmentItem(file) + val envelope = SentryEnvelope(SentryEnvelopeHeader(SentryId()), listOf(item)) + + file.delete() + serializeEnvelope(envelope) + serializeEnvelope(envelope) + + verify(recorder, times(1)).recordLostEnvelopeItem(DiscardReason.INVALID, item) + } + + @Test + fun `fromAttachment with file aborts when the file shrinks while it is written`() { + val file = tmpDir.newFile("attachment.txt") + file.writeText("hello") + val item = fileAttachmentItem(file) + + item.openPayload().use { payload -> + RandomAccessFile(file, "rw").use { it.setLength(2) } + assertFailsWith { payload.writeTo(ByteArrayOutputStream()) } + } + } + + @Test + fun `fromAttachment with file aborts when the file grows while it is written`() { + val file = tmpDir.newFile("attachment.txt") + file.writeText("hello") + val item = fileAttachmentItem(file) + + item.openPayload().use { payload -> + file.appendText(" world") + assertFailsWith { payload.writeTo(ByteArrayOutputStream()) } + } + } + + @Test + fun `envelope serialization fails when a file shrinks while the envelope is written`() { + val file = tmpDir.newFile("attachment.bin") + file.writeBytes(ByteArray(20_000)) + val envelope = + SentryEnvelope(SentryEnvelopeHeader(SentryId()), listOf(fileAttachmentItem(file))) + val output = + object : ByteArrayOutputStream() { + override fun write(b: ByteArray, off: Int, len: Int) { + // The first large write is the first chunk of the file payload. + if (len >= 8192) { + RandomAccessFile(file, "rw").use { it.setLength(10_000) } + } + super.write(b, off, len) + } + } + + assertFailsWith { + fixture.serializer.serialize(envelope, output) + } + } + @Test fun `fromAttachment with 2MB file`() { val file = File(fixture.pathname) @@ -840,6 +971,20 @@ class SentryEnvelopeItemTest { assertArrayEquals(expectedBytes, actualItem.data) } + private fun fileAttachmentItem(file: File): SentryEnvelopeItem = + SentryEnvelopeItem.fromAttachment( + fixture.serializer, + fixture.options.logger, + Attachment(file.path), + fixture.maxAttachmentSize, + ) + + private fun serializeEnvelope(envelope: SentryEnvelope): String { + val stream = ByteArrayOutputStream() + fixture.serializer.serialize(envelope, stream) + return stream.toString("UTF-8") + } + private fun serialize(serializable: JsonSerializable): ByteArray { ByteArrayOutputStream().use { stream -> BufferedWriter(OutputStreamWriter(stream, Charset.forName("UTF-8"))).use { writer -> diff --git a/sentry/src/test/java/io/sentry/cache/EnvelopeCacheTest.kt b/sentry/src/test/java/io/sentry/cache/EnvelopeCacheTest.kt index 0cc2c968195..e9033dc9510 100644 --- a/sentry/src/test/java/io/sentry/cache/EnvelopeCacheTest.kt +++ b/sentry/src/test/java/io/sentry/cache/EnvelopeCacheTest.kt @@ -17,6 +17,7 @@ import io.sentry.Session.State.Ok import io.sentry.UncaughtExceptionHandlerIntegration.UncaughtExceptionHint import io.sentry.cache.EnvelopeCache.PREFIX_CURRENT_SESSION_FILE import io.sentry.cache.EnvelopeCache.SUFFIX_SESSION_FILE +import io.sentry.exception.SentryEnvelopeAbortedException import io.sentry.hints.AbnormalExit import io.sentry.hints.NativeCrashExit import io.sentry.hints.SessionEndHint @@ -24,6 +25,7 @@ import io.sentry.hints.SessionStartHint import io.sentry.protocol.SentryId import io.sentry.util.HintUtils import java.io.File +import java.io.OutputStream import java.io.Writer import java.nio.file.Files import java.nio.file.Path @@ -121,6 +123,22 @@ class EnvelopeCacheTest { assertFalse(file.exists()) } + @Test + fun `deletes the partially written envelope file when serialization fails`() { + val serializer = mock() + val cache = fixture.getSUT { it.setSerializer(serializer) } + val envelope = SentryEnvelope(SentryId(), null, emptyList()) + whenever(serializer.serialize(same(envelope), any())).thenAnswer { + it.getArgument(1).write("partial".toByteArray()) + throw SentryEnvelopeAbortedException("changed") + } + + val didStore = cache.storeEnvelope(envelope, Hint()) + + assertFalse(didStore) + assertThat(File(fixture.options.cacheDirPath!!).listFiles()).isEmpty() + } + @Test fun `creates current file on session start`() { val cache = fixture.getSUT() diff --git a/sentry/src/test/java/io/sentry/transport/AsyncHttpTransportClientReportTest.kt b/sentry/src/test/java/io/sentry/transport/AsyncHttpTransportClientReportTest.kt index 367f1776665..5d168bfc595 100644 --- a/sentry/src/test/java/io/sentry/transport/AsyncHttpTransportClientReportTest.kt +++ b/sentry/src/test/java/io/sentry/transport/AsyncHttpTransportClientReportTest.kt @@ -11,6 +11,7 @@ import io.sentry.clientreport.ClientReportTestHelper.Companion.uncaughtException import io.sentry.clientreport.DiscardReason import io.sentry.clientreport.IClientReportRecorder import io.sentry.dsnString +import io.sentry.exception.SentryEnvelopeAbortedException import io.sentry.hints.Retryable import io.sentry.protocol.User import io.sentry.util.HintUtils @@ -302,6 +303,32 @@ class AsyncHttpTransportClientReportTest { verifyNoMoreInteractions(fixture.clientReportRecorder) } + @Test + fun `records lost envelope as invalid and does not retry when serialization is aborted`() { + // given + givenSetup() + whenever(fixture.connection.send(any())).thenThrow(SentryEnvelopeAbortedException("changed")) + + // when + val retryableHint = retryableHint() + assertFailsWith(java.lang.IllegalStateException::class) { + fixture.getSUT().send(fixture.envelopeBeforeAttachingClientReport, retryableHint) + } + + // then + verify(fixture.clientReportRecorder, times(1)) + .attachReportToEnvelope(same(fixture.envelopeBeforeAttachingClientReport)) + verify(fixture.clientReportRecorder, times(1)) + .recordLostEnvelope( + eq(DiscardReason.INVALID), + same(fixture.envelopeAfterAttachingClientReport), + ) + verifyNoMoreInteractions(fixture.clientReportRecorder) + val sentrySdkHint = HintUtils.getSentrySdkHint(retryableHint) + assertFalse((sentrySdkHint as Retryable).isRetry) + verify(fixture.envelopeCache).discard(fixture.envelopeBeforeAttachingClientReport) + } + @Test fun `records lost envelope on io exception for non retryable`() { // given diff --git a/sentry/src/test/java/io/sentry/transport/HttpConnectionTest.kt b/sentry/src/test/java/io/sentry/transport/HttpConnectionTest.kt index 610b70803c9..8b9c60cde54 100644 --- a/sentry/src/test/java/io/sentry/transport/HttpConnectionTest.kt +++ b/sentry/src/test/java/io/sentry/transport/HttpConnectionTest.kt @@ -10,8 +10,10 @@ import io.sentry.SentryLevel import io.sentry.SentryOptions import io.sentry.SentryOptions.Proxy import io.sentry.Session +import io.sentry.exception.SentryEnvelopeAbortedException import io.sentry.protocol.User import java.io.IOException +import java.io.OutputStream import java.net.InetSocketAddress import java.net.Proxy.Type import java.net.URL @@ -20,6 +22,7 @@ import javax.net.ssl.HttpsURLConnection import javax.net.ssl.SSLSocketFactory import kotlin.test.Test import kotlin.test.assertEquals +import kotlin.test.assertFailsWith import kotlin.test.assertFalse import kotlin.test.assertNull import kotlin.test.assertTrue @@ -81,6 +84,20 @@ class HttpConnectionTest { assertTrue(result.isSuccess) } + @Test + fun `does not send the request when the envelope serialization is aborted`() { + val transport = fixture.getSUT() + val envelope = SentryEnvelope.from(fixture.serializer, createSession(), null) + whenever(fixture.serializer.serialize(eq(envelope), any())) + .thenThrow(SentryEnvelopeAbortedException("changed")) + + assertFailsWith { transport.send(envelope) } + + verify(fixture.connection, never()).responseCode + verify(fixture.connection).disconnect() + verify(fixture.socketTagger).untagSockets() + } + @Test fun `uses Retry-After header if X-Sentry-Rate-Limit is not set when sending an envelope`() { val transport = fixture.getSUT()