Skip to content

Commit

Permalink
aspects: map values cannot contain unexpected entries (canonical#13286)
Browse files Browse the repository at this point in the history
Signed-off-by: Miguel Pires <[email protected]>
  • Loading branch information
MiguelPires authored Oct 16, 2023
1 parent 1f2bb3d commit cc790fb
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 8 deletions.
8 changes: 8 additions & 0 deletions aspects/schema.go
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,14 @@ func (v *mapSchema) Validate(raw []byte) error {
return err
}

if v.entrySchemas != nil {
for key := range mapValue {
if _, ok := v.entrySchemas[key]; !ok {
return fmt.Errorf(`map contains unexpected key %q`, key)
}
}
}

var missing bool
for _, required := range v.requiredCombs {
missing = false
Expand Down
34 changes: 26 additions & 8 deletions aspects/schema_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,30 @@ func (*schemaSuite) TestMapWithSchemaConstraint(c *C) {
c.Assert(err, IsNil)
}

func (*schemaSuite) TestMapWithUnexpectedKey(c *C) {
schemaStr := []byte(`{
"schema": {
"snaps": {
"schema": {
"foo": "string"
}
}
}
}`)

input := []byte(`{
"snaps": {
"foo": "abc",
"bar": "cba"
}
}`)

schema, err := aspects.ParseSchema(schemaStr)
c.Assert(err, IsNil)

err = schema.Validate(input)
c.Assert(err, ErrorMatches, `map contains unexpected key "bar"`)
}
func (*schemaSuite) TestMapWithKeysStringConstraintHappy(c *C) {
schemaStr := []byte(`{
"schema": {
Expand Down Expand Up @@ -241,12 +265,8 @@ func (*schemaSuite) TestMapSchemaMetConstraintsWithMissingEntry(c *C) {
}
}`)

// bar is in the schema but not the input and baz is the opposite (both aren't errors)
input := []byte(`{
"foo": "oof",
"baz": {
"a": "b"
}
"foo": "oof"
}`)

schema, err := aspects.ParseSchema(schemaStr)
Expand All @@ -268,8 +288,7 @@ func (*schemaSuite) TestMapSchemaUnmetConstraint(c *C) {
"foo": "oof",
"bar": {
"a": "b"
},
"baz": "zab"
}
}`)

schema, err := aspects.ParseSchema(schemaStr)
Expand Down Expand Up @@ -769,7 +788,6 @@ func (*schemaSuite) TestMapBasedUserDefinedTypeHappy(c *C) {
"snaps": {
"core20": {
"name": "core20",
"version": "20230503",
"status": "active"
},
"snapd": {
Expand Down

0 comments on commit cc790fb

Please sign in to comment.