Skip to content

Commit 6bad239

Browse files
authored
Add better Avro validation (#365)
* Add better Avro validation * Minor cleanup * Minor cleanup
1 parent fd4d24a commit 6bad239

File tree

2 files changed

+35
-1
lines changed

2 files changed

+35
-1
lines changed

schemaregistry/serde/avro.ts

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import {
33
FieldTransform,
44
FieldType, Migration, RefResolver,
55
RuleConditionError,
6-
RuleContext, SchemaId, SerdeType,
6+
RuleContext, SchemaId, SerdeType, SerializationError,
77
Serializer, SerializerConfig
88
} from "./serde";
99
import {
@@ -93,6 +93,10 @@ export class AvroSerializer extends Serializer implements AvroSerde {
9393
const subject = this.subjectName(topic, info)
9494
msg = await this.executeRules(
9595
subject, topic, RuleMode.WRITE, null, info, msg, getInlineTags(info, deps))
96+
avroType.isValid(msg, {errorHook: (path, any, type) => {
97+
throw new SerializationError(
98+
`Invalid message at ${path.join('.')}, expected ${type}, got ${stringify(any)}`)
99+
}})
96100
let msgBytes = avroType.toBuffer(msg)
97101
msgBytes = await this.executeRulesWithPhase(
98102
subject, topic, RulePhase.ENCODING, RuleMode.WRITE, null, info, msgBytes, null)

schemaregistry/test/serde/avro.spec.ts

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,18 @@ const demoSchema = `
7575
]
7676
}
7777
`
78+
const nameSchema = `
79+
{
80+
"type": "record",
81+
"namespace": "examples",
82+
"name": "NameSchema",
83+
"fields": [
84+
{ "name": "fullName", "type": "string" },
85+
{ "name": "lastName", "type": "string" }
86+
],
87+
"version": "1"
88+
}
89+
`
7890
const demoSchemaSingleTag = `
7991
{
8092
"name": "DemoSchema",
@@ -369,6 +381,24 @@ describe('AvroSerializer', () => {
369381
expect(obj2.boolField).toEqual(obj.boolField);
370382
expect(obj2.bytesField).toEqual(obj.bytesField);
371383
})
384+
it('bad serialization', async () => {
385+
let conf: ClientConfig = {
386+
baseURLs: [baseURL],
387+
cacheCapacity: 1000
388+
}
389+
let client = SchemaRegistryClient.newClient(conf)
390+
let ser = new AvroSerializer(client, SerdeType.VALUE, {useLatestVersion: true})
391+
let info = {
392+
schemaType: 'AVRO',
393+
schema: nameSchema
394+
}
395+
await client.register(subject, info, false)
396+
try {
397+
await ser.serialize(topic, { lastName: "lastName" })
398+
} catch (err) {
399+
expect(err).toBeInstanceOf(SerializationError)
400+
}
401+
})
372402
it('guid in header', async () => {
373403
let conf: ClientConfig = {
374404
baseURLs: [baseURL],

0 commit comments

Comments
 (0)