You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@pulsar.apache.org by mm...@apache.org on 2026/08/26 22:21:01 UTC

(pulsar) branch branch-4.2 updated: [fix][sec] Upgrade avro to 1.12.2 (#24992)

This is an automated email from the ASF dual-hosted git repository.

merlimat pushed a commit to branch branch-4.2
in repository https://gitbox.apache.org/repos/asf/pulsar.git


The following commit(s) were added to refs/heads/branch-4.2 by this push:
     new 70998be86c27 [fix][sec] Upgrade avro to 1.12.2 (#24992)
70998be86c27 is described below

commit 70998be86c270ae0deb075037bbacd39f4839697
Author: Lari Hotari <lh...@users.noreply.github.com>
AuthorDate: Thu Aug 27 01:13:52 2026 +0300

    [fix][sec] Upgrade avro to 1.12.2 (#24992)
---
 distribution/server/src/assemble/LICENSE.bin.txt   |   4 +-
 distribution/shell/src/assemble/LICENSE.bin.txt    |   4 +-
 pom.xml                                            |   2 +-
 .../schema/PulsarInternalAvroTypesTrustTest.java   | 206 +++++++
 .../pulsar/client/impl/schema/AvroSchema.java      |  33 +-
 .../pulsar/client/impl/schema/ProtobufSchema.java  |   8 +
 .../impl/schema/generic/GenericAvroReader.java     |  12 +-
 .../pulsar/client/schema/AvroTrustedClasses.java   | 679 +++++++++++++++++++++
 .../apache/pulsar/client/schema/package-info.java  |  23 +
 .../client/impl/schema/ProtobufSchemaTest.java     |   9 +-
 .../client/schema/AvroTrustedClassesTest.java      | 285 +++++++++
 .../AvroTrustedClassesWithoutValidatorTest.java    |  94 +++
 .../pulsar/client/schema/fixtures/Order.java       |  70 +++
 .../pulsar/client/schema/fixtures/OrderState.java  |  25 +
 .../client/schema/fixtures/other/Address.java      |  35 ++
 15 files changed, 1476 insertions(+), 13 deletions(-)

diff --git a/distribution/server/src/assemble/LICENSE.bin.txt b/distribution/server/src/assemble/LICENSE.bin.txt
index 80b6e846c652..3bafc226ade3 100644
--- a/distribution/server/src/assemble/LICENSE.bin.txt
+++ b/distribution/server/src/assemble/LICENSE.bin.txt
@@ -479,8 +479,8 @@ The Apache Software License, Version 2.0
   * zt-zip
     - org.zeroturnaround-zt-zip-1.17.jar
   * Apache Avro
-    - org.apache.avro-avro-1.12.0.jar
-    - org.apache.avro-avro-protobuf-1.12.0.jar
+    - org.apache.avro-avro-1.12.2.jar
+    - org.apache.avro-avro-protobuf-1.12.2.jar
   * Apache Curator
     - org.apache.curator-curator-client-5.7.1.jar
     - org.apache.curator-curator-framework-5.7.1.jar
diff --git a/distribution/shell/src/assemble/LICENSE.bin.txt b/distribution/shell/src/assemble/LICENSE.bin.txt
index 48aa790e160d..b434c44be9be 100644
--- a/distribution/shell/src/assemble/LICENSE.bin.txt
+++ b/distribution/shell/src/assemble/LICENSE.bin.txt
@@ -417,8 +417,8 @@ The Apache Software License, Version 2.0
  * Google Error Prone Annotations - error_prone_annotations-2.45.0.jar
  * Javassist -- javassist-3.25.0-GA.jar
   * Apache Avro
-    - avro-1.12.0.jar
-    - avro-protobuf-1.12.0.jar
+    - avro-1.12.2.jar
+    - avro-protobuf-1.12.2.jar
  * RE2j -- re2j-1.8.jar
  * Spotify completable-futures -- completable-futures-0.3.6.jar
  * RoaringBitmap -- RoaringBitmap-1.6.9.jar
diff --git a/pom.xml b/pom.xml
index 6b37827791ae..d5726190f96b 100644
--- a/pom.xml
+++ b/pom.xml
@@ -239,7 +239,7 @@ flexible messaging model and an intuitive client API.</description>
     <rabbitmq-client.version>5.28.0</rabbitmq-client.version>
     <aws-sdk.version>1.12.788</aws-sdk.version>
     <aws-sdk2.version>2.32.28</aws-sdk2.version>
-    <avro.version>1.12.0</avro.version>
+    <avro.version>1.12.2</avro.version>
     <joda.version>2.10.10</joda.version>
     <jclouds.version>2.6.0</jclouds.version>
     <guice.version>5.1.0</guice.version>
diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/schema/PulsarInternalAvroTypesTrustTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/schema/PulsarInternalAvroTypesTrustTest.java
new file mode 100644
index 000000000000..2bc1d333e4d1
--- /dev/null
+++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/schema/PulsarInternalAvroTypesTrustTest.java
@@ -0,0 +1,206 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pulsar.broker.service.schema;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import org.apache.avro.util.ClassSecurityValidator;
+import org.apache.avro.util.ClassSecurityValidator.ClassSecurityPredicate;
+import org.apache.pulsar.broker.loadbalance.extensions.channel.ServiceUnitState;
+import org.apache.pulsar.broker.loadbalance.extensions.channel.ServiceUnitStateData;
+import org.apache.pulsar.broker.loadbalance.extensions.data.BrokerLoadData;
+import org.apache.pulsar.broker.loadbalance.extensions.data.TopBundlesLoadData;
+import org.apache.pulsar.broker.transaction.buffer.metadata.AbortTxnMetadata;
+import org.apache.pulsar.broker.transaction.buffer.metadata.TransactionBufferSnapshot;
+import org.apache.pulsar.broker.transaction.buffer.metadata.v2.TransactionBufferSnapshotIndexes;
+import org.apache.pulsar.client.api.Schema;
+import org.apache.pulsar.common.api.proto.CommandSubscribe.SubType;
+import org.apache.pulsar.common.events.ActionType;
+import org.apache.pulsar.common.events.EventType;
+import org.apache.pulsar.common.events.PulsarEvent;
+import org.apache.pulsar.common.events.TopicPoliciesEvent;
+import org.apache.pulsar.common.policies.data.InactiveTopicDeleteMode;
+import org.apache.pulsar.common.policies.data.InactiveTopicPolicies;
+import org.apache.pulsar.common.policies.data.PersistencePolicies;
+import org.apache.pulsar.common.policies.data.PublishRate;
+import org.apache.pulsar.common.policies.data.RetentionPolicies;
+import org.apache.pulsar.common.policies.data.SubscribeRate;
+import org.apache.pulsar.common.policies.data.TopicPolicies;
+import org.apache.pulsar.common.policies.data.impl.BacklogQuotaImpl;
+import org.apache.pulsar.common.policies.data.impl.DispatchRateImpl;
+import org.apache.pulsar.metadata.api.MetadataEvent;
+import org.apache.pulsar.metadata.api.NotificationType;
+import org.apache.pulsar.metadata.api.extended.CreateOption;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+/**
+ * Verifies that the broker can serialize every type it writes to its system topics with nothing declared
+ * in advance — building the schema from the class is what trusts it, exactly as for an application POJO.
+ *
+ * <p>Each test pins the global validator to Avro's hardcoded {@code DEFAULT_TRUSTED_CLASSES}, so that
+ * anything not covered by building the schema fails here rather than being carried by trust some other
+ * test happened to declare first.
+ */
+@Test(groups = "broker")
+public class PulsarInternalAvroTypesTrustTest {
+
+    private ClassSecurityPredicate previousValidator;
+
+    @BeforeMethod
+    public void useProductionBaselineValidator() {
+        previousValidator = ClassSecurityValidator.getGlobal();
+        // DEFAULT_TRUSTED_CLASSES excludes the system-properties predicate, unlike DEFAULT.
+        ClassSecurityValidator.setGlobal(ClassSecurityValidator.DEFAULT_TRUSTED_CLASSES);
+    }
+
+    @AfterMethod(alwaysRun = true)
+    public void restoreValidator() {
+        ClassSecurityValidator.setGlobal(previousValidator);
+    }
+
+    @Test
+    public void testMetadataEventRoundTrips() {
+        // Published by PulsarMetadataEventSynchronizer. Exercises the HashSet "java-class" property and
+        // the CreateOption / NotificationType enums.
+        MetadataEvent event = new MetadataEvent("/path", "value".getBytes(), new HashSet<>(List.of(
+                CreateOption.Ephemeral)), 1L, 2L, "cluster", NotificationType.Created);
+
+        Schema<MetadataEvent> schema = Schema.AVRO(MetadataEvent.class);
+
+        assertThat(schema.decode(schema.encode(event))).isEqualTo(event);
+    }
+
+    @Test
+    public void testPulsarEventRoundTrips() {
+        // Published to the __change_events system topic, and reaches TopicPolicies through
+        // TopicPoliciesEvent.
+        PulsarEvent event = PulsarEvent.builder()
+                .eventType(EventType.TOPIC_POLICY)
+                .actionType(ActionType.UPDATE)
+                .replicateTo(new HashSet<>(List.of("cluster-a")))
+                .topicPoliciesEvent(TopicPoliciesEvent.builder()
+                        .domain("persistent")
+                        .tenant("public")
+                        .namespace("default")
+                        .topic("t1")
+                        // Populate the nested types too: Avro only resolves the class behind a schema
+                        // node when it actually writes it, so leaving these null would skip the enum
+                        // and the policy impl types entirely and hide a missing allow-list entry.
+                        .policies(TopicPolicies.builder()
+                                .subscriptionTypesEnabled(List.of(SubType.Shared, SubType.Key_Shared))
+                                .replicationClusters(List.of("cluster-a"))
+                                .backLogQuotaMap(Map.of("destination_storage",
+                                        (BacklogQuotaImpl) BacklogQuotaImpl.builder().limitSize(1024L).build()))
+                                .dispatchRate(DispatchRateImpl.builder().dispatchThrottlingRateInMsg(10).build())
+                                .retentionPolicies(new RetentionPolicies(1, 2))
+                                .persistence(new PersistencePolicies(1, 1, 1, 1.0))
+                                .inactiveTopicPolicies(new InactiveTopicPolicies(
+                                        InactiveTopicDeleteMode.delete_when_no_subscriptions, 60, true))
+                                .publishRate(new PublishRate(10, 1024))
+                                .subscribeRate(new SubscribeRate(10, 30))
+                                .build())
+                        .build())
+                .build();
+
+        Schema<PulsarEvent> schema = Schema.AVRO(PulsarEvent.class);
+
+        assertThat(schema.decode(schema.encode(event))).isEqualTo(event);
+    }
+
+    @Test
+    public void testTransactionBufferSnapshotRoundTrips() {
+        // The original snapshot format lives in ...buffer.metadata, not ...buffer.metadata.v2, so it is
+        // only covered if the parent package is trusted.
+        TransactionBufferSnapshot snapshot = new TransactionBufferSnapshot();
+        snapshot.setTopicName("persistent://public/default/t1");
+        snapshot.setMaxReadPositionLedgerId(1L);
+        snapshot.setMaxReadPositionEntryId(2L);
+        AbortTxnMetadata aborted = new AbortTxnMetadata();
+        aborted.setTxnIdMostBits(3L);
+        aborted.setTxnIdLeastBits(4L);
+        snapshot.setAborts(List.of(aborted));
+
+        Schema<TransactionBufferSnapshot> schema = Schema.AVRO(TransactionBufferSnapshot.class);
+
+        // These snapshot classes do not define equals(), so compare field by field.
+        assertThat(schema.decode(schema.encode(snapshot)))
+                .usingRecursiveComparison().isEqualTo(snapshot);
+    }
+
+    @Test
+    public void testTransactionBufferSnapshotIndexesRoundTrip() {
+        TransactionBufferSnapshotIndexes indexes = new TransactionBufferSnapshotIndexes();
+        indexes.setTopicName("persistent://public/default/t1");
+        indexes.setIndexList(List.of());
+
+        Schema<TransactionBufferSnapshotIndexes> schema = Schema.AVRO(TransactionBufferSnapshotIndexes.class);
+
+        assertThat(schema.decode(schema.encode(indexes)))
+                .usingRecursiveComparison().isEqualTo(indexes);
+    }
+
+    @Test
+    public void testJsonSchemaOverBrokerInternalTypesRoundTrips() {
+        // Schema.JSON also derives an Avro schema from the POJO, but reads and writes it with Jackson
+        // rather than ReflectDatumReader/Writer, so it does not resolve classes reflectively and does not
+        // need its types in the allow-list. These are the broker's own JSON-schema types, used by the
+        // extensible load balancer; pin the behaviour so a future change to the JSON read/write path
+        // cannot start requiring trust without a test noticing.
+        Schema<ServiceUnitStateData> unitStateSchema = Schema.JSON(ServiceUnitStateData.class);
+        ServiceUnitStateData unitState = new ServiceUnitStateData(
+                ServiceUnitState.Owned, "dst-broker", "src-broker", 1L);
+        assertThat(unitStateSchema.decode(unitStateSchema.encode(unitState)))
+                .usingRecursiveComparison().isEqualTo(unitState);
+
+        Schema<BrokerLoadData> brokerLoadSchema = Schema.JSON(BrokerLoadData.class);
+        assertThat(brokerLoadSchema.decode(brokerLoadSchema.encode(new BrokerLoadData()))).isNotNull();
+
+        Schema<TopBundlesLoadData> topBundlesSchema = Schema.JSON(TopBundlesLoadData.class);
+        assertThat(topBundlesSchema.decode(topBundlesSchema.encode(new TopBundlesLoadData()))).isNotNull();
+    }
+
+    @Test
+    public void testTrustDoesNotLeakToUnrelatedApplicationClasses() {
+        // Serializing the broker's own types must not widen the set for anything else. Build a schema
+        // first so Pulsar's predicate is actually installed on top of the pinned baseline - otherwise
+        // the assertion below would be answered by the baseline alone and could never fail, whatever
+        // auto-registration did.
+        Schema.AVRO(MetadataEvent.class);
+        assertThat(ClassSecurityValidator.getGlobal().isTrusted(MetadataEvent.class)).isTrue();
+
+        assertThat(ClassSecurityValidator.getGlobal().isTrusted(UnusedPojo.class)).isFalse();
+    }
+
+    /** Never passed to a schema, so nothing should have trusted it. */
+    public static class UnusedPojo {
+        private String field = "value";
+
+        public String getField() {
+            return field;
+        }
+
+        public void setField(String field) {
+            this.field = field;
+        }
+    }
+}
diff --git a/pulsar-client/src/main/java/org/apache/pulsar/client/impl/schema/AvroSchema.java b/pulsar-client/src/main/java/org/apache/pulsar/client/impl/schema/AvroSchema.java
index 34c1d3a2aa9f..45e53edc4f25 100644
--- a/pulsar-client/src/main/java/org/apache/pulsar/client/impl/schema/AvroSchema.java
+++ b/pulsar-client/src/main/java/org/apache/pulsar/client/impl/schema/AvroSchema.java
@@ -28,12 +28,14 @@ import org.apache.avro.LogicalType;
 import org.apache.avro.LogicalTypes;
 import org.apache.avro.data.TimeConversions;
 import org.apache.avro.reflect.ReflectData;
+import org.apache.commons.lang3.StringUtils;
 import org.apache.pulsar.client.api.Schema;
 import org.apache.pulsar.client.api.schema.SchemaDefinition;
 import org.apache.pulsar.client.api.schema.SchemaReader;
 import org.apache.pulsar.client.api.schema.SchemaWriter;
 import org.apache.pulsar.client.impl.schema.reader.MultiVersionAvroReader;
 import org.apache.pulsar.client.impl.schema.writer.AvroWriter;
+import org.apache.pulsar.client.schema.AvroTrustedClasses;
 import org.apache.pulsar.common.schema.SchemaInfo;
 import org.apache.pulsar.common.schema.SchemaType;
 import org.joda.time.DateTime;
@@ -85,8 +87,10 @@ public class AvroSchema<T> extends AvroBaseStructSchema<T> {
 
     public static <T> AvroSchema<T> of(SchemaDefinition<T> schemaDefinition) {
         if (schemaDefinition.getSchemaReaderOpt().isPresent() && schemaDefinition.getSchemaWriterOpt().isPresent()) {
+            SchemaInfo schemaInfo = parseSchemaInfo(schemaDefinition, SchemaType.AVRO);
+            trustApplicationPojo(schemaDefinition, schemaInfo);
             return new AvroSchema<>(schemaDefinition.getSchemaReaderOpt().get(),
-                    schemaDefinition.getSchemaWriterOpt().get(), parseSchemaInfo(schemaDefinition, SchemaType.AVRO));
+                    schemaDefinition.getSchemaWriterOpt().get(), schemaInfo);
         }
         ClassLoader pojoClassLoader = null;
         if (schemaDefinition.getClassLoader() != null) {
@@ -95,7 +99,32 @@ public class AvroSchema<T> extends AvroBaseStructSchema<T> {
             pojoClassLoader = schemaDefinition.getPojo().getClassLoader();
         }
 
-        return new AvroSchema<>(parseSchemaInfo(schemaDefinition, SchemaType.AVRO), pojoClassLoader);
+        SchemaInfo schemaInfo = parseSchemaInfo(schemaDefinition, SchemaType.AVRO);
+        trustApplicationPojo(schemaDefinition, schemaInfo);
+        return new AvroSchema<>(schemaInfo, pojoClassLoader);
+    }
+
+    /**
+     * Lets Avro reflect over the class the application supplied, and over the types the schema derived
+     * from it references, so that using {@code Schema.AVRO(MyPojo.class)} needs no further declaration.
+     *
+     * <p>Guarded on the POJO being present, which is what keeps this on the right side of the trust
+     * boundary. A definition built with {@code withJsonDef(...)} carries no POJO — that is how
+     * {@link AutoConsumeSchema} passes a schema fetched from the registry — and a schema chosen by
+     * whoever registered it must not be able to widen the allow-list.
+     */
+    private static <T> void trustApplicationPojo(SchemaDefinition<T> schemaDefinition, SchemaInfo schemaInfo) {
+        if (StringUtils.isNotBlank(schemaDefinition.getJsonDef())) {
+            // SchemaUtil.createAvroSchema gives jsonDef precedence, so the schema was parsed from that
+            // rather than derived from the POJO. Only the stock builder forbids setting both, and
+            // SchemaDefinition is a public interface, so check the same condition here rather than
+            // assuming: expanding trust from a schema Pulsar did not derive would let whoever supplied
+            // that document choose the class names. The class the application named is still its own,
+            // so trust that much; anything further in such a schema is for the application to declare.
+            AvroTrustedClasses.trustExactly(schemaDefinition.getPojo());
+            return;
+        }
+        AvroTrustedClasses.trustApplicationSchema(schemaDefinition.getPojo(), schemaInfo);
     }
 
     public static <T> AvroSchema<T> of(Class<T> pojo) {
diff --git a/pulsar-client/src/main/java/org/apache/pulsar/client/impl/schema/ProtobufSchema.java b/pulsar-client/src/main/java/org/apache/pulsar/client/impl/schema/ProtobufSchema.java
index 71e0bed69120..3715d83984c0 100644
--- a/pulsar-client/src/main/java/org/apache/pulsar/client/impl/schema/ProtobufSchema.java
+++ b/pulsar-client/src/main/java/org/apache/pulsar/client/impl/schema/ProtobufSchema.java
@@ -34,6 +34,7 @@ import org.apache.avro.protobuf.ProtobufData;
 import org.apache.pulsar.client.api.schema.SchemaDefinition;
 import org.apache.pulsar.client.impl.schema.reader.ProtobufReader;
 import org.apache.pulsar.client.impl.schema.writer.ProtobufWriter;
+import org.apache.pulsar.client.schema.AvroTrustedClasses;
 import org.apache.pulsar.common.schema.SchemaInfo;
 import org.apache.pulsar.common.schema.SchemaType;
 import org.apache.pulsar.common.util.ObjectMapperFactory;
@@ -107,6 +108,13 @@ public class ProtobufSchema<T extends Message> extends AvroBaseStructSchema<T> {
                     + " is not assignable from " + pojo.getName());
         }
 
+        // The application named this class, so let Avro reflect over it and over the protobuf runtime
+        // types avro-protobuf resolves alongside it. This has to happen before the schema is derived,
+        // not after: deriving it is itself a reflective resolution, which is also why there is no
+        // derived schema to expand from here. Encoding and decoding go through protobuf's own reader
+        // and writer, so the message's nested types are never resolved by Avro.
+        AvroTrustedClasses.trustExactly(pojo);
+
             SchemaInfo schemaInfo = SchemaInfoImpl.builder()
                     .schema(createProtobufAvroSchema(schemaDefinition.getPojo()).toString().getBytes(UTF_8))
                     .type(SchemaType.PROTOBUF)
diff --git a/pulsar-client/src/main/java/org/apache/pulsar/client/impl/schema/generic/GenericAvroReader.java b/pulsar-client/src/main/java/org/apache/pulsar/client/impl/schema/generic/GenericAvroReader.java
index f333ecfceabb..c355be49af7b 100644
--- a/pulsar-client/src/main/java/org/apache/pulsar/client/impl/schema/generic/GenericAvroReader.java
+++ b/pulsar-client/src/main/java/org/apache/pulsar/client/impl/schema/generic/GenericAvroReader.java
@@ -24,6 +24,7 @@ import java.io.InputStream;
 import java.util.List;
 import java.util.Optional;
 import java.util.stream.Collectors;
+import org.apache.avro.AvroRuntimeException;
 import org.apache.avro.Schema;
 import org.apache.avro.generic.GenericDatumReader;
 import org.apache.avro.io.BinaryEncoder;
@@ -87,7 +88,11 @@ public class GenericAvroReader implements SchemaReader<GenericRecord> {
                     null,
                     decoder);
             return new GenericAvroRecord(schemaVersion, schema, fields, avroRecord);
-        } catch (IOException | IndexOutOfBoundsException e) {
+        } catch (IOException | IndexOutOfBoundsException | AvroRuntimeException e) {
+            // Avro 1.12.1 enabled the fast reader by default (AVRO-3230). It reports malformed data as
+            // AvroTypeException (e.g. "Enumeration out of range") where the classic path raised an
+            // IndexOutOfBoundsException, so catch AvroRuntimeException too and keep reporting decoding
+            // failures as SchemaSerializationException.
             throw new SchemaSerializationException(e);
         }
     }
@@ -101,7 +106,10 @@ public class GenericAvroReader implements SchemaReader<GenericRecord> {
                             null,
                             decoder);
             return new GenericAvroRecord(schemaVersion, schema, fields, avroRecord);
-        } catch (IOException | IndexOutOfBoundsException e) {
+        } catch (IOException | IndexOutOfBoundsException | AvroRuntimeException e) {
+            // See the byte[] overload above: the fast reader, on by default since Avro 1.12.1, reports
+            // malformed data as AvroTypeException. This is the overload consumers actually reach, via
+            // MessageImpl.decodeBySchema -> AbstractStructSchema.decode -> AbstractMultiVersionReader.
             throw new SchemaSerializationException(e);
         } finally {
             try {
diff --git a/pulsar-client/src/main/java/org/apache/pulsar/client/schema/AvroTrustedClasses.java b/pulsar-client/src/main/java/org/apache/pulsar/client/schema/AvroTrustedClasses.java
new file mode 100644
index 000000000000..8982325de3fd
--- /dev/null
+++ b/pulsar-client/src/main/java/org/apache/pulsar/client/schema/AvroTrustedClasses.java
@@ -0,0 +1,679 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pulsar.client.schema;
+
+import static java.nio.charset.StandardCharsets.UTF_8;
+import com.google.common.annotations.VisibleForTesting;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.IdentityHashMap;
+import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.function.Predicate;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.avro.Schema;
+import org.apache.avro.reflect.ReflectData;
+import org.apache.avro.specific.SpecificData;
+import org.apache.avro.util.ClassSecurityValidator;
+import org.apache.avro.util.ClassSecurityValidator.ClassSecurityPredicate;
+import org.apache.pulsar.client.impl.schema.util.SchemaUtil;
+import org.apache.pulsar.common.classification.InterfaceAudience;
+import org.apache.pulsar.common.classification.InterfaceStability;
+import org.apache.pulsar.common.schema.SchemaInfo;
+
+/**
+ * Declares which classes Avro is allowed to reflect over.
+ *
+ * <p>Avro 1.12.2 refuses to resolve any class that is not explicitly trusted, and that check runs on
+ * every reflective class resolution — including the ones {@code Schema.AVRO(...)} performs on each
+ * produce and consume.
+ *
+ * <p><b>Most applications need nothing from this class.</b> Passing a class to {@code Schema.AVRO(...)}
+ * is itself the application naming it, so Pulsar trusts that class and every type the schema derived
+ * from it references — nested records and enums, including ones in other packages, and the declared
+ * collection and {@code @Stringable} types its fields carry. Pulsar Functions and connectors are covered
+ * the same way, since they build their schemas through the same call.
+ *
+ * <p>What is deliberately <em>not</em> covered is a class named only by a schema that arrived over the
+ * wire. A schema fetched from the registry names classes chosen by whoever registered it, and resolving
+ * those is what the allow-list exists to constrain. {@code Schema.AUTO_CONSUME()} stays clear of this
+ * for the usual case: a record schema is decoded generically into a {@code GenericRecord} and no class
+ * is resolved at all. Only a topic whose schema is <em>not</em> a record at the top level reaches Avro
+ * reflection, and then every named type the schema mentions — record, enum or fixed — is resolved,
+ * including through a container: an array or map of records resolves the record class as soon as there
+ * is an element to read. An application that consumes such a topic declares the class itself:
+ *
+ * <pre>{@code
+ * // Once, before the first producer or consumer.
+ * AvroTrustedClasses.trust(Colour.class);
+ * }</pre>
+ *
+ * <p>{@link #trust(Class[])} follows what the class references, the same way auto-registration does.
+ * Prefer it to {@link #trustPackages(String...)}: a package rarely covers a POJO on its own, because
+ * Avro also resolves the <em>declared</em> collection type of a field, so a POJO with a {@code List}
+ * field needs {@code java.util.List} as well.
+ *
+ * <p>Declarations are process-wide and accumulate. Code that needs to make a temporary change — a test
+ * asserting that some class is <em>not</em> trusted, most often — takes a {@link #snapshot()} first and
+ * hands it back to {@link #restore(State)} afterwards, which puts back exactly what was declared
+ * before rather than discarding declarations that belong to something else:
+ *
+ * <pre>{@code
+ * State before = AvroTrustedClasses.snapshot();
+ * try {
+ *     AvroTrustedClasses.resetToDefaults();
+ *     // ... assert what is and is not trusted ...
+ * } finally {
+ *     AvroTrustedClasses.restore(before);
+ * }
+ * }</pre>
+ *
+ * <p>This class behaves identically in the shaded and unshaded clients. Avro's own API does not:
+ * shading relocates {@code org.apache.avro.util.ClassSecurityValidator}, so an application depending
+ * on {@code pulsar-client} or {@code pulsar-client-all} cannot name it, and the Avro system property
+ * is renamed along with it. For the same reason, the advice in Avro's own {@code SecurityException}
+ * message does not apply to the shaded clients.
+ *
+ * <p>Trust widens the set Avro will accept; it never narrows it. Whatever validator is already
+ * installed — Avro's own defaults, a policy from the {@code SERIALIZABLE_CLASSES} /
+ * {@code SERIALIZABLE_PACKAGES} system properties, or one the application installed itself — keeps
+ * working, because this class composes with it rather than replacing it. Composition happens once;
+ * every later declaration is an append, so it takes effect immediately and costs nothing on the
+ * serialization path.
+ *
+ * <p>Declaring trust after a rejection still works for subsequent operations; the one that already
+ * failed has failed.
+ *
+ * <p>Only classes reached through Avro schemas are affected. {@code Schema.JSON(...)} reads and
+ * writes through Jackson and needs nothing declared here.
+ */
+@InterfaceAudience.Public
+@InterfaceStability.Evolving
+@Slf4j
+public final class AvroTrustedClasses {
+
+    /**
+     * The declarations in force. Swapping this reference is how {@link #restore(State)} puts back a
+     * previous set of declarations atomically.
+     */
+    private static volatile State current = State.withDefaults();
+
+    /**
+     * Whether the Avro on the class path has a trusted-class validator to install into at all. It was
+     * introduced in Avro 1.12.2; an application using {@code pulsar-client-original} can pin an older
+     * Avro, and on those versions there is nothing to enforce and so nothing to declare. Everything
+     * this class does then becomes a no-op rather than a {@link NoClassDefFoundError} raised out of
+     * {@code Schema.AVRO(...)}.
+     */
+    private static final boolean VALIDATOR_AVAILABLE = isValidatorAvailable();
+
+    private static boolean isValidatorAvailable() {
+        try {
+            Class.forName("org.apache.avro.util.ClassSecurityValidator", false,
+                    AvroTrustedClasses.class.getClassLoader());
+            return true;
+        } catch (ClassNotFoundException | LinkageError e) {
+            log.debug("Avro has no ClassSecurityValidator; trusted-class declarations are a no-op");
+            return false;
+        }
+    }
+
+    private AvroTrustedClasses() {
+    }
+
+    /**
+     * Everything declared through {@link AvroTrustedClasses}: the trusted names and predicates, and the
+     * record of which schemas have already been walked. One instance is live at a time and answers
+     * Avro's trust check; {@link AvroTrustedClasses#snapshot()} hands out a detached copy of it.
+     *
+     * <p>Opaque to callers, who only hold a copy and give it back to
+     * {@link AvroTrustedClasses#restore(State)}. Because that copy is detached, it is unaffected by
+     * anything declared afterwards and can be restored more than once.
+     */
+    public static final class State {
+
+        /** Trusted package prefixes; sub-packages are included. */
+        private final Set<String> trustedPackages = ConcurrentHashMap.newKeySet();
+
+        /** Individually trusted binary class names. */
+        private final Set<String> trustedClasses = ConcurrentHashMap.newKeySet();
+
+        /** Additional rules, for policies the name-based methods cannot express. */
+        private final Set<Predicate<Class<?>>> trustedPredicates = ConcurrentHashMap.newKeySet();
+
+        /**
+         * Application classes whose derived schema has already been walked, so a class used for many
+         * producers or consumers is traversed once rather than on every schema construction. Holds
+         * names rather than Class objects, so it pins neither a class nor its loader.
+         */
+        private final Set<WalkKey> walked = ConcurrentHashMap.newKeySet();
+
+        /**
+         * Identifies one traversal, by the schema that was walked rather than by the class alone. The
+         * same class can derive different schemas — JSR-310 conversions replace a named type with a
+         * logical primitive, and two class loaders can define different versions of the same class name
+         * — and each of those names a different set of types. Keying on the class alone could cache the
+         * smaller set and then refuse a type the larger one needs, which fails closed at serialization
+         * time. Holds names and schema text only, so it pins neither a class nor a loader.
+         */
+        private record WalkKey(String className, String schemaJson) {
+        }
+
+        private State() {
+        }
+
+        /** The built-in baseline: what a JVM starts out with before anything is declared. */
+        private static State withDefaults() {
+            State state = new State();
+            // Protobuf runtime types that avro-protobuf resolves when building a schema for a generated
+            // message, such as the com.google.protobuf.Any wrapper. Needed by Schema.PROTOBUF for any
+            // application, so it belongs to the client's own baseline rather than to a caller. In the
+            // shaded client this literal is relocated alongside the classes it names, so it still
+            // matches.
+            state.trustedPackages.add("com.google.protobuf");
+            // Collection types that ReflectData records as a "java-class" property on the array or map
+            // schema it generates for a field, and then resolves reflectively. Trusting a class expands
+            // through the derived schema and picks these up on its own, but declaring a package or a
+            // bare class name does not, which made "trust my model package" quietly insufficient for
+            // any POJO with a List field. They are plain containers with nothing exploitable in
+            // construction, and Avro's own build trusts the same set, so there is no value in making
+            // callers rediscover them.
+            state.trustedClasses.addAll(Arrays.asList(
+                    "java.util.Collection",
+                    "java.util.List",
+                    "java.util.ArrayList",
+                    "java.util.Set",
+                    "java.util.HashSet",
+                    "java.util.LinkedHashSet",
+                    "java.util.TreeSet",
+                    "java.util.Map",
+                    "java.util.HashMap",
+                    "java.util.LinkedHashMap",
+                    "java.util.TreeMap",
+                    "java.util.concurrent.ConcurrentHashMap"));
+            return state;
+        }
+
+        /**
+         * An independent copy. Both {@code snapshot()} and {@code restore()} copy, so a copy handed to
+         * a caller never shares mutable state with the live instance.
+         */
+        private State copy() {
+            State copy = new State();
+            copy.trustedPackages.addAll(trustedPackages);
+            copy.trustedClasses.addAll(trustedClasses);
+            copy.trustedPredicates.addAll(trustedPredicates);
+            copy.walked.addAll(walked);
+            return copy;
+        }
+
+        private void addClassName(String className) {
+            if (className != null && !className.isEmpty()) {
+                trustedClasses.add(className);
+            }
+        }
+
+        private void addClassNames(Collection<String> classNames) {
+            for (String className : classNames) {
+                addClassName(className);
+            }
+        }
+
+        private void addPackageNames(Collection<String> packageNames) {
+            for (String packageName : packageNames) {
+                if (packageName != null && !packageName.isEmpty()) {
+                    trustedPackages.add(packageName);
+                }
+            }
+        }
+
+        private void addPredicate(Predicate<Class<?>> predicate) {
+            trustedPredicates.add(predicate);
+        }
+
+        /** Records a traversal, returning false when this schema has already been walked. */
+        private boolean markWalked(String className, String schemaJson) {
+            return walked.add(new WalkKey(className, schemaJson));
+        }
+
+        private int walkedCount() {
+            return walked.size();
+        }
+
+        /** Whether the class is covered by anything declared here. */
+        private boolean isTrusted(Class<?> clazz) {
+            if (clazz == null) {
+                return false;
+            }
+            // Nested classes report the enclosing package, so Outer$Inner is matched by its package too.
+            Package classPackage = clazz.getPackage();
+            if (isTrustedName(clazz.getName(), classPackage == null ? null : classPackage.getName())) {
+                return true;
+            }
+            for (Predicate<Class<?>> predicate : trustedPredicates) {
+                if (predicate.test(clazz)) {
+                    return true;
+                }
+            }
+            return false;
+        }
+
+        private boolean isTrustedName(String className, String packageName) {
+            if (trustedClasses.contains(className)) {
+                return true;
+            }
+            if (packageName == null) {
+                return false;
+            }
+            for (String trusted : trustedPackages) {
+                // Require a package separator at the boundary so that trusting "com.example.model" does
+                // not also trust a package named "com.example.modelExtra".
+                if (packageName.equals(trusted) || packageName.startsWith(trusted + ".")) {
+                    return true;
+                }
+            }
+            return false;
+        }
+    }
+
+    /**
+     * Copies everything declared so far, for handing back to {@link #restore(State)} later. The copy
+     * is unaffected by anything declared afterwards.
+     */
+    public static State snapshot() {
+        return current.copy();
+    }
+
+    /**
+     * Replaces the declarations with those of a snapshot, discarding anything declared since it was
+     * taken and restoring anything that has been dropped. The snapshot is copied rather than adopted,
+     * so it stays valid and can be restored again.
+     *
+     * <p>Pair this with {@link #snapshot()} around a temporary change. It is what a test should use
+     * instead of {@link #resetToDefaults()} alone, since other components — a broker running in the
+     * same JVM, for instance — have declarations of their own that must survive the test.
+     *
+     * <p>Restoring only affects declarations made through this class. Avro's global validator is left
+     * as it is; code that swapped that out is responsible for putting it back.
+     */
+    public static void restore(State snapshot) {
+        Objects.requireNonNull(snapshot, "snapshot");
+        current = snapshot.copy();
+        install();
+    }
+
+    /**
+     * Drops every declaration made through this class and returns to the built-in defaults — the
+     * protobuf runtime package and the collection types Avro records as {@code java-class} properties.
+     * Trust that did not come from this class is untouched, including Avro's own
+     * {@code SERIALIZABLE_CLASSES} and {@code SERIALIZABLE_PACKAGES} properties and any validator
+     * installed directly through Avro.
+     *
+     * <p>Chiefly for tests, and best paired with {@link #snapshot()} and {@link #restore(State)} so
+     * that declarations belonging to other components come back afterwards. Declared trust is
+     * process-wide and accumulates, and building a schema declares its class on its own, so a test
+     * asserting that something is <em>not</em> trusted only means anything if it starts from a known
+     * state — otherwise an unrelated earlier test can leave the class trusted and the assertion passes
+     * vacuously.
+     *
+     * <p>Take care outside tests. Declarations are shared by the whole JVM, so this drops what other
+     * components declared as well, and schemas built earlier do not re-declare anything. Avro caches
+     * the classes it has already resolved, so the effect usually shows up later, as a refusal of some
+     * type that had not been resolved yet, rather than immediately.
+     */
+    public static void resetToDefaults() {
+        current = State.withDefaults();
+        install();
+    }
+
+    /** How many derived schemas have been walked. Only for tests. */
+    @VisibleForTesting
+    static int walkedCountForTesting() {
+        return current.walkedCount();
+    }
+
+    /**
+     * Name-based form of the trust check, so the matching rules can be tested without needing a
+     * loadable class in every package under test.
+     *
+     * @param packageName the class's package, or null for the default package, which is never trusted
+     */
+    @VisibleForTesting
+    static boolean isTrustedName(String className, String packageName) {
+        return current.isTrustedName(className, packageName);
+    }
+
+    /**
+     * Trusts each given class along with everything Avro resolves when serializing it: the nested
+     * records, enums and fixed types reachable from its fields, whatever package they live in, and the
+     * declared collection and {@code @Stringable} types its fields carry.
+     *
+     * <p>Prefer this to the name-based methods. Call it once per POJO you use with
+     * {@code Schema.AVRO(...)}, before creating the producer or consumer.
+     *
+     * <p>If a class has no schema Avro can derive — a bare {@code java.util.List}, say, which has no
+     * element type to describe — only the class itself is trusted; there is nothing to expand. Use
+     * {@link #trustExactly(Class[])} when that is what you meant.
+     */
+    public static void trust(Class<?>... classes) {
+        State state = current;
+        for (Class<?> clazz : classes) {
+            if (clazz == null) {
+                continue;
+            }
+            state.addClassName(clazz.getName());
+            state.addClassNames(typesReachableFrom(clazz));
+        }
+        install();
+    }
+
+    /**
+     * Trusts a class the application supplied to a Pulsar schema, together with every type the schema
+     * Pulsar derived from it references. Called by Pulsar when it builds an Avro schema from an
+     * application class, so applications normally do not have to declare anything themselves.
+     *
+     * <p>The trust boundary this relies on is that {@code pojo} came from application code. It must
+     * therefore never be called with a class named by a schema that arrived over the wire — a schema
+     * fetched from the registry names classes chosen by whoever registered it, and resolving those is
+     * exactly what the allow-list exists to constrain.
+     *
+     * <p>Takes the derived {@link SchemaInfo} rather than re-deriving from the class, so the types
+     * trusted are exactly the ones the schema in use actually names. Deriving a second time with a
+     * differently configured {@code ReflectData} would not produce the same set.
+     *
+     * <p>Use {@link #trustExactly(Class[])} instead where there is no derived schema to expand from.
+     *
+     * @param pojo the application class, or null to do nothing
+     * @param schemaInfo the schema Pulsar derived from it
+     */
+    @InterfaceAudience.Private
+    public static void trustApplicationSchema(Class<?> pojo, SchemaInfo schemaInfo) {
+        if (pojo == null) {
+            return;
+        }
+        State state = current;
+        state.addClassName(pojo.getName());
+        if (schemaInfo == null || schemaInfo.getSchema() == null || schemaInfo.getSchema().length == 0) {
+            install();
+            return;
+        }
+        String schemaJson = new String(schemaInfo.getSchema(), UTF_8);
+        if (state.markWalked(pojo.getName(), schemaJson)) {
+            try {
+                Set<String> names = new HashSet<>();
+                // Resolve names against the loader that defined the POJO: that is where the types it
+                // references live, and it is the loader Avro itself uses for them.
+                collectTypeNames(SchemaUtil.parseAvroSchema(schemaJson),
+                        Collections.newSetFromMap(new IdentityHashMap<>()), names, pojo.getClassLoader());
+                state.addClassNames(names);
+            } catch (RuntimeException e) {
+                // A schema Pulsar just derived should always parse; if it somehow does not, the class
+                // itself is still trusted and an explicit trust(...) call remains available.
+                log.debug("Could not expand trust from the schema derived for class {}", pojo.getName(), e);
+            }
+        }
+        // Deliberately outside the cache: install() is what re-composes Pulsar's predicate if something
+        // else has replaced the global validator since, and it is a reference comparison once installed.
+        install();
+    }
+
+    /**
+     * Trusts every class in the given packages, and in their sub-packages. Matching requires a package
+     * separator at the boundary, so trusting {@code com.example.model} does not trust a package named
+     * {@code com.example.modelExtra}.
+     *
+     * <p>Remember that a package rarely covers a POJO on its own — see the note on
+     * {@link #trust(Class[])} about declared collection types.
+     */
+    public static void trustPackages(String... packageNames) {
+        current.addPackageNames(Arrays.asList(packageNames));
+        install();
+    }
+
+    /**
+     * Trusts exactly the given classes, without following what they reference. Use this when you want
+     * to say precisely which classes are trusted; {@link #trust(Class[])} is usually the more practical
+     * choice, since it also covers the types Avro reaches from them.
+     *
+     * <p>Works for interfaces too, which is the one case where {@link #trust(Class[])} has nothing to
+     * expand: an interface either has no schema of its own (Avro generates an empty record) or none at
+     * all (a bare {@code java.util.List} cannot be described without an element type). Note that
+     * trusting an interface does not trust its implementations — Avro names the concrete class in the
+     * schema, so those have to be trusted in their own right, which {@link #trust(Class[])} does
+     * automatically for a class whose fields declare them with {@code @Union}.
+     */
+    public static void trustExactly(Class<?>... classes) {
+        if (classes != null) {
+            State state = current;
+            for (Class<?> clazz : classes) {
+                if (clazz != null) {
+                    state.addClassName(clazz.getName());
+                }
+            }
+        }
+        // Installs even when nothing was named, so that the built-in defaults - the protobuf runtime
+        // types and the collection types Avro records as java-class properties - take effect in a JVM
+        // whose schemas are all built from a schema document rather than from a class.
+        install();
+    }
+
+    /**
+     * Trusts individually named classes, without following what they reference. Use this for classes
+     * you cannot reference at compile time. Nested classes must be named with the binary form, using
+     * {@code $} rather than a dot: {@code com.example.Outer$Inner}.
+     */
+    public static void trustClasses(String... classNames) {
+        current.addClassNames(Arrays.asList(classNames));
+        install();
+    }
+
+    /**
+     * Trusts any class the given predicate accepts. An escape hatch for policies the other methods
+     * cannot express; the predicate is consulted on the serialization path, so keep it cheap.
+     */
+    public static void trust(Predicate<Class<?>> predicate) {
+        if (predicate != null) {
+            current.addPredicate(predicate);
+            install();
+        }
+    }
+
+    /**
+     * Installs this class's trust into Avro's global validator, when there is one to install into.
+     * Idempotent: after the first call the normal path is a single reference comparison, and declaring
+     * more trust never composes again.
+     */
+    private static void install() {
+        if (VALIDATOR_AVAILABLE) {
+            Validator.install();
+        }
+    }
+
+    /**
+     * Whether the global validator is still the one this class installed. Always false when the Avro on
+     * the class path has no validator.
+     */
+    public static boolean isInstalled() {
+        return VALIDATOR_AVAILABLE && Validator.isInstalled();
+    }
+
+    /** Whether the class is covered by anything declared through this class. */
+    private static boolean isTrustedClass(Class<?> clazz) {
+        return current.isTrusted(clazz);
+    }
+
+    /**
+     * Holds every reference to Avro's validator types, so they are resolved only when this nested class
+     * is first used. Keeping them out of {@link AvroTrustedClasses} itself is what lets that class load,
+     * and its methods run harmlessly, against an Avro that predates the validator.
+     */
+    private static final class Validator {
+
+        /**
+         * Pulsar's contribution to the global validator, as a single stable instance. It reads whatever
+         * declarations are current on every call, so declaring more trust — or restoring a snapshot —
+         * takes effect immediately without composing into the global validator again; composition
+         * happens only in {@link #install()}.
+         *
+         * <p>Holding one instance keeps repeated installs cheap, but it does not make duplicates
+         * impossible: if something composes its own predicate on top of ours, the identity check no
+         * longer matches and the next install composes a second reference to this instance. That is
+         * harmless — {@code composite} is a short-circuiting OR — just not free.
+         */
+        private static final ClassSecurityPredicate TRUSTED_PREDICATE = AvroTrustedClasses::isTrustedClass;
+
+        /** The predicate last installed, so {@link #install()} can tell whether it is still active. */
+        private static ClassSecurityPredicate installedPredicate;
+
+        private Validator() {
+        }
+
+        static synchronized void install() {
+            ClassSecurityPredicate current = ClassSecurityValidator.getGlobal();
+            if (current == installedPredicate) {
+                return;
+            }
+            ClassSecurityPredicate composed = ClassSecurityValidator.composite(current, TRUSTED_PREDICATE);
+            ClassSecurityValidator.setGlobal(composed);
+            installedPredicate = composed;
+            log.debug("Installed Pulsar's Avro trusted-class validator");
+        }
+
+        static synchronized boolean isInstalled() {
+            return installedPredicate != null && ClassSecurityValidator.getGlobal() == installedPredicate;
+        }
+    }
+
+    /**
+     * Names every type Avro will resolve when serializing the class, taken from the schema it
+     * generates for it. Schema generation uses plain reflection and never consults the validator, so
+     * this is safe to do before the class is trusted.
+     */
+    private static Set<String> typesReachableFrom(Class<?> clazz) {
+        Schema schema;
+        try {
+            schema = ReflectData.get().getSchema(clazz);
+        } catch (RuntimeException e) {
+            // Not every class has a derivable schema (a bare interface, for example). The class itself
+            // has already been trusted, which is the useful part.
+            log.debug("Could not derive an Avro schema to expand trust from for class {}", clazz.getName(), e);
+            return Collections.emptySet();
+        }
+        Set<String> names = new HashSet<>();
+        collectTypeNames(schema, Collections.newSetFromMap(new IdentityHashMap<>()), names,
+                clazz.getClassLoader());
+        return names;
+    }
+
+    private static void collectTypeNames(Schema schema, Set<Schema> visited, Set<String> names,
+                                         ClassLoader loader) {
+        if (schema == null || !visited.add(schema)) {
+            return;
+        }
+        // Collection and @Stringable types are recorded as properties naming the declared class.
+        addIfPresent(schema.getProp(SpecificData.CLASS_PROP), names);
+        addIfPresent(schema.getProp(SpecificData.KEY_CLASS_PROP), names);
+        addIfPresent(schema.getProp(SpecificData.ELEMENT_PROP), names);
+
+        switch (schema.getType()) {
+            case RECORD:
+                addNamedType(schema, names, loader);
+                for (Schema.Field field : schema.getFields()) {
+                    collectTypeNames(field.schema(), visited, names, loader);
+                }
+                break;
+            case ENUM:
+            case FIXED:
+                addNamedType(schema, names, loader);
+                break;
+            case ARRAY:
+                collectTypeNames(schema.getElementType(), visited, names, loader);
+                break;
+            case MAP:
+                collectTypeNames(schema.getValueType(), visited, names, loader);
+                break;
+            case UNION:
+                for (Schema member : schema.getTypes()) {
+                    collectTypeNames(member, visited, names, loader);
+                }
+                break;
+            default:
+                break;
+        }
+    }
+
+    /**
+     * Records a named type under the binary name of the class it resolves to. Avro spells a nested
+     * class {@code a.b.Outer.Inner} in the schema but resolves it by retrying with {@code $}
+     * separators, and the validator matches on {@code Class.getName()}, so the {@code $} form is the
+     * one that has to be trusted.
+     */
+    private static void addNamedType(Schema schema, Set<String> names, ClassLoader loader) {
+        String fullName = schema.getFullName();
+        if (fullName == null) {
+            return;
+        }
+        String resolved = resolveBinaryName(fullName, loader);
+        names.add(resolved != null ? resolved : fullName);
+    }
+
+    private static String resolveBinaryName(String fullName, ClassLoader preferredLoader) {
+        ClassLoader loader = preferredLoader;
+        if (loader == null) {
+            loader = Thread.currentThread().getContextClassLoader();
+        }
+        if (loader == null) {
+            loader = AvroTrustedClasses.class.getClassLoader();
+        }
+        // Mirrors SpecificData.getClass: try the name as written, then progressively replace trailing
+        // dots with '$' to find a nested class. Uses plain reflection with initialize=false, so it
+        // neither runs static initializers nor consults Avro's validator.
+        if (classExists(fullName, loader)) {
+            return fullName;
+        }
+        StringBuilder candidate = new StringBuilder(fullName);
+        int lastDot = fullName.lastIndexOf('.');
+        while (lastDot != -1) {
+            candidate.setCharAt(lastDot, '$');
+            if (classExists(candidate.toString(), loader)) {
+                return candidate.toString();
+            }
+            lastDot = fullName.lastIndexOf('.', lastDot - 1);
+        }
+        return null;
+    }
+
+    private static boolean classExists(String name, ClassLoader loader) {
+        try {
+            Class.forName(name, false, loader);
+            return true;
+        } catch (ClassNotFoundException | LinkageError e) {
+            return false;
+        }
+    }
+
+    private static void addIfPresent(String className, Set<String> names) {
+        if (className != null && !className.isEmpty()) {
+            names.add(className);
+        }
+    }
+}
diff --git a/pulsar-client/src/main/java/org/apache/pulsar/client/schema/package-info.java b/pulsar-client/src/main/java/org/apache/pulsar/client/schema/package-info.java
new file mode 100644
index 000000000000..51f5a549ebb3
--- /dev/null
+++ b/pulsar-client/src/main/java/org/apache/pulsar/client/schema/package-info.java
@@ -0,0 +1,23 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/**
+ * Supported entry points for configuring how Pulsar's schemas handle an application's own classes.
+ */
+package org.apache.pulsar.client.schema;
diff --git a/pulsar-client/src/test/java/org/apache/pulsar/client/impl/schema/ProtobufSchemaTest.java b/pulsar-client/src/test/java/org/apache/pulsar/client/impl/schema/ProtobufSchemaTest.java
index 9e283b6799df..dd6ad959c39c 100644
--- a/pulsar-client/src/test/java/org/apache/pulsar/client/impl/schema/ProtobufSchemaTest.java
+++ b/pulsar-client/src/test/java/org/apache/pulsar/client/impl/schema/ProtobufSchemaTest.java
@@ -38,6 +38,8 @@ import lombok.extern.slf4j.Slf4j;
 import org.apache.avro.Schema;
 import org.apache.pulsar.common.schema.SchemaType;
 import org.apache.pulsar.functions.proto.Function;
+import org.json.JSONException;
+import org.skyscreamer.jsonassert.JSONAssert;
 import org.testng.Assert;
 import org.testng.annotations.Test;
 
@@ -52,7 +54,7 @@ public class ProtobufSchemaTest {
             + "\"avro.java.string\":\"String\"},\"default\":\"\"},{\"name\":\"doubleField\","
             + "\"type\":\"double\",\"default\":0.0},{\"name\":\"intField\",\"type\":\"int\","
             + "\"default\":0},{\"name\":\"testEnum\",\"type\":{\"type\":\"enum\","
-            + "\"name\":\"TestEnum\",\"symbols\":[\"SHARED\",\"FAILOVER\"]},"
+            + "\"name\":\"TestEnum\",\"symbols\":[\"SHARED\",\"FAILOVER\"],\"default\":\"SHARED\"},"
             + "\"default\":\"SHARED\"},{\"name\":\"nestedField\","
             + "\"type\":[\"null\",{\"type\":\"record\",\"name\":\"SubMessage\","
             + "\"fields\":[{\"name\":\"foo\",\"type\":{\"type\":\"string\","
@@ -135,7 +137,7 @@ public class ProtobufSchemaTest {
     }
 
     @Test
-    public void testSchema() {
+    public void testSchema() throws JSONException {
         ProtobufSchema<org.apache.pulsar.client.schema.proto.Test.TestMessage> protobufSchema =
                 ProtobufSchema.of(org.apache.pulsar.client.schema.proto.Test.TestMessage.class);
 
@@ -144,8 +146,7 @@ public class ProtobufSchemaTest {
         String schemaJson = new String(protobufSchema.getSchemaInfo().getSchema());
         Schema.Parser parser = new Schema.Parser();
         Schema schema = parser.parse(schemaJson);
-
-        Assert.assertEquals(schema.toString(), EXPECTED_SCHEMA_JSON);
+        JSONAssert.assertEquals(schema.toString(), EXPECTED_SCHEMA_JSON, false);
     }
 
     @Test
diff --git a/pulsar-client/src/test/java/org/apache/pulsar/client/schema/AvroTrustedClassesTest.java b/pulsar-client/src/test/java/org/apache/pulsar/client/schema/AvroTrustedClassesTest.java
new file mode 100644
index 000000000000..08f1b3baf31c
--- /dev/null
+++ b/pulsar-client/src/test/java/org/apache/pulsar/client/schema/AvroTrustedClassesTest.java
@@ -0,0 +1,285 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pulsar.client.schema;
+
+import static java.nio.charset.StandardCharsets.UTF_8;
+import static org.assertj.core.api.Assertions.assertThat;
+import java.net.URI;
+import java.util.List;
+import java.util.Map;
+import java.util.Random;
+import org.apache.avro.reflect.ReflectData;
+import org.apache.avro.reflect.Union;
+import org.apache.avro.util.ClassSecurityValidator;
+import org.apache.avro.util.ClassSecurityValidator.ClassSecurityPredicate;
+import org.apache.pulsar.client.api.Schema;
+import org.apache.pulsar.client.api.schema.SchemaDefinition;
+import org.apache.pulsar.client.impl.schema.util.SchemaUtil;
+import org.apache.pulsar.client.schema.fixtures.Order;
+import org.apache.pulsar.client.schema.fixtures.OrderState;
+import org.apache.pulsar.client.schema.fixtures.other.Address;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+/**
+ * Each test pins the global validator to Avro's hardcoded DEFAULT_TRUSTED_CLASSES first, so what is
+ * trusted is only ever what the test itself declares. The build sets no Avro SERIALIZABLE_* properties,
+ * so this matches how a production JVM starts out.
+ */
+public class AvroTrustedClassesTest {
+
+    private ClassSecurityPredicate previousValidator;
+    private AvroTrustedClasses.State previousDeclarations;
+
+    @BeforeMethod
+    public void useProductionBaselineValidator() {
+        previousValidator = ClassSecurityValidator.getGlobal();
+        // Declared trust is process-wide and accumulates, so start each test from the defaults - but
+        // keep what was declared before, since a broker sharing this JVM still needs its own types.
+        previousDeclarations = AvroTrustedClasses.snapshot();
+        ClassSecurityValidator.setGlobal(ClassSecurityValidator.DEFAULT_TRUSTED_CLASSES);
+        AvroTrustedClasses.resetToDefaults();
+    }
+
+    @AfterMethod(alwaysRun = true)
+    public void restoreValidator() {
+        AvroTrustedClasses.restore(previousDeclarations);
+        ClassSecurityValidator.setGlobal(previousValidator);
+    }
+
+    @Test
+    public void testSchemaAvroOverAnApplicationClassNeedsNoDeclaration() {
+        // Constructing the schema is itself the application naming the class, so Pulsar trusts it and
+        // everything the derived schema references. Order pulls in an enum, a record in a *different*
+        // package, a List field and a URI field — none of which the user should have to enumerate.
+        Schema<Order> schema = Schema.AVRO(Order.class);
+        Order order = Order.sample();
+
+        assertThat(schema.decode(schema.encode(order))).usingRecursiveComparison().isEqualTo(order);
+        assertThat(isTrusted(Address.class)).isTrue();
+        assertThat(isTrusted(OrderState.class)).isTrue();
+        assertThat(isTrusted(List.class)).isTrue();
+        assertThat(isTrusted(URI.class)).isTrue();
+    }
+
+    @Test
+    public void testAutoRegistrationDoesNotTrustSchemasArrivingFromTheRegistry() {
+        // The trust boundary: a definition built from wire bytes carries no POJO, which is how
+        // AutoConsumeSchema passes a registry-fetched schema. Whoever registered that schema chose the
+        // class names in it, so they must not widen the allow-list.
+        String wireSchema = new String(Schema.AVRO(Order.class).getSchemaInfo().getSchema(), UTF_8);
+        AvroTrustedClasses.resetToDefaults();
+
+        Schema.AVRO(SchemaDefinition.builder().withJsonDef(wireSchema).build());
+
+        assertThat(isTrusted(Order.class)).isFalse();
+        assertThat(isTrusted(Address.class)).isFalse();
+    }
+
+    @Test
+    public void testAnApplicationClassIsWalkedOnlyOnce() {
+        Schema.AVRO(Order.class);
+        int afterFirst = AvroTrustedClasses.walkedCountForTesting();
+
+        Schema.AVRO(Order.class);
+        Schema.AVRO(Order.class);
+
+        assertThat(AvroTrustedClasses.walkedCountForTesting()).isEqualTo(afterFirst);
+        // ...and the trust is still in place after the cached calls.
+        assertThat(isTrusted(Address.class)).isTrue();
+    }
+
+    @Test
+    public void testTrustClassCoversTheWholeObjectGraph() {
+        // Order pulls in an enum, a record in a *different* package, a List field and a URI field.
+        // Declaring the root class alone has to be enough.
+        AvroTrustedClasses.trust(Order.class);
+
+        Schema<Order> schema = Schema.AVRO(Order.class);
+        Order order = Order.sample();
+
+        assertThat(schema.decode(schema.encode(order))).usingRecursiveComparison().isEqualTo(order);
+    }
+
+    @Test
+    public void testTrustClassReachesTypesTheRootPackageDoesNotCover() {
+        AvroTrustedClasses.trust(Order.class);
+
+        // Named types in other packages, and the declared field types Avro records as properties.
+        assertThat(isTrusted(Address.class)).isTrue();
+        assertThat(isTrusted(OrderState.class)).isTrue();
+        assertThat(isTrusted(List.class)).isTrue();
+        assertThat(isTrusted(URI.class)).isTrue();
+        // ...but nothing beyond what the graph actually reaches.
+        assertThat(isTrusted(Random.class)).isFalse();
+    }
+
+    @Test
+    public void testCollectionTypesAreTrustedOutOfTheBox() {
+        // Avro records a field's declared collection type as a "java-class" property and resolves it
+        // reflectively, so declaring a package alone used to be quietly insufficient for any POJO with a
+        // List field. These are seeded, so that sharp edge is gone.
+        AvroTrustedClasses.trustPackages(Order.class.getPackage().getName());
+
+        assertThat(isTrusted(Order.class)).isTrue();
+        assertThat(isTrusted(List.class)).isTrue();
+        assertThat(isTrusted(Map.class)).isTrue();
+        // Still only the container types, not java.util wholesale.
+        assertThat(isTrusted(Random.class)).isFalse();
+    }
+
+    @Test
+    public void testTrustExactlyDoesNotFollowReferencedTypes() {
+        AvroTrustedClasses.trustExactly(Order.class);
+
+        assertThat(isTrusted(Order.class)).isTrue();
+        // Unlike trust(Class), nothing the class references comes along. (List is seeded, so it is not
+        // a useful witness here.)
+        assertThat(isTrusted(Address.class)).isFalse();
+        assertThat(isTrusted(OrderState.class)).isFalse();
+    }
+
+    @Test
+    public void testTrustWorksForInterfaces() {
+        // Avro derives an empty record for a user interface, so there is nothing to expand, but the
+        // interface itself still has to be trusted: a field declaring it is named after it in the schema.
+        AvroTrustedClasses.trust(Shape.class);
+
+        assertThat(isTrusted(Shape.class)).isTrue();
+    }
+
+    @Test
+    public void testTrustWorksForInterfacesWithNoDerivableSchema() {
+        // ReflectData cannot describe a bare java.util.List — "Can't find element type of Collection" —
+        // so the schema walk fails. Trusting the class itself must still take effect.
+        AvroTrustedClasses.trust(List.class);
+
+        assertThat(isTrusted(List.class)).isTrue();
+    }
+
+    @Test
+    public void testTrustExpandsThroughAUnionOfImplementations() {
+        // Where an interface field enumerates its implementations, Avro inlines them as records in the
+        // schema, so trusting the holder reaches them. Trusting the interface alone would not.
+        AvroTrustedClasses.trust(ShapeHolder.class);
+
+        assertThat(isTrusted(Circle.class)).isTrue();
+        assertThat(isTrusted(Square.class)).isTrue();
+    }
+
+    @Test
+    public void testTrustPredicate() {
+        AvroTrustedClasses.trust(clazz -> clazz.getName().equals(Random.class.getName()));
+
+        assertThat(isTrusted(Random.class)).isTrue();
+    }
+
+    @Test
+    public void testResetToDefaultsDropsDeclarationsButKeepsTheValidatorInstalled() {
+        AvroTrustedClasses.trust(Order.class);
+        assertThat(isTrusted(Order.class)).isTrue();
+        assertThat(AvroTrustedClasses.isInstalled()).isTrue();
+
+        AvroTrustedClasses.resetToDefaults();
+
+        assertThat(isTrusted(Order.class)).isFalse();
+        assertThat(isTrusted(Address.class)).isFalse();
+        // The built-in baseline comes back rather than leaving nothing declared at all.
+        assertThat(isTrusted(List.class)).isTrue();
+        // Still composed into the global validator, so later declarations take effect without a
+        // second install. This is what separates it from the test-only reset.
+        assertThat(AvroTrustedClasses.isInstalled()).isTrue();
+
+        AvroTrustedClasses.trust(Order.class);
+        assertThat(isTrusted(Order.class)).isTrue();
+    }
+
+    @Test
+    public void testResetToDefaultsClearsTheWalkCache() {
+        // Auto-registration caches the schemas it has walked, so the reset has to drop that too -
+        // otherwise the cache would suppress the re-walk and the class would stay untrusted.
+        Schema.AVRO(Order.class);
+        assertThat(AvroTrustedClasses.walkedCountForTesting()).isEqualTo(1);
+        assertThat(isTrusted(Order.class)).isTrue();
+
+        AvroTrustedClasses.resetToDefaults();
+        assertThat(AvroTrustedClasses.walkedCountForTesting()).isZero();
+        assertThat(isTrusted(Order.class)).isFalse();
+
+        Schema.AVRO(Order.class);
+        assertThat(isTrusted(Order.class)).isTrue();
+    }
+
+    @Test
+    public void testTrustRegistersANestedEnumUnderItsBinaryName() throws Exception {
+        // The AUTO_CONSUME-over-a-JSON-enum path resolves the class named in the writer's schema, which
+        // Avro spells with dots ("...Test.Colour") and then resolves by retrying with '$'. The validator
+        // matches on Class.getName(), so the '$' form is what has to be registered. Reproduces the
+        // resolution AutoConsumeSchema.extractFromAvroSchema performs.
+        org.apache.avro.Schema enumSchema = SchemaUtil.parseAvroSchema(
+                new String(Schema.JSON(Colour.class).getSchemaInfo().getSchema(), UTF_8));
+        assertThat(enumSchema.getType()).isEqualTo(org.apache.avro.Schema.Type.ENUM);
+        assertThat(enumSchema.getFullName()).contains(".Colour");
+
+        AvroTrustedClasses.trust(Colour.class);
+
+        assertThat(ReflectData.get().getClass(enumSchema)).isSameAs(Colour.class);
+    }
+
+    private static boolean isTrusted(Class<?> clazz) {
+        return ClassSecurityValidator.getGlobal().isTrusted(clazz);
+    }
+
+    /** Nested so that its binary name uses '$' while Avro spells the schema name with dots. */
+    public enum Colour {
+        RED,
+        GREEN
+    }
+
+    /** A user interface: Avro derives an empty record for it. */
+    public interface Shape {
+    }
+
+    public static class Circle implements Shape {
+        private int radius = 1;
+
+        public int getRadius() {
+            return radius;
+        }
+    }
+
+    public static class Square implements Shape {
+        private int side = 2;
+
+        public int getSide() {
+            return side;
+        }
+    }
+
+    /** Declares the interface's implementations, which is how Avro reflect models polymorphism. */
+    public static class ShapeHolder {
+        @Union({Circle.class, Square.class})
+        private Shape shape = new Circle();
+
+        public Shape getShape() {
+            return shape;
+        }
+    }
+}
diff --git a/pulsar-client/src/test/java/org/apache/pulsar/client/schema/AvroTrustedClassesWithoutValidatorTest.java b/pulsar-client/src/test/java/org/apache/pulsar/client/schema/AvroTrustedClassesWithoutValidatorTest.java
new file mode 100644
index 000000000000..91eb95ad334a
--- /dev/null
+++ b/pulsar-client/src/test/java/org/apache/pulsar/client/schema/AvroTrustedClassesWithoutValidatorTest.java
@@ -0,0 +1,94 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pulsar.client.schema;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatCode;
+import java.lang.reflect.Method;
+import java.net.URL;
+import java.net.URLClassLoader;
+import org.testng.annotations.Test;
+
+/**
+ * Avro only gained {@code ClassSecurityValidator} in 1.12.2, and an application using
+ * {@code pulsar-client-original} can pin an older Avro. Declaring trusted classes has to degrade to a
+ * no-op there rather than failing — {@code AvroSchema.of} calls into this on every schema construction,
+ * so a NoClassDefFoundError would surface as {@code Schema.AVRO(...)} itself breaking.
+ *
+ * <p>Loads {@code AvroTrustedClasses} in a class loader that hides the validator, which is the only way
+ * to exercise the absent case while the test JVM itself has a current Avro.
+ */
+public class AvroTrustedClassesWithoutValidatorTest {
+
+    private static final String VALIDATOR = "org.apache.avro.util.ClassSecurityValidator";
+
+    @Test
+    public void testDeclaringTrustIsANoOpWhenAvroHasNoValidator() throws Exception {
+        try (URLClassLoader hidden = new HidingClassLoader(VALIDATOR)) {
+            Class<?> trustedClasses = hidden.loadClass(AvroTrustedClasses.class.getName());
+            // Loaded by the hiding loader, so this is genuinely the "no validator" world.
+            assertThat(trustedClasses.getClassLoader()).isSameAs(hidden);
+
+            Method trust = trustedClasses.getMethod("trust", Class[].class);
+            Method trustPackages = trustedClasses.getMethod("trustPackages", String[].class);
+            Method isInstalled = trustedClasses.getMethod("isInstalled");
+
+            assertThatCode(() -> {
+                trust.invoke(null, (Object) new Class<?>[] {String.class});
+                trustPackages.invoke(null, (Object) new String[] {"com.example"});
+            }).doesNotThrowAnyException();
+
+            assertThat((Boolean) isInstalled.invoke(null)).isFalse();
+        }
+    }
+
+    /** Delegates everything except the named classes, which it reports as absent. */
+    private static final class HidingClassLoader extends URLClassLoader {
+
+        private final String hiddenPrefix;
+
+        HidingClassLoader(String hiddenPrefix) {
+            // Load from the same class path as the test, but as a child of the platform loader so that
+            // application classes resolve here rather than being delegated to the parent.
+            super(classPathUrls(), ClassLoader.getPlatformClassLoader());
+            this.hiddenPrefix = hiddenPrefix;
+        }
+
+        @Override
+        protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
+            if (name.startsWith(hiddenPrefix)) {
+                throw new ClassNotFoundException(name + " is hidden by this test");
+            }
+            return super.loadClass(name, resolve);
+        }
+
+        private static URL[] classPathUrls() {
+            String[] entries = System.getProperty("java.class.path").split(System.getProperty("path.separator"));
+            URL[] urls = new URL[entries.length];
+            for (int i = 0; i < entries.length; i++) {
+                try {
+                    urls[i] = new java.io.File(entries[i]).toURI().toURL();
+                } catch (Exception e) {
+                    throw new IllegalStateException("Cannot build the test class path", e);
+                }
+            }
+            return urls;
+        }
+    }
+}
diff --git a/pulsar-client/src/test/java/org/apache/pulsar/client/schema/fixtures/Order.java b/pulsar-client/src/test/java/org/apache/pulsar/client/schema/fixtures/Order.java
new file mode 100644
index 000000000000..471b134ee99a
--- /dev/null
+++ b/pulsar-client/src/test/java/org/apache/pulsar/client/schema/fixtures/Order.java
@@ -0,0 +1,70 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pulsar.client.schema.fixtures;
+
+import java.net.URI;
+import java.util.ArrayList;
+import java.util.List;
+import org.apache.pulsar.client.schema.fixtures.other.Address;
+
+/**
+ * Stands in for an application POJO that exercises everything trusting a package alone would miss: an
+ * enum, a record in another package, a declared {@code List} field and a {@code @Stringable} field.
+ */
+public class Order {
+
+    private String id;
+    private OrderState state;
+    private Address shipTo;
+    private List<String> items;
+    private URI callback;
+
+    public Order() {
+    }
+
+    public static Order sample() {
+        Order order = new Order();
+        order.id = "order-1";
+        order.state = OrderState.NEW;
+        order.shipTo = new Address("Helsinki");
+        order.items = new ArrayList<>(List.of("widget", "gadget"));
+        order.callback = URI.create("https://example.com/callback");
+        return order;
+    }
+
+    public String getId() {
+        return id;
+    }
+
+    public OrderState getState() {
+        return state;
+    }
+
+    public Address getShipTo() {
+        return shipTo;
+    }
+
+    public List<String> getItems() {
+        return items;
+    }
+
+    public URI getCallback() {
+        return callback;
+    }
+}
diff --git a/pulsar-client/src/test/java/org/apache/pulsar/client/schema/fixtures/OrderState.java b/pulsar-client/src/test/java/org/apache/pulsar/client/schema/fixtures/OrderState.java
new file mode 100644
index 000000000000..57720fd433b6
--- /dev/null
+++ b/pulsar-client/src/test/java/org/apache/pulsar/client/schema/fixtures/OrderState.java
@@ -0,0 +1,25 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pulsar.client.schema.fixtures;
+
+/** Enum reached from {@link Order}, in the same package as the root POJO. */
+public enum OrderState {
+    NEW,
+    SHIPPED
+}
diff --git a/pulsar-client/src/test/java/org/apache/pulsar/client/schema/fixtures/other/Address.java b/pulsar-client/src/test/java/org/apache/pulsar/client/schema/fixtures/other/Address.java
new file mode 100644
index 000000000000..e1a84de4334a
--- /dev/null
+++ b/pulsar-client/src/test/java/org/apache/pulsar/client/schema/fixtures/other/Address.java
@@ -0,0 +1,35 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pulsar.client.schema.fixtures.other;
+
+/** Record reached from Order but living in a DIFFERENT package, so package trust would miss it. */
+public class Address {
+    private String city;
+
+    public Address() {
+    }
+
+    public Address(String city) {
+        this.city = city;
+    }
+
+    public String getCity() {
+        return city;
+    }
+}