82 lines
2.3 KiB
Go
82 lines
2.3 KiB
Go
package validjsonschema
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"fmt"
|
|
|
|
"github.com/santhosh-tekuri/jsonschema/v6"
|
|
|
|
"gitea.maximumdirect.net/eric/notarius/internal/framework/contracts"
|
|
"gitea.maximumdirect.net/eric/notarius/internal/framework/pipeline"
|
|
)
|
|
|
|
const Key = "generic/valid_json_schema"
|
|
const ReasonCodeInvalidJSON = "invalid_json"
|
|
const ReasonCodeSchemaInvalid = "json_schema_invalid"
|
|
|
|
var _ contracts.Validator = (*Validator)(nil)
|
|
|
|
type Validator struct{}
|
|
|
|
func New() *Validator {
|
|
return &Validator{}
|
|
}
|
|
|
|
func (v *Validator) Name() string {
|
|
return Key
|
|
}
|
|
|
|
func (v *Validator) ExecutionClass() contracts.ExecutionClass {
|
|
return contracts.ExecutionClassDeterministic
|
|
}
|
|
|
|
func (v *Validator) Validate(ctx context.Context, req contracts.ValidationRequest) (contracts.ValidationResult, error) {
|
|
if len(req.Schema.JSONSchema) == 0 {
|
|
return contracts.ValidationResult{}, fmt.Errorf("response schema content is not available")
|
|
}
|
|
|
|
instance, err := jsonschema.UnmarshalJSON(bytes.NewReader(req.Payload.Content))
|
|
if err != nil {
|
|
return contracts.ValidationResult{
|
|
Approved: false,
|
|
ReasonCode: ReasonCodeInvalidJSON,
|
|
Message: "payload is not valid JSON",
|
|
}, nil
|
|
}
|
|
|
|
schemaDocument, err := jsonschema.UnmarshalJSON(bytes.NewReader(req.Schema.JSONSchema))
|
|
if err != nil {
|
|
return contracts.ValidationResult{}, fmt.Errorf("parse response schema: %w", err)
|
|
}
|
|
compiler := jsonschema.NewCompiler()
|
|
if err := compiler.AddResource("schema.json", schemaDocument); err != nil {
|
|
return contracts.ValidationResult{}, fmt.Errorf("load response schema: %w", err)
|
|
}
|
|
schema, err := compiler.Compile("schema.json")
|
|
if err != nil {
|
|
return contracts.ValidationResult{}, fmt.Errorf("compile response schema: %w", err)
|
|
}
|
|
if err := schema.Validate(instance); err != nil {
|
|
return contracts.ValidationResult{
|
|
Approved: false,
|
|
ReasonCode: ReasonCodeSchemaInvalid,
|
|
Message: "payload does not conform to response schema",
|
|
}, nil
|
|
}
|
|
return contracts.ValidationResult{Approved: true}, nil
|
|
}
|
|
|
|
func Spec() pipeline.ValidatorSpec {
|
|
return pipeline.ValidatorSpec{
|
|
Key: Key,
|
|
ExecutionClass: contracts.ExecutionClassDeterministic,
|
|
}
|
|
}
|
|
|
|
func Register(registry *pipeline.ValidatorRegistry) error {
|
|
return registry.RegisterWithSpec(Spec(), func() (contracts.Validator, error) {
|
|
return New(), nil
|
|
})
|
|
}
|