1// Licensed to Elasticsearch B.V. under one or more contributor
2// license agreements. See the NOTICE file distributed with
3// this work for additional information regarding copyright
4// ownership. Elasticsearch B.V. licenses this file to you under
5// the Apache License, Version 2.0 (the "License"); you may
6// not use this file except in compliance with the License.
7// You may obtain a copy of the License at
8//
9//     http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18// +build gofuzz
19
20package model // import "go.elastic.co/apm/model"
21
22import (
23	"bytes"
24	"encoding/json"
25
26	"go.elastic.co/apm/internal/apmschema"
27	"go.elastic.co/fastjson"
28)
29
30func Fuzz(data []byte) int {
31	type Payload struct {
32		Service      *Service      `json:"service"`
33		Process      *Process      `json:"process,omitempty"`
34		System       *System       `json:"system,omitempty"`
35		Errors       []*Error      `json:"errors"`
36		Transactions []Transaction `json:"transactions"`
37	}
38
39	var payload Payload
40	decoder := json.NewDecoder(bytes.NewReader(data))
41	decoder.DisallowUnknownFields()
42	if err := decoder.Decode(&payload); err != nil {
43		return -1
44	}
45	raw := make(map[string]interface{})
46	if err := json.Unmarshal(data, &raw); err != nil {
47		return -1
48	}
49
50	if len(payload.Errors) != 0 {
51		payload := ErrorsPayload{
52			Service: payload.Service,
53			Process: payload.Process,
54			System:  payload.System,
55			Errors:  payload.Errors,
56		}
57		var w fastjson.Writer
58		if err := payload.MarshalFastJSON(&w); err != nil {
59			panic(err)
60		}
61		if err := apmschema.Errors.Validate(bytes.NewReader(w.Bytes())); err != nil {
62			panic(err)
63		}
64	}
65
66	if len(payload.Transactions) != 0 {
67		payload := TransactionsPayload{
68			Service:      payload.Service,
69			Process:      payload.Process,
70			System:       payload.System,
71			Transactions: payload.Transactions,
72		}
73		var w fastjson.Writer
74		if err := payload.MarshalFastJSON(&w); err != nil {
75			panic(err)
76		}
77		if err := apmschema.Transactions.Validate(bytes.NewReader(w.Bytes())); err != nil {
78			panic(err)
79		}
80	}
81	return 0
82}
83