From cc790fb7cfd77d9838818f02e82bbb7893681aa5 Mon Sep 17 00:00:00 2001 From: Miguel Pires Date: Mon, 16 Oct 2023 13:30:24 +0100 Subject: [PATCH] aspects: map values cannot contain unexpected entries (#13286) Signed-off-by: Miguel Pires --- aspects/schema.go | 8 ++++++++ aspects/schema_test.go | 34 ++++++++++++++++++++++++++-------- 2 files changed, 34 insertions(+), 8 deletions(-) diff --git a/aspects/schema.go b/aspects/schema.go index ff508396223..26df25984fa 100644 --- a/aspects/schema.go +++ b/aspects/schema.go @@ -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 diff --git a/aspects/schema_test.go b/aspects/schema_test.go index de5bfc36907..29edf38853f 100644 --- a/aspects/schema_test.go +++ b/aspects/schema_test.go @@ -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": { @@ -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) @@ -268,8 +288,7 @@ func (*schemaSuite) TestMapSchemaUnmetConstraint(c *C) { "foo": "oof", "bar": { "a": "b" - }, - "baz": "zab" + } }`) schema, err := aspects.ParseSchema(schemaStr) @@ -769,7 +788,6 @@ func (*schemaSuite) TestMapBasedUserDefinedTypeHappy(c *C) { "snaps": { "core20": { "name": "core20", - "version": "20230503", "status": "active" }, "snapd": {