From 54333b1a9f0a59fe161255362b0263b9aed14605 Mon Sep 17 00:00:00 2001 From: Jithesh Thekkarikottil Rajan Date: Thu, 3 Dec 2026 07:13:17 -0800 Subject: [PATCH] Inventory recorded named-blob manifests by exact version Add a read-only command that validates recorded manifests for supplied version tuples without fetching blob data. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- ambry-named-mysql/README.md | 38 +++++ ambry-named-mysql/build.gradle | 4 + ...NamedBlobManifestStoreIntegrationTest.java | 135 +++++++++++++++ .../named/NamedBlobManifestInventory.java | 157 ++++++++++++++++++ .../ambry/named/NamedBlobManifestStore.java | 111 +++++++++---- .../named/NamedBlobManifestInventoryTest.java | 63 +++++++ build.gradle | 1 + 7 files changed, 479 insertions(+), 30 deletions(-) create mode 100644 ambry-named-mysql/src/main/java/com/github/ambry/named/NamedBlobManifestInventory.java create mode 100644 ambry-named-mysql/src/test/java/com/github/ambry/named/NamedBlobManifestInventoryTest.java diff --git a/ambry-named-mysql/README.md b/ambry-named-mysql/README.md index 919c88c07c..02ce922a95 100644 --- a/ambry-named-mysql/README.md +++ b/ambry-named-mysql/README.md @@ -16,6 +16,44 @@ Configure the reader data source for `READ COMMITTED` or stronger on every check A pool shared with the publisher must use `REPEATABLE READ`; readers do not change its isolation. Distinct roots can reference the same child; finding its ID does not authorize deletion. +## Inspecting recorded manifests + +The read-only inventory checks at most 32 supplied version tuples on one database, with one bounded manifest lookup +per tuple. Each connection must use `READ COMMITTED` isolation or stronger. Give the command a private UTF-8 JSON file +containing `[accountId, containerId, blobName, version]` arrays. Use decimal strings for versions to preserve all 64 +bits. For example: + +```json +[[17, 4, "folder/example", "1234567890123456789"]] +``` + +Set `AMBRY_INVENTORY_JDBC_URL` to the approved, authoritative database's JDBC URL (include the database name and use +`sslMode=VERIFY_IDENTITY` for remote connections), `AMBRY_INVENTORY_JDBC_USER` to an identity with SELECT access only, +and `AMBRY_INVENTORY_JDBC_PASSWORD` only if required. Do not put credentials in the URL or on the command line. The +command is verified against a local test fixture only. Using it against a TLS endpoint that requires a private CA or +client certificate requires separate validation of the JDBC trust and key store setup. + +The JDBC `connectTimeout` and `socketTimeout` default to five seconds each. Connector/J URL properties with those names +override the defaults (values are in milliseconds). They limit connection establishment and socket reads, respectively, +not the duration of a query or the whole run. + +```sh +./gradlew --quiet :ambry-named-mysql:manifestInventory \ + --args='/path/to/private-tuples.json /path/to/new-report.jsonl' +``` + +The new report file contains JSON Lines keyed by one-based input position: + +- `verified`: the recorded row passed checksum and descriptor-framing checks. The recorded count includes duplicate + IDs. The command does not independently validate child IDs or check that chunks exist. +- `missing`: no exact committed row was observed on the selected database. +- `invalid`: the row failed validation. + +Exit zero means the report completed, even if it contains `invalid` rows. A nonzero exit indicates an incomplete run. +If the run is interrupted, rerun the original input into a fresh report to preserve the input positions. The inventory +reads no root or chunk data, changes no rows, discovers no additional versions, and says nothing about reachability or +bytes safe to reclaim. + ## Compatibility and limits These package-private methods have no frontend caller. They require one authoritative InnoDB writer for the name range, diff --git a/ambry-named-mysql/build.gradle b/ambry-named-mysql/build.gradle index 8b13789179..21c3591ec9 100644 --- a/ambry-named-mysql/build.gradle +++ b/ambry-named-mysql/build.gradle @@ -1 +1,5 @@ +tasks.register('manifestInventory', JavaExec) { + classpath = sourceSets.main.runtimeClasspath + mainClass.set('com.github.ambry.named.NamedBlobManifestInventory') +} diff --git a/ambry-named-mysql/src/integration-test/java/com/github/ambry/named/NamedBlobManifestStoreIntegrationTest.java b/ambry-named-mysql/src/integration-test/java/com/github/ambry/named/NamedBlobManifestStoreIntegrationTest.java index 69c053e6c1..f555d44c83 100644 --- a/ambry-named-mysql/src/integration-test/java/com/github/ambry/named/NamedBlobManifestStoreIntegrationTest.java +++ b/ambry-named-mysql/src/integration-test/java/com/github/ambry/named/NamedBlobManifestStoreIntegrationTest.java @@ -8,7 +8,12 @@ import static org.mockito.AdditionalAnswers.delegatesTo; import static org.mockito.Mockito.*; +import java.io.ByteArrayInputStream; import java.io.InputStream; +import java.io.StringWriter; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; @@ -35,6 +40,7 @@ import java.util.stream.Collectors; import javax.sql.DataSource; import org.json.JSONArray; +import org.json.JSONObject; import org.junit.Test; import com.codahale.metrics.MetricRegistry; import com.github.ambry.account.Account; @@ -75,6 +81,135 @@ public void testDetachedRecoveryAcrossReplacement() throws Exception { withDatabase(NamedBlobManifestStoreIntegrationTest::exercise); } + @Test + public void testInventoryVerifiesExactPublishedTuples() throws Exception { + withDatabase((db, named) -> { + BlobId child = blob(BlobId.BlobDataType.DATACHUNK); + long exact = 9_007_199_254_740_993L; + BlobId original = blob(BlobId.BlobDataType.METADATA); + insertNamed(db, exact, original, NamedBlobState.READY); + retireOne(named, exact, original, 2, Arrays.asList(child, child).iterator()); + BlobId next = blob(BlobId.BlobDataType.METADATA); + insertNamed(db, exact + 1, next, NamedBlobState.READY); + retireOne(named, exact + 1, next, 1, Collections.singletonList(child).iterator()); + try (Connection c = db.getConnection(); PreparedStatement corrupt = c.prepareStatement( + "UPDATE named_blob_manifests_v1 SET payload=REPEAT(X'00',129) WHERE version=?")) { + corrupt.setLong(1, exact + 1); + assertEquals(1, corrupt.executeUpdate()); + } + NamedBlobManifestStore store = new NamedBlobManifestStore(db); + expectDataError("Invalid published manifest length", + () -> store.read(store.getPublished(ACCOUNT, CONTAINER, NAME, exact + 1))); + expectDataError("Invalid published manifest length", + () -> store.readVerifiedCount(ACCOUNT, CONTAINER, NAME, exact + 1)); + + JSONArray tuples = new JSONArray(); + tuples.put(new JSONArray(Arrays.asList(ACCOUNT, CONTAINER, NAME, Long.toString(exact)))); + tuples.put(new JSONArray(Arrays.asList(ACCOUNT, CONTAINER, NAME + " ", Long.toString(exact)))); + tuples.put(new JSONArray(Arrays.asList(ACCOUNT, CONTAINER, NAME, Long.toString(exact + 1)))); + for (int i = 3; i < 32; i++) { + tuples.put(tuples.getJSONArray(0)); + } + DataSource inventorySource = mock(DataSource.class); + when(inventorySource.getConnection()).thenAnswer(call -> db.getConnection()); + String[] lines = inspectInventory(tuples, new NamedBlobManifestStore(inventorySource)); + verify(inventorySource, times(tuples.length())).getConnection(); + assertEquals(32, lines.length); + JSONObject verified = new JSONObject(lines[0]); + assertEquals(1, verified.getInt("input")); + assertEquals("verified", verified.getString("status")); + assertEquals(2, verified.getInt("recorded_child_count")); + JSONObject missing = new JSONObject(lines[1]); + assertEquals(2, missing.getInt("input")); + assertEquals("missing", missing.getString("status")); + assertFalse(missing.has("recorded_child_count")); + JSONObject invalid = new JSONObject(lines[2]); + assertEquals(3, invalid.getInt("input")); + assertEquals("invalid", invalid.getString("status")); + assertFalse(invalid.has("recorded_child_count")); + JSONObject last = new JSONObject(lines[31]); + assertEquals(32, last.getInt("input")); + assertEquals("verified", last.getString("status")); + }); + } + + @Test + public void testInventoryMatchesExactUnicodeNameWithLatin1Reader() throws Exception { + withDatabase((db, named) -> { + String name = NAME + "/\uD83D\uDE80"; + BlobId child = blob(BlobId.BlobDataType.DATACHUNK); + for (long version = 1; version <= 2; version++) { + BlobId root = blob(BlobId.BlobDataType.METADATA); + insertNamed(db, name, version, root, NamedBlobState.READY); + retireOneNamed(named, name, version, root, 1, Collections.singletonList(child).iterator()); + } + String schema; + try (Connection c = db.getConnection(); Statement s = c.createStatement()) { + schema = c.getCatalog(); + assertEquals(1, s.executeUpdate("UPDATE named_blob_manifests_v1 SET child_count=0 WHERE version=2")); + } + MysqlDataSource latin1 = source(schema); + latin1.setCharacterEncoding("ISO-8859-1"); + try (Connection c = latin1.getConnection(); Statement s = c.createStatement(); + ResultSet state = s.executeQuery("SELECT @@character_set_client")) { + assertTrue(state.next()); + assertEquals("latin1", state.getString(1)); + } + JSONArray tuples = new JSONArray(); + tuples.put(new JSONArray(Arrays.asList(ACCOUNT, CONTAINER, name, "1"))); + tuples.put(new JSONArray(Arrays.asList(ACCOUNT, CONTAINER, name, "2"))); + tuples.put(new JSONArray(Arrays.asList(ACCOUNT, CONTAINER, name + " ", "2"))); + String[] lines = inspectInventory(tuples, new NamedBlobManifestStore(latin1)); + assertEquals(3, lines.length); + assertEquals("verified", new JSONObject(lines[0]).getString("status")); + assertEquals("invalid", new JSONObject(lines[1]).getString("status")); + assertEquals("missing", new JSONObject(lines[2]).getString("status")); + }); + } + + @Test + public void testInventoryRejectsInvalidDescriptorFraming() throws Exception { + withDatabase((db, named) -> { + BlobId root = blob(BlobId.BlobDataType.METADATA); + long version = 1; + insertNamed(db, version, root, NamedBlobState.READY); + retireOne(named, version, root, 1, Collections.singletonList(blob(BlobId.BlobDataType.DATACHUNK)).iterator()); + + byte[] name = NAME.getBytes(StandardCharsets.UTF_8); + byte[] hashHeader = ByteBuffer.allocate(2 * Short.BYTES + Long.BYTES + 2 * Integer.BYTES) + .putShort(ACCOUNT).putShort(CONTAINER).putLong(version).putInt(1).putInt(name.length).array(); + NamedBlobManifestStore store = new NamedBlobManifestStore(db); + NamedBlobManifestStore.Manifest manifest = store.getPublished(ACCOUNT, CONTAINER, NAME, version); + // Recompute the checksum so only the malformed descriptor framing can reject these rows. + byte[][] payloads = {{2, 1}, {1, 1, 1}}; + String[] errors = {"Invalid published child descriptor", "Trailing bytes on published manifest"}; + for (int i = 0; i < payloads.length; i++) { + byte[] payload = payloads[i]; + MessageDigest hash = MessageDigest.getInstance("SHA-256"); + hash.update(hashHeader); + hash.update(name); + hash.update(root.getID().getBytes(StandardCharsets.US_ASCII)); + hash.update((byte) 0); + try (Connection c = db.getConnection(); PreparedStatement corrupt = c.prepareStatement( + "UPDATE named_blob_manifests_v1 SET payload=?,payload_hash=? WHERE version=?")) { + corrupt.setBytes(1, payload); + corrupt.setBytes(2, hash.digest(payload)); + corrupt.setLong(3, version); + assertEquals(1, corrupt.executeUpdate()); + } + expectDataError(errors[i], () -> store.read(manifest)); + expectDataError(errors[i], () -> store.readVerifiedCount(ACCOUNT, CONTAINER, NAME, version)); + } + }); + } + + private static String[] inspectInventory(JSONArray tuples, NamedBlobManifestStore store) throws Exception { + StringWriter output = new StringWriter(); + NamedBlobManifestInventory.inspect(new ByteArrayInputStream(tuples.toString().getBytes(StandardCharsets.UTF_8)), + store, output); + return output.toString().split("\\R"); + } + private interface Scenario { void run(DataSource source, MySqlNamedBlobDb named) throws Exception; } diff --git a/ambry-named-mysql/src/main/java/com/github/ambry/named/NamedBlobManifestInventory.java b/ambry-named-mysql/src/main/java/com/github/ambry/named/NamedBlobManifestInventory.java new file mode 100644 index 0000000000..0eb92ead84 --- /dev/null +++ b/ambry-named-mysql/src/main/java/com/github/ambry/named/NamedBlobManifestInventory.java @@ -0,0 +1,157 @@ +/* + * Copyright 2026 LinkedIn Corp. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +package com.github.ambry.named; + +import java.io.IOException; +import java.io.InputStream; +import java.io.Writer; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.nio.file.StandardOpenOption; +import java.sql.SQLException; +import java.sql.SQLDataException; +import java.util.ArrayList; +import java.util.List; +import org.json.JSONObject; +import com.fasterxml.jackson.core.JsonFactory; +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.JsonToken; +import com.mysql.cj.jdbc.MysqlDataSource; + +/** On-demand inspection of explicitly supplied, exact named-version manifest keys. */ +public final class NamedBlobManifestInventory { + private static final JsonFactory JSON = new JsonFactory(); + private static final int MAX_TUPLES = 32; + // Allows worst-case JSON escaping of 350 unicode characters per name, without accepting an unbounded file. + private static final int MAX_INPUT_BYTES = 160 * 1024; + private static final int DEFAULT_JDBC_TIMEOUT_MS = 5_000; + + private NamedBlobManifestInventory() { + } + + public static void main(String[] args) { + String url = System.getenv("AMBRY_INVENTORY_JDBC_URL"); + String user = System.getenv("AMBRY_INVENTORY_JDBC_USER"); + if (args.length != 2 || url == null || url.isEmpty() || user == null || user.isEmpty()) { + System.err.println("Supply a JSON tuple file and a new report path; set AMBRY_INVENTORY_JDBC_URL and" + + " AMBRY_INVENTORY_JDBC_USER."); + System.exit(2); + return; + } + + MysqlDataSource source = new MysqlDataSource(); + source.setURL(url); + source.setUser(user); + source.setPassword(System.getenv("AMBRY_INVENTORY_JDBC_PASSWORD")); + try (InputStream input = Files.newInputStream(Paths.get(args[0])); + Writer output = Files.newBufferedWriter(Paths.get(args[1]), StandardCharsets.UTF_8, StandardOpenOption.CREATE_NEW, + StandardOpenOption.WRITE)) { + source.setConnectTimeout(DEFAULT_JDBC_TIMEOUT_MS); + source.setSocketTimeout(DEFAULT_JDBC_TIMEOUT_MS); + inspect(input, new NamedBlobManifestStore(source), output); + } catch (IllegalArgumentException | IllegalStateException | IOException e) { + System.err.println("Inventory stopped: invalid input, unsupported reader isolation, or an I/O failure."); + System.exit(1); + } catch (SQLException e) { + System.err.println("Inventory stopped: database error " + e.getErrorCode() + "."); + System.exit(1); + } + } + + static void inspect(InputStream input, NamedBlobManifestStore store, Writer output) throws IOException, SQLException { + List keys = readKeys(input); + for (int i = 0; i < keys.size(); i++) { + Key key = keys.get(i); + JSONObject result = new JSONObject().put("input", i + 1); + try { + Integer count = store.readVerifiedCount(key.account, key.container, key.name, key.version); + if (count == null) { + result.put("status", "missing"); + } else { + result.put("status", "verified").put("recorded_child_count", count); + } + } catch (SQLDataException e) { + result.put("status", "invalid"); + } + output.write(result.toString()); + output.write('\n'); + output.flush(); + } + } + + private static List readKeys(InputStream input) throws IOException { + byte[] bytes = new byte[MAX_INPUT_BYTES + 1]; + int size = 0; + while (size < bytes.length) { + int n = input.read(bytes, size, bytes.length - size); + if (n == -1) { + break; + } + size += n; + } + if (size > MAX_INPUT_BYTES) { + throw new IllegalArgumentException("Tuple file too large"); + } + String text = StandardCharsets.UTF_8.newDecoder().decode(ByteBuffer.wrap(bytes, 0, size)).toString(); + try (JsonParser parser = JSON.createParser(text)) { + requireToken(parser.nextToken(), JsonToken.START_ARRAY); + List keys = new ArrayList<>(); + for (JsonToken token = parser.nextToken(); token != JsonToken.END_ARRAY; token = parser.nextToken()) { + requireToken(token, JsonToken.START_ARRAY); + if (keys.size() == MAX_TUPLES) { + throw new IllegalArgumentException("Too many tuples"); + } + short account = Short.parseShort(readDecimal(parser)); + short container = Short.parseShort(readDecimal(parser)); + requireToken(parser.nextToken(), JsonToken.VALUE_STRING); + String name = parser.getText(); + if (name.isEmpty() || name.codePointCount(0, name.length()) > 350 || !StandardCharsets.UTF_8.newEncoder() + .canEncode(name)) { + throw new IllegalArgumentException("Invalid blob name"); + } + long version = Long.parseLong(readDecimal(parser)); + requireToken(parser.nextToken(), JsonToken.END_ARRAY); + keys.add(new Key(account, container, name, version)); + } + if (keys.isEmpty() || parser.nextToken() != null) { + throw new IllegalArgumentException("Expected 1 to " + MAX_TUPLES + " exact tuples"); + } + return keys; + } catch (JsonProcessingException e) { + throw new IllegalArgumentException("Invalid tuple file", e); + } + } + + private static void requireToken(JsonToken actual, JsonToken expected) { + if (actual != expected) { + throw new IllegalArgumentException("Expected " + expected); + } + } + + private static String readDecimal(JsonParser parser) throws IOException { + JsonToken token = parser.nextToken(); + if (token != JsonToken.VALUE_NUMBER_INT && token != JsonToken.VALUE_STRING) { + throw new IllegalArgumentException("Expected an integer"); + } + return parser.getText(); + } + + private static final class Key { + final short account; + final short container; + final String name; + final long version; + + Key(short account, short container, String name, long version) { + this.account = account; + this.container = container; + this.name = name; + this.version = version; + } + } +} diff --git a/ambry-named-mysql/src/main/java/com/github/ambry/named/NamedBlobManifestStore.java b/ambry-named-mysql/src/main/java/com/github/ambry/named/NamedBlobManifestStore.java index 9ebab8f921..b7ec094be6 100644 --- a/ambry-named-mysql/src/main/java/com/github/ambry/named/NamedBlobManifestStore.java +++ b/ambry-named-mysql/src/main/java/com/github/ambry/named/NamedBlobManifestStore.java @@ -26,6 +26,7 @@ import java.util.Objects; import java.util.TreeSet; import javax.sql.DataSource; +import org.apache.commons.codec.binary.Hex; import com.github.ambry.commons.BlobId; import com.github.ambry.protocol.NamedBlobState; import com.github.ambry.store.StoreKey; @@ -53,7 +54,12 @@ final class NamedBlobManifestStore { private static final String TABLE = "named_blob_manifests_v1"; private static final String HEADER_COLUMNS = "account_id,container_id,blob_name,version,root_id,child_count,publication_key"; + private static final String READ_HEADER_COLUMNS = "account_id,container_id,version,root_id,child_count"; private static final String KEY = "account_id=? AND container_id=? AND blob_name=? AND version=?"; + // Keep the indexed lookup, then rule out PAD SPACE aliases before decoding any header fields. + private static final String EXACT_READ_KEY = + "account_id=? AND container_id=? AND blob_name=CONVERT(UNHEX(?) USING utf8mb4) COLLATE utf8mb4_bin" + + " AND version=? AND CAST(blob_name AS BINARY)=UNHEX(?)"; private final DataSource db; @@ -139,15 +145,21 @@ private static byte[] encode(Iterator descriptors, int expec private static void bindKey(PreparedStatement s, short account, short container, String name, long version) throws SQLException { - bindKey(s, account, container, name, version, 1); + s.setInt(1, account); + s.setInt(2, container); + s.setString(3, name); + s.setLong(4, version); } - private static void bindKey(PreparedStatement s, short account, short container, String name, long version, int at) - throws SQLException { + private static void bindExactReadKey(PreparedStatement s, short account, short container, String name, long version, + int at) throws SQLException { + // Send ASCII hex so the connection's client charset cannot transcode the name. + String utf8NameHex = Hex.encodeHexString(name.getBytes(StandardCharsets.UTF_8)); s.setInt(at, account); s.setInt(at + 1, container); - s.setString(at + 2, name); + s.setString(at + 2, utf8NameHex); s.setLong(at + 3, version); + s.setString(at + 4, utf8NameHex); } static void checkManifestCount(List versions) { @@ -421,16 +433,14 @@ static final class Manifest { final long version; final String root; final int count; - final byte[] publicationKey; - private Manifest(ResultSet r) throws SQLException { + private Manifest(ResultSet r, String exactName) throws SQLException { account = r.getShort(1); container = r.getShort(2); - name = r.getString(3); - version = r.getLong(4); - root = Base64.getUrlEncoder().withoutPadding().encodeToString(r.getBytes(5)); - count = r.getInt(6); - publicationKey = r.getBytes(7); + name = exactName; + version = r.getLong(3); + root = Base64.getUrlEncoder().withoutPadding().encodeToString(r.getBytes(4)); + count = r.getInt(5); if (count < 1 || count > MAX_CHILDREN) { throw new SQLDataException("Invalid manifest bounds: " + name + "/" + version); } @@ -469,59 +479,100 @@ boolean isPublished(PreparedRetirement p) throws SQLException { * row in this table is published by construction, so existence alone is sufficient. */ Manifest getPublished(short account, short container, String name, long version) throws SQLException { - String sql = "SELECT " + HEADER_COLUMNS + " FROM " + TABLE + " WHERE " + KEY; + String sql = "SELECT " + READ_HEADER_COLUMNS + " FROM " + TABLE + " WHERE " + EXACT_READ_KEY; + try (Connection c = db.getConnection()) { + requireCommittedReads(c); + try (PreparedStatement s = c.prepareStatement(sql)) { + bindExactReadKey(s, account, container, Objects.requireNonNull(name, "name"), version, 1); + try (ResultSet r = s.executeQuery()) { + if (!r.next()) { + return null; + } + return new Manifest(r, name); + } + } + } + } + + /** Verify one exact committed row and return its descriptor count, or null if no row matches. */ + Integer readVerifiedCount(short account, short container, String name, long version) throws SQLException { + // Bound the bytes sent to JDBC using the count from the same row as the payload. + String sql = "SELECT " + READ_HEADER_COLUMNS + ",payload_hash,CASE WHEN child_count BETWEEN 1 AND " + + MAX_CHILDREN + " AND OCTET_LENGTH(payload) <= child_count * " + (MAX_ID_BYTES + 1) + + " THEN payload END AS bounded_payload FROM " + TABLE + " WHERE " + EXACT_READ_KEY; + Manifest manifest; + byte[] body; + byte[] payloadHash; try (Connection c = db.getConnection()) { requireCommittedReads(c); try (PreparedStatement s = c.prepareStatement(sql)) { - bindKey(s, account, container, Objects.requireNonNull(name, "name"), version); + bindExactReadKey(s, account, container, Objects.requireNonNull(name, "name"), version, 1); try (ResultSet r = s.executeQuery()) { if (!r.next()) { return null; } - Manifest manifest = new Manifest(r); - // The named table's VARCHAR key uses a PAD SPACE collation. - return name.equals(manifest.name) ? manifest : null; + manifest = new Manifest(r, name); + payloadHash = r.getBytes("payload_hash"); + body = r.getBytes("bounded_payload"); } } } + validatePayload(manifest, body, payloadHash, null); + return manifest.count; } /** Read the full ordered child list for one published manifest row; the caller owns any inspection progress. */ List read(Manifest m) throws SQLException { byte[] body; + byte[] payloadHash; try (Connection c = db.getConnection()) { requireCommittedReads(c); - try (PreparedStatement s = c.prepareStatement("SELECT payload,payload_hash FROM " + TABLE + " WHERE " + KEY)) { - bindKey(s, m.account, m.container, m.name, m.version); + // Do not fetch an oversized LONGBLOB from a malformed row into the JDBC client. + try (PreparedStatement s = c.prepareStatement( + "SELECT CASE WHEN OCTET_LENGTH(payload) <= ? THEN payload END,payload_hash FROM " + TABLE + + " WHERE " + EXACT_READ_KEY)) { + s.setInt(1, m.count * (MAX_ID_BYTES + 1)); + bindExactReadKey(s, m.account, m.container, m.name, m.version, 2); try (ResultSet r = s.executeQuery()) { if (!r.next()) { throw new SQLDataException("Missing published manifest: " + m.name + "/" + m.version); } - byte[] payload = r.getBytes(1); - byte[] payloadHash = r.getBytes(2); - if (!MessageDigest.isEqual(payloadHash, hash(m.account, m.container, m.name, m.version, m.count, m.root, - payload))) { - throw new SQLDataException("Manifest checksum mismatch: " + m.name + "/" + m.version); - } - body = payload; + body = r.getBytes(1); + payloadHash = r.getBytes(2); } } } - ByteBuffer in = ByteBuffer.wrap(body); List ids = new ArrayList<>(m.count); + validatePayload(m, body, payloadHash, ids); + return Collections.unmodifiableList(ids); + } + + /** Pass a null list to validate framing without allocating encoded IDs. */ + private static void validatePayload(Manifest m, byte[] body, byte[] payloadHash, List ids) + throws SQLDataException { + if (body == null) { + throw new SQLDataException("Invalid published manifest length"); + } + if (!MessageDigest.isEqual(payloadHash, hash(m.account, m.container, m.name, m.version, m.count, m.root, body))) { + throw new SQLDataException("Manifest checksum mismatch: " + m.name + "/" + m.version); + } + ByteBuffer in = ByteBuffer.wrap(body); for (int i = 0; i < m.count; i++) { int length = in.hasRemaining() ? Byte.toUnsignedInt(in.get()) : 0; if (length == 0 || length > MAX_ID_BYTES || length > in.remaining()) { throw new SQLDataException("Invalid published child descriptor"); } - byte[] bytes = new byte[length]; - in.get(bytes); - ids.add(Base64.getUrlEncoder().withoutPadding().encodeToString(bytes)); + if (ids == null) { + in.position(in.position() + length); + } else { + byte[] bytes = new byte[length]; + in.get(bytes); + ids.add(Base64.getUrlEncoder().withoutPadding().encodeToString(bytes)); + } } if (in.hasRemaining()) { throw new SQLDataException("Trailing bytes on published manifest"); } - return Collections.unmodifiableList(ids); } private static byte[] hash(short account, short container, String name, long version, int count, String root, diff --git a/ambry-named-mysql/src/test/java/com/github/ambry/named/NamedBlobManifestInventoryTest.java b/ambry-named-mysql/src/test/java/com/github/ambry/named/NamedBlobManifestInventoryTest.java new file mode 100644 index 0000000000..46e39e55f2 --- /dev/null +++ b/ambry-named-mysql/src/test/java/com/github/ambry/named/NamedBlobManifestInventoryTest.java @@ -0,0 +1,63 @@ +/* + * Copyright 2026 LinkedIn Corp. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +package com.github.ambry.named; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.fail; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.io.ByteArrayInputStream; +import java.io.StringWriter; +import java.nio.charset.StandardCharsets; +import java.sql.SQLTransientConnectionException; +import java.util.Collections; +import javax.sql.DataSource; +import org.junit.Test; + +public class NamedBlobManifestInventoryTest { + @Test + public void testRejectsMalformedBatchBeforeAnyRead() throws Exception { + DataSource db = mock(DataSource.class); + NamedBlobManifestStore store = new NamedBlobManifestStore(db); + String key = "[17,4,\"example\",\"1\"]"; + String tooLongName = String.join("", Collections.nCopies(351, "a")); + String oversizedFile = "[" + key + "]" + String.join("", Collections.nCopies(160 * 1024, " ")); + for (String invalid : new String[] {"[]", "[" + key + "] extra", "[" + key + "]\0", + "[[17,4,example,\"1\"]]", "[" + key + ",]", + "[" + key + ",[17,4,\"example\",\"1.5\"]]", "[[17,4,\"example\",\"1\",\"extra\"]]", "[[17,4,\"\",\"1\"]]", + "[[17,4,\"" + tooLongName + "\",\"1\"]]", "[[17,4,\"\\uD800\",\"1\"]]", "[[40000,4,\"example\",\"1\"]]", + "[" + String.join(",", Collections.nCopies(33, key)) + "]", oversizedFile}) { + try { + NamedBlobManifestInventory.inspect(input(invalid), store, new StringWriter()); + fail("Malformed batch accepted"); + } catch (IllegalArgumentException expected) { + // The entire batch must be validated before any lookup. + } + } + verifyNoInteractions(db); + } + + @Test + public void testDatabaseFailureIsNotReportedAsMissing() throws Exception { + DataSource db = mock(DataSource.class); + SQLTransientConnectionException failure = new SQLTransientConnectionException("database unavailable"); + when(db.getConnection()).thenThrow(failure); + StringWriter output = new StringWriter(); + try { + NamedBlobManifestInventory.inspect(input("[[17,4,\"example\",\"1\"]]"), new NamedBlobManifestStore(db), output); + fail("Database failure was hidden"); + } catch (SQLTransientConnectionException actual) { + assertSame(failure, actual); + } + assertEquals("", output.toString()); + } + + private static ByteArrayInputStream input(String value) { + return new ByteArrayInputStream(value.getBytes(StandardCharsets.UTF_8)); + } +} diff --git a/build.gradle b/build.gradle index b10537e6af..ff30d3f470 100644 --- a/build.gradle +++ b/build.gradle @@ -893,6 +893,7 @@ project(':ambry-named-mysql') { implementation project(':ambry-mysql') implementation project(':ambry-commons') implementation project(':ambry-utils') + implementation "com.fasterxml.jackson.core:jackson-core:$jacksonVersion" implementation "mysql:mysql-connector-java:$mysqlConnectorVersion" implementation "com.zaxxer:HikariCP:$hikariVersion" implementation "io.dropwizard.metrics:metrics-core:$metricsVersion"