-
Notifications
You must be signed in to change notification settings - Fork 43
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
Rule Type schema validation: change library and apply defaults #4953
Merged
Merged
Changes from all commits
Commits
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 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 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 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 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 |
---|---|---|
|
@@ -7,7 +7,8 @@ import ( | |
"fmt" | ||
"strings" | ||
|
||
"github.com/xeipuuv/gojsonschema" | ||
"github.com/santhosh-tekuri/jsonschema/v6" | ||
"google.golang.org/protobuf/types/known/structpb" | ||
|
||
minderv1 "github.com/mindersec/minder/pkg/api/protobuf/go/minder/v1" | ||
) | ||
|
@@ -18,32 +19,32 @@ type RuleValidator struct { | |
ruleTypeName string | ||
|
||
// schema is the schema that this rule type must conform to | ||
schema *gojsonschema.Schema | ||
schema *jsonschema.Schema | ||
// paramSchema is the schema that the parameters for this rule type must conform to | ||
paramSchema *gojsonschema.Schema | ||
paramSchema *jsonschema.Schema | ||
} | ||
|
||
// NewRuleValidator creates a new rule validator | ||
func NewRuleValidator(rt *minderv1.RuleType) (*RuleValidator, error) { | ||
// Load schemas | ||
schemaLoader := gojsonschema.NewGoLoader(rt.Def.RuleSchema) | ||
schema, err := gojsonschema.NewSchema(schemaLoader) | ||
if rt.GetDef().GetRuleSchema() == nil { | ||
return nil, fmt.Errorf("rule type %s does not have a rule schema", rt.Name) | ||
} | ||
// Create a new schema compiler | ||
// Compile the main rule schema | ||
mainSchema, err := compileSchemaFromPB(rt.GetDef().GetRuleSchema()) | ||
if err != nil { | ||
return nil, fmt.Errorf("cannot create json schema: %w", err) | ||
} | ||
|
||
var paramSchema *gojsonschema.Schema | ||
if rt.Def.ParamSchema != nil { | ||
paramSchemaLoader := gojsonschema.NewGoLoader(rt.Def.ParamSchema) | ||
paramSchema, err = gojsonschema.NewSchema(paramSchemaLoader) | ||
if err != nil { | ||
return nil, fmt.Errorf("cannot create json schema for params: %w", err) | ||
} | ||
// Compile the parameter schema if it exists | ||
paramSchema, err := compileSchemaFromPB(rt.GetDef().GetParamSchema()) | ||
if err != nil { | ||
return nil, fmt.Errorf("cannot create json schema for params: %w", err) | ||
} | ||
|
||
return &RuleValidator{ | ||
ruleTypeName: rt.Name, | ||
schema: schema, | ||
schema: mainSchema, | ||
paramSchema: paramSchema, | ||
}, nil | ||
} | ||
|
@@ -57,7 +58,7 @@ func (r *RuleValidator) ValidateRuleDefAgainstSchema(contextualProfile map[strin | |
Err: err.Error(), | ||
} | ||
} | ||
|
||
applyDefaults(r.schema, contextualProfile) | ||
return nil | ||
} | ||
|
||
|
@@ -67,36 +68,66 @@ func (r *RuleValidator) ValidateParamsAgainstSchema(params map[string]any) error | |
if r.paramSchema == nil { | ||
return nil | ||
} | ||
|
||
if err := validateAgainstSchema(r.paramSchema, params); err != nil { | ||
return &RuleValidationError{ | ||
RuleType: r.ruleTypeName, | ||
Err: err.Error(), | ||
} | ||
} | ||
|
||
applyDefaults(r.paramSchema, params) | ||
return nil | ||
} | ||
|
||
func validateAgainstSchema(schema *gojsonschema.Schema, obj map[string]any) error { | ||
documentLoader := gojsonschema.NewGoLoader(obj) | ||
result, err := schema.Validate(documentLoader) | ||
if err != nil { | ||
return fmt.Errorf("cannot validate json schema: %s", err) | ||
func compileSchemaFromPB(schemaData *structpb.Struct) (*jsonschema.Schema, error) { | ||
if schemaData == nil { | ||
return nil, nil | ||
} | ||
|
||
if !result.Valid() { | ||
return buildValidationError(result.Errors()) | ||
return compileSchemaFromMap(schemaData.AsMap()) | ||
} | ||
|
||
func compileSchemaFromMap(schemaData map[string]any) (*jsonschema.Schema, error) { | ||
compiler := jsonschema.NewCompiler() | ||
if err := compiler.AddResource("schema.json", schemaData); err != nil { | ||
return nil, fmt.Errorf("invalid schema: %w", err) | ||
} | ||
return compiler.Compile("schema.json") | ||
} | ||
|
||
func validateAgainstSchema(schema *jsonschema.Schema, obj map[string]any) error { | ||
if err := schema.Validate(obj); err != nil { | ||
if verror, ok := err.(*jsonschema.ValidationError); ok { | ||
return buildValidationError(verror.Causes) | ||
} | ||
return fmt.Errorf("invalid json schema: %s", err) | ||
} | ||
return nil | ||
} | ||
|
||
func buildValidationError(errs []gojsonschema.ResultError) error { | ||
func buildValidationError(errs []*jsonschema.ValidationError) error { | ||
problems := make([]string, 0, len(errs)) | ||
for _, desc := range errs { | ||
problems = append(problems, desc.String()) | ||
problems = append(problems, desc.Error()) | ||
} | ||
|
||
return fmt.Errorf("invalid json schema: %s", strings.TrimSpace(strings.Join(problems, "\n"))) | ||
} | ||
|
||
// applyDefaults recursively applies default values from the schema to the object. | ||
func applyDefaults(schema *jsonschema.Schema, obj map[string]any) { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I wish the library had this function, but it looks like it doesn't. 😞 There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. No library I found has one 😢 |
||
for key, def := range schema.Properties { | ||
// If the key does not exist in obj, apply the default value from the schema if present | ||
if _, exists := obj[key]; !exists && def.Default != nil { | ||
obj[key] = *def.Default | ||
} | ||
|
||
// If def has properties, apply defaults to the nested object | ||
if def.Properties != nil { | ||
o, ok := obj[key].(map[string]any) | ||
if !ok { | ||
// cannot apply defaults to non-object types | ||
continue | ||
} | ||
applyDefaults(def, o) | ||
} | ||
} | ||
} |
This file contains 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
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.
Why
TrimSpace
here?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.
In all honesty, I don't remember. It may not be needed anymore.