-
Notifications
You must be signed in to change notification settings - Fork 16
feat: support inbound plugin jsonschema validator #239
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
cchenggit
wants to merge
6
commits into
webhookx-io:main
Choose a base branch
from
cchenggit:feat/plugin-jsonschema-validator
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
56a15da
feat: support inbound plugin jsonschema validator
cchenggit b6f075d
feat: remove schema resource and add default schema
cchenggit 79d33b2
chore: update README
cchenggit beec762
chore: update config example
cchenggit 014d7ec
test: clean debug print
cchenggit 442afd0
update schema version config
cchenggit File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,40 @@ | ||
| package jsonschema | ||
|
|
||
| import ( | ||
| "github.com/getkin/kin-openapi/openapi3" | ||
| lru "github.com/hashicorp/golang-lru/v2" | ||
| "github.com/webhookx-io/webhookx/pkg/openapi" | ||
| "github.com/webhookx-io/webhookx/utils" | ||
| ) | ||
|
|
||
| type JSONSchema struct { | ||
| schemaDef string | ||
| hex string | ||
| } | ||
|
|
||
| func New(schemaDef []byte) *JSONSchema { | ||
| return &JSONSchema{ | ||
| schemaDef: string(schemaDef), | ||
| hex: utils.Sha256(string(schemaDef)), | ||
| } | ||
| } | ||
|
|
||
| var cache, _ = lru.New[string, *openapi3.Schema](128) | ||
|
|
||
| func (s *JSONSchema) Validate(ctx *ValidatorContext) error { | ||
| schema, ok := cache.Get(s.hex) | ||
| if !ok { | ||
| schema = &openapi3.Schema{} | ||
| err := schema.UnmarshalJSON([]byte(s.schemaDef)) | ||
| if err != nil { | ||
| return err | ||
| } | ||
| cache.Add(s.hex, schema) | ||
| } | ||
|
|
||
| err := openapi.Validate(schema, ctx.HTTPRequest.Data) | ||
| if err != nil { | ||
| return err | ||
| } | ||
| return nil | ||
| } |
66 changes: 66 additions & 0 deletions
66
plugins/jsonschema_validator/jsonschema/jsonschema_test.go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,66 @@ | ||
| package jsonschema | ||
|
|
||
| import ( | ||
| "encoding/json" | ||
| . "github.com/onsi/ginkgo/v2" | ||
| . "github.com/onsi/gomega" | ||
| "testing" | ||
| ) | ||
|
|
||
| func TestJSONSchema(t *testing.T) { | ||
| RegisterFailHandler(Fail) | ||
| RunSpecs(t, "Schema Validator Suite") | ||
| } | ||
|
|
||
| var _ = Describe("Schema Validator Plugin", func() { | ||
|
|
||
| Context("JSONSchema Validator", func() { | ||
| It("should validate valid JSON data against the schema", func() { | ||
| schemaDef := `{ | ||
| "type": "object", | ||
| "properties": { | ||
| "name": { "type": "string" }, | ||
| "age": { "type": "integer", "minimum": 0 } | ||
| }, | ||
| "required": ["name", "age"] | ||
| }` | ||
|
|
||
| validator := New([]byte(schemaDef)) | ||
|
|
||
| validData := map[string]interface{}{"name": "John Doe", "age": 30} | ||
| ctx := &ValidatorContext{ | ||
| HTTPRequest: &HTTPRequest{ | ||
| Data: validData, | ||
| }, | ||
| } | ||
|
|
||
| err := validator.Validate(ctx) | ||
| Expect(err).To(BeNil()) | ||
| }) | ||
|
|
||
| It("should return an error for invalid JSON data against the schema", func() { | ||
| schemaDef := `{ | ||
| "type": "object", | ||
| "properties": { | ||
| "name": { "type": "string" }, | ||
| "age": { "type": "integer", "minimum": 0 } | ||
| }, | ||
| "required": ["name", "age"] | ||
| }` | ||
|
|
||
| validator := New([]byte(schemaDef)) | ||
|
|
||
| invalidData := map[string]interface{}{"name": "John Doe", "age": -5} | ||
| ctx := &ValidatorContext{ | ||
| HTTPRequest: &HTTPRequest{ | ||
| Data: invalidData, | ||
| }, | ||
| } | ||
|
|
||
| err := validator.Validate(ctx) | ||
| Expect(err).ToNot(BeNil()) | ||
| b, _ := json.Marshal(err) | ||
| Expect(string(b)).To(Equal(`{"message":"request validation","fields":{"age":"number must be at least 0"}}`)) | ||
| }) | ||
| }) | ||
| }) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,18 @@ | ||
| package jsonschema | ||
|
|
||
| import ( | ||
| "net/http" | ||
| ) | ||
|
|
||
| type Validator interface { | ||
| Validate(ctx *ValidatorContext) error | ||
| } | ||
|
|
||
| type ValidatorContext struct { | ||
| HTTPRequest *HTTPRequest | ||
| } | ||
|
|
||
| type HTTPRequest struct { | ||
| R *http.Request | ||
| Data map[string]any | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,149 @@ | ||
| package jsonschema_validator | ||
|
|
||
| import ( | ||
| "context" | ||
| "encoding/json" | ||
| "errors" | ||
| "fmt" | ||
| "github.com/getkin/kin-openapi/openapi3" | ||
| "github.com/webhookx-io/webhookx/pkg/errs" | ||
| "github.com/webhookx-io/webhookx/pkg/http/response" | ||
| "github.com/webhookx-io/webhookx/pkg/plugin" | ||
| "github.com/webhookx-io/webhookx/pkg/types" | ||
| "github.com/webhookx-io/webhookx/plugins/jsonschema_validator/jsonschema" | ||
| "github.com/webhookx-io/webhookx/utils" | ||
| ) | ||
|
|
||
| type Config struct { | ||
| Draft string `json:"draft" validate:"required,oneof=6 default:6"` | ||
| DefaultSchema string `json:"default_schema" validate:"omitempty,json,max=1048576"` | ||
| Schemas map[string]*Schema `json:"schemas" validate:"dive"` | ||
| } | ||
|
|
||
| type Schema struct { | ||
| Schema string `json:"schema" validate:"omitempty,json,max=1048576"` | ||
| } | ||
|
|
||
| type SchemaValidatorPlugin struct { | ||
| plugin.BasePlugin[Config] | ||
| } | ||
|
|
||
| func New(config []byte) (plugin.Plugin, error) { | ||
| p := &SchemaValidatorPlugin{} | ||
| p.Name = "jsonschema-validator" | ||
|
|
||
| if config != nil { | ||
| if err := p.UnmarshalConfig(config); err != nil { | ||
| return nil, err | ||
| } | ||
| } | ||
| return p, nil | ||
| } | ||
|
|
||
| func unmarshalAndValidateSchema(schema string) (*openapi3.Schema, error) { | ||
| openapiSchema := &openapi3.Schema{} | ||
| err := openapiSchema.UnmarshalJSON([]byte(schema)) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("value must be a valid jsonschema") | ||
| } | ||
| err = openapiSchema.Validate(context.Background(), openapi3.EnableSchemaFormatValidation()) | ||
| if err != nil { | ||
| return openapiSchema, err | ||
| } | ||
| return openapiSchema, nil | ||
| } | ||
|
|
||
| func (p *SchemaValidatorPlugin) ValidateConfig() error { | ||
| err := utils.Validate(p.Config) | ||
| if err != nil { | ||
| return err | ||
| } | ||
|
|
||
| e := errs.NewValidateError(errors.New("request validation")) | ||
|
|
||
| var defaultErr error | ||
| if p.Config.DefaultSchema != "" { | ||
| _, err := unmarshalAndValidateSchema(p.Config.DefaultSchema) | ||
| if err != nil { | ||
| defaultErr = err | ||
| e.Fields = map[string]interface{}{ | ||
| "default_schema": err.Error(), | ||
| } | ||
| } | ||
| } | ||
|
|
||
| for event, schema := range p.Config.Schemas { | ||
| field := fmt.Sprintf("schemas[%s]", event) | ||
| if schema == nil || schema.Schema == "" { | ||
| if defaultErr != nil { | ||
| e.Fields[field] = map[string]string{ | ||
| "schema": "invalid due to reusing the default_schema definition", | ||
| } | ||
| } | ||
| } else { | ||
| _, err = unmarshalAndValidateSchema(schema.Schema) | ||
| if err != nil { | ||
| e.Fields[field] = map[string]string{ | ||
| "schema": err.Error(), | ||
| } | ||
| } | ||
| } | ||
| } | ||
| if len(e.Fields) > 0 { | ||
| return e | ||
| } | ||
| return nil | ||
| } | ||
|
|
||
| func (p *SchemaValidatorPlugin) ExecuteInbound(inbound *plugin.Inbound) (res plugin.InboundResult, err error) { | ||
| var event map[string]any | ||
| body := inbound.RawBody | ||
| if err = json.Unmarshal(body, &event); err != nil { | ||
| return | ||
| } | ||
|
|
||
| eventType, ok := event["event_type"].(string) | ||
| if !ok || eventType == "" { | ||
| res.Payload = body | ||
| return | ||
| } | ||
|
|
||
| data := event["data"] | ||
| if data == nil { | ||
| res.Payload = body | ||
| return | ||
| } | ||
|
|
||
| schema, ok := p.Config.Schemas[eventType] | ||
| if !ok { | ||
| res.Payload = body | ||
| return | ||
| } | ||
| if schema == nil || schema.Schema == "" { | ||
| if p.Config.DefaultSchema == "" { | ||
| res.Payload = body | ||
| return | ||
| } | ||
| schema = &Schema{ | ||
| Schema: p.Config.DefaultSchema, | ||
| } | ||
| } | ||
|
|
||
| validator := jsonschema.New([]byte(schema.Schema)) | ||
| e := validator.Validate(&jsonschema.ValidatorContext{ | ||
| HTTPRequest: &jsonschema.HTTPRequest{ | ||
| R: inbound.Request, | ||
| Data: data.(map[string]any), | ||
| }, | ||
| }) | ||
| if e != nil { | ||
| response.JSON(inbound.Response, 400, types.ErrorResponse{ | ||
| Message: "Request Validation", | ||
| Error: e, | ||
| }) | ||
| res.Terminated = true | ||
| return | ||
| } | ||
| res.Payload = body | ||
| return | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Requires a
versionfield. (enum: draft4/draft6/draft7/etc..)There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
current jsonschema only support openapi3 schema, which based on the draft6
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
why not use string? (
draft4,draft6,draft202012)There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
let's use string value but simplify the version number
draft: 4/6/7/2019-09/2020-12