|
| 1 | +package jsonschema_validator |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "encoding/json" |
| 6 | + "errors" |
| 7 | + "fmt" |
| 8 | + "github.com/getkin/kin-openapi/openapi3" |
| 9 | + lru "github.com/hashicorp/golang-lru/v2" |
| 10 | + "github.com/webhookx-io/webhookx/pkg/errs" |
| 11 | + "github.com/webhookx-io/webhookx/pkg/plugin" |
| 12 | + "github.com/webhookx-io/webhookx/plugins/jsonschema_validator/jsonschema" |
| 13 | + "github.com/webhookx-io/webhookx/utils" |
| 14 | + "io" |
| 15 | + "net/http" |
| 16 | + "os" |
| 17 | + "time" |
| 18 | +) |
| 19 | + |
| 20 | +type Config struct { |
| 21 | + Schemas map[string]*SchemaResource `json:"schemas" validate:"dive,required"` |
| 22 | +} |
| 23 | + |
| 24 | +type EventTypeSchema struct { |
| 25 | + EventType string `json:"event_type" validate:"required,max=100"` |
| 26 | + JSONSchema string `json:"jsonschema" validate:"required,jsonschema,max=1048576"` |
| 27 | +} |
| 28 | + |
| 29 | +type SchemaResource struct { |
| 30 | + JSONString string `json:"json" validate:"omitempty,json,max=1048576"` |
| 31 | + File string `json:"file" validate:"omitempty,file"` |
| 32 | + URL string `json:"url" validate:"omitempty,url"` |
| 33 | +} |
| 34 | + |
| 35 | +var cache, _ = lru.New[string, []byte](128) |
| 36 | + |
| 37 | +func (s *SchemaResource) Resource() ([]byte, string, error) { |
| 38 | + // priority: json > file > url |
| 39 | + if s.JSONString != "" { |
| 40 | + return []byte(s.JSONString), "json", nil |
| 41 | + } |
| 42 | + if s.File != "" { |
| 43 | + bytes, ok := cache.Get(s.File) |
| 44 | + if ok { |
| 45 | + return bytes, "file", nil |
| 46 | + } |
| 47 | + bytes, err := os.ReadFile(s.File) |
| 48 | + if err != nil { |
| 49 | + return nil, "file", fmt.Errorf("failed to read schema: %w", err) |
| 50 | + } |
| 51 | + cache.Add(s.File, bytes) |
| 52 | + return bytes, "file", nil |
| 53 | + } |
| 54 | + if s.URL != "" { |
| 55 | + bytes, ok := cache.Get(s.URL) |
| 56 | + if ok { |
| 57 | + return bytes, "url", nil |
| 58 | + } |
| 59 | + client := &http.Client{ |
| 60 | + Timeout: time.Second * 2, |
| 61 | + } |
| 62 | + resp, err := client.Get(s.URL) |
| 63 | + if err != nil { |
| 64 | + return nil, "url", fmt.Errorf("failed to fetch schema: %w", err) |
| 65 | + } |
| 66 | + defer func() { _ = resp.Body.Close() }() |
| 67 | + body, err := io.ReadAll(resp.Body) |
| 68 | + if err != nil { |
| 69 | + return nil, "url", fmt.Errorf("failed to read schema from response: %w", err) |
| 70 | + } |
| 71 | + cache.Add(s.URL, body) |
| 72 | + return body, "url", nil |
| 73 | + } |
| 74 | + return nil, "json", errors.New("no schema defined") |
| 75 | +} |
| 76 | + |
| 77 | +type SchemaValidatorPlugin struct { |
| 78 | + plugin.BasePlugin[Config] |
| 79 | +} |
| 80 | + |
| 81 | +func New(config []byte) (plugin.Plugin, error) { |
| 82 | + p := &SchemaValidatorPlugin{} |
| 83 | + p.Name = "jsonschema-validator" |
| 84 | + |
| 85 | + if config != nil { |
| 86 | + if err := p.UnmarshalConfig(config); err != nil { |
| 87 | + return nil, err |
| 88 | + } |
| 89 | + } |
| 90 | + return p, nil |
| 91 | +} |
| 92 | + |
| 93 | +func (p *SchemaValidatorPlugin) ValidateConfig() error { |
| 94 | + err := utils.Validate(p.Config) |
| 95 | + if err != nil { |
| 96 | + return err |
| 97 | + } |
| 98 | + |
| 99 | + e := errs.NewValidateError(errors.New("request validation")) |
| 100 | + for event, schema := range p.Config.Schemas { |
| 101 | + field := fmt.Sprintf("schemas[%s]", event) |
| 102 | + if schema == nil { |
| 103 | + e.Fields[field] = fmt.Errorf("schema is empty") |
| 104 | + return e |
| 105 | + } |
| 106 | + schemaBytes, invalidField, err := schema.Resource() |
| 107 | + if err != nil { |
| 108 | + e.Fields[field] = map[string]string{ |
| 109 | + invalidField: err.Error(), |
| 110 | + } |
| 111 | + return e |
| 112 | + } |
| 113 | + openapiSchema := &openapi3.Schema{} |
| 114 | + err = openapiSchema.UnmarshalJSON(schemaBytes) |
| 115 | + if err != nil { |
| 116 | + e.Fields[field] = map[string]string{ |
| 117 | + invalidField: "the content must be a valid json string", |
| 118 | + } |
| 119 | + return e |
| 120 | + } |
| 121 | + err = openapiSchema.Validate(context.Background(), openapi3.EnableSchemaFormatValidation()) |
| 122 | + if err != nil { |
| 123 | + e.Fields[field] = map[string]string{ |
| 124 | + invalidField: fmt.Sprintf("invalid jsonschema: %v", err), |
| 125 | + } |
| 126 | + return e |
| 127 | + } |
| 128 | + } |
| 129 | + return nil |
| 130 | +} |
| 131 | + |
| 132 | +func (p *SchemaValidatorPlugin) ExecuteInbound(inbound *plugin.Inbound) (res plugin.InboundResult, err error) { |
| 133 | + // parse body to get event type |
| 134 | + var event map[string]any |
| 135 | + body := inbound.RawBody |
| 136 | + if err = json.Unmarshal(body, &event); err != nil { |
| 137 | + return |
| 138 | + } |
| 139 | + |
| 140 | + eventType, ok := event["event_type"].(string) |
| 141 | + if !ok || eventType == "" { |
| 142 | + res.Payload = body |
| 143 | + return |
| 144 | + } |
| 145 | + |
| 146 | + data := event["data"] |
| 147 | + if data == nil { |
| 148 | + res.Payload = body |
| 149 | + return |
| 150 | + } |
| 151 | + |
| 152 | + schemaResource, ok := p.Config.Schemas[eventType] |
| 153 | + if !ok || schemaResource == nil { |
| 154 | + res.Payload = body |
| 155 | + return |
| 156 | + } |
| 157 | + |
| 158 | + bytes, _, err := schemaResource.Resource() |
| 159 | + if err != nil { |
| 160 | + return |
| 161 | + } |
| 162 | + validator := jsonschema.New(bytes) |
| 163 | + err = validator.Validate(&jsonschema.ValidatorContext{ |
| 164 | + HTTPRequest: &jsonschema.HTTPRequest{ |
| 165 | + R: inbound.Request, |
| 166 | + Data: data.(map[string]any), |
| 167 | + }, |
| 168 | + }) |
| 169 | + if err != nil { |
| 170 | + return |
| 171 | + } |
| 172 | + res.Payload = body |
| 173 | + return |
| 174 | +} |
0 commit comments