fix(s3): make GetObject atomic against concurrent same-key overwrites (#2874)

* fix(s3): make GetObject atomic against concurrent same-key overwrites

A GetObject racing PutObject overwrites of the same key could return a
torn response assembled from two object versions: Content-Length, ETag,
and checksum headers from one version with body bytes from another.
When the newer body was longer than the advertised Content-Length, the
surplus bytes stayed on the wire and corrupted the keep-alive
connection's HTTP/1.1 framing (clients then log "Unsolicited response
received on idle HTTP channel", and the next request on that pooled
connection breaks). AWS S3 gives a concurrent read exactly one complete
version, never a mix.

Two gaps combined into the tear:

- S3Service.getObject read metadata and data as two unlocked reads,
  while writers install them as two separate stores (objectStore, then
  writeFile) under the bucket monitor. Take the same monitor around the
  read pair so it can never straddle a write.
- S3Controller resolved response headers from a headObject snapshot but
  streamed the body lazily at entity-write time via openObjectStream,
  re-reading whatever data the key held by then. Serve both the full
  and Range responses from the byte[] captured atomically with the
  metadata, and fail loudly if a snapshot's data ever disagrees with
  its declared size instead of corrupting the response framing.

The website index path now uses getObject so the served snapshot
carries its matching body as well.

Regression test: S3ConcurrentWriteReadTest#
concurrentOverwriteNeverPairsMetadataWithAnotherVersionsBody alternates
two fixed bodies of different lengths under concurrent readers and
asserts every read returns one complete version whose size and ETag
match its bytes. It fails on the previous code within seconds
("declared size=300 but body has 256 bytes") and passes with the fix.
Verified end-to-end with an AWS SDK Go v2 raced GET/PUT reproduction:
torn bodies, CRC checksum mismatches, and unsolicited-response warnings
on floci/floci:1.7.0; zero across 4 runs (~900k reads) on the patched
build. S3 suite: 1070/1070 green.

Change-Id: I4f4dbef49d85e0cdf13aaaca66dc8592db0fbed0
Signed-off-by: Thomas Kosiewski <tk@coder.com>

* fix(s3): serve conditional GETs and website requests from one snapshot

Review follow-ups on the torn-GET fix:

- Conditional GETs evaluated If-Match/If-None-Match/If-(Un)Modified-Since
  against a separate headObject fetch and then served a later getObject
  snapshot, so an overwrite landing between the two could return a
  version the precondition never approved. Preconditions are now
  evaluated against the same atomic snapshot that is served, making the
  decision and the returned version consistent by construction.

- Website HEAD requests loaded the index document's bytes only to
  discard them (headOnlyResponse strips the entity). The website
  resolution carries metadata only again; the controller fetches the
  atomic metadata+body snapshot just for GET renders, and HEAD builds
  its headers without touching the data. Shared response-header
  construction is extracted into objectResponseHeaders.

Change-Id: Ia116b6c6886febfde2bdabe3b4e2b4695617ab4f
Signed-off-by: Thomas Kosiewski <tk@coder.com>

---------

Signed-off-by: Thomas Kosiewski <tk@coder.com>
This commit is contained in:
Thomas Kosiewski authored and GitHub committed 2026-09-01 09:08:53 -04:00
1 parent 225233c192
commit b4aab999f7
3 files changed
+161 -55

No files matched your search

@@ -6,6 +6,7 @@ import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
@@ -87,6 +88,83 @@ class S3ConcurrentWriteReadTest {
assertEquals(true, reads.get() > 0, "reader threads never observed the object");
}
/**
* Regression test for torn GET responses under same-key overwrites: metadata (size, ETag,
* checksums — the source of {@code Content-Length} and {@code x-amz-checksum-*} response
* headers) and body bytes must always come from the same version. Writers install metadata
* and data as two separate stores under the bucket monitor, so a getObject that reads the
* pair without that monitor can return version N's metadata with version N+1's bytes; on the
* wire that surfaces as a body longer than the declared Content-Length, whose surplus bytes
* corrupt the keep-alive connection's framing. AWS S3 reads are atomic: one complete version,
* never a mix.
*/
@Test
void concurrentOverwriteNeverPairsMetadataWithAnotherVersionsBody() throws Exception {
S3Service s3 = new S3Service(new InMemoryStorage<>(), new InMemoryStorage<>(),
tempDir.resolve("s3"), false);
String bucket = "torn-read-repro";
String key = "torn-probe";
s3.createBucket(bucket, "us-east-1");
byte[] bodyA = new byte[256];
Arrays.fill(bodyA, (byte) 'a');
byte[] bodyB = new byte[300];
Arrays.fill(bodyB, (byte) 'b');
String eTagA = new S3Object(bucket, key, bodyA, null).getETag();
String eTagB = new S3Object(bucket, key, bodyB, null).getETag();
s3.putObject(bucket, key, bodyA, "application/octet-stream", Map.of());
int writers = 2;
int readers = 4;
int iterations = 4000;
AtomicReference<String> firstTear = new AtomicReference<>();
AtomicInteger reads = new AtomicInteger();
volatileDone done = new volatileDone();
Thread[] threads = new Thread[writers + readers];
for (int w = 0; w < writers; w++) {
threads[w] = new Thread(() -> {
for (int i = 0; i < iterations && firstTear.get() == null; i++) {
s3.putObject(bucket, key, i % 2 == 0 ? bodyA : bodyB,
"application/octet-stream", Map.of());
}
done.count.incrementAndGet();
});
}
for (int r = 0; r < readers; r++) {
threads[writers + r] = new Thread(() -> {
while (done.count.get() < writers && firstTear.get() == null) {
S3Object obj = s3.getObject(bucket, key);
byte[] data = obj.getData();
reads.incrementAndGet();
String tear = null;
if (data == null || (!Arrays.equals(data, bodyA) && !Arrays.equals(data, bodyB))) {
tear = "body is neither version: length="
+ (data == null ? "null" : data.length);
} else if (obj.getSize() != data.length) {
tear = "declared size=" + obj.getSize() + " but body has " + data.length
+ " bytes (Content-Length/body mismatch)";
} else if (!obj.getETag().equals(data.length == bodyA.length ? eTagA : eTagB)) {
tear = "ETag " + obj.getETag() + " does not match the returned "
+ data.length + "-byte body";
}
if (tear != null) {
firstTear.compareAndSet(null, tear);
return;
}
}
});
}
for (Thread t : threads) t.start();
for (Thread t : threads) {
t.join(60_000);
assertFalse(t.isAlive(), "thread did not finish within the join timeout");
}
assertNull(firstTear.get(), firstTear.get());
assertEquals(true, reads.get() > 0, "reader threads never observed the object");
}
/** Tiny holder so the reader loop can see writers finishing without a shared executor. */
private static final class volatileDone {
final AtomicInteger count = new AtomicInteger();