Skip to content

Commit

Permalink
schema: Use Validators map and prepare to extend beyond JSON Schema
Browse files Browse the repository at this point in the history
With image-tools split off into its own repository, the plan seems to
be to keep all intra-blob JSON validation in this repository and to
move all other validation (e.g. for layers or for walking Merkle
trees) in image-tools [1].  All the non-validation logic currently in
image/ is moving into image-tools as well [2].

Some requirements (e.g. multi-parameter checks like allowed OS/arch
pairs [3]) are difficult to handle in JSON Schema but easy to handle
in Go.  And callers won't care if we're using JSON Schema or not; they
just want to know if their blob is valid.

This commit restructures intra-blob validation to ease the path going
forward (although it doesn't actually change the current validation
significantly).  The old method:

  func (v Validator) Validate(src io.Reader) error

is now a new Validator type:

  type Validator(blob io.Reader, descriptor *v1.Descriptor, strict bool) (err error)

and instead of instantiating an old Validator instance:

  schema.MediaTypeImageConfig.Validate(reader)

there's a Validators registry mapping from the media type strings to
the appropriate Validator instance (which may or may not use JSON
Schema under the hood).  And there's a Validate function (with the
same Validator interface) that looks up the appropriate entry in
Validators for you so you have:

  schema.Validate(reader, descriptor, true)

By using a Validators map, we make it easy for library consumers to
register (or override) intra-blob validators for a particular type.
Locations that call Validate(...) will automatically pick up the new
validators without needing local changes.

All of the old validation was based on JSON Schema, so currently all
Validators values are ValidateJSONSchema.  As the schema package grows
non-JSON-Schema validation, entries will start to look like:

  var Validators = map[string]Validator{
    v1.MediaTypeImageConfig: ValidateConfig,
    ...
  }

although ValidateConfig will probably use ValidateJSONSchema
internally.

By passing through a descriptor, we get a chance to validate the
digest and size (which we were not doing before).  Digest and size
validation for a byte array are also exposed directly (as
ValidateByteDigest and ValidateByteSize) for use in validators that
are not based on ValidateJSONSchema.  Access to the digest also gives
us a way to print specific error messages on failures.

There is also a new 'strict' parameter to distinguish between
compliant images (which should always pass when strict is false) and
images that only use features which the spec requires implementations
to support (which should only pass if strict is true).  The current
JSON Schemas are not strict, but the config/layer media type checks in
ValidateManifest exercise this distinction.

Also use go-digest for local hashing now that we're vendoring it.

[1]: http://ircbot.wl.linuxfoundation.org/meetings/opencontainers/2016/opencontainers.2016-10-12-21.01.log.html#l-71
[2]: #337
[3]: https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.5.5
[4]: #341

Signed-off-by: W. Trevor King <wking@tremily.us>
  • Loading branch information
wking committed Jan 22, 2017
1 parent d1c7054 commit f2b9500
Show file tree
Hide file tree
Showing 7 changed files with 281 additions and 115 deletions.
13 changes: 10 additions & 3 deletions schema/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,9 @@ import (
"strings"
"testing"

"github.com/opencontainers/go-digest"
"github.com/opencontainers/image-spec/schema"
"github.com/opencontainers/image-spec/specs-go/v1"
)

func TestConfig(t *testing.T) {
Expand Down Expand Up @@ -210,9 +212,14 @@ func TestConfig(t *testing.T) {
fail: false,
},
} {
r := strings.NewReader(tt.config)
err := schema.MediaTypeImageConfig.Validate(r)

configBytes := []byte(tt.config)
reader := strings.NewReader(tt.config)
descriptor := v1.Descriptor{
MediaType: v1.MediaTypeImageConfig,
Digest: digest.FromBytes(configBytes).String(),
Size: int64(len(configBytes)),
}
err := schema.Validate(reader, &descriptor, true)
if got := err != nil; tt.fail != got {
t.Errorf("test %d: expected validation failure %t but got %t, err %v", i, tt.fail, got, err)
}
Expand Down
72 changes: 72 additions & 0 deletions schema/manifest.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
// Copyright 2016 The Linux Foundation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package schema

import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"

"github.com/opencontainers/image-spec/specs-go/v1"
"github.com/pkg/errors"
)

// ValidateManifest validates the given CAS blob as
// application/vnd.oci.image.manifest.v1+json. Calls
// ValidateJSONSchema as well.
func ValidateManifest(blob io.Reader, descriptor *v1.Descriptor, strict bool) (err error) {
if descriptor.MediaType != v1.MediaTypeImageManifest {
return fmt.Errorf("unexpected descriptor media type: %q", descriptor.MediaType)
}

buffer, err := ioutil.ReadAll(blob)
if err != nil {
return errors.Wrapf(err, "unable to read %s", descriptor.Digest)
}

err = ValidateJSONSchema(bytes.NewReader(buffer), descriptor, strict)
if err != nil {
return err
}

header := v1.Manifest{}
err = json.Unmarshal(buffer, &header)
if err != nil {
return errors.Wrap(err, "manifest format mismatch")
}

if header.Config.MediaType != v1.MediaTypeImageConfig {
error := fmt.Errorf("warning: config %s has an unknown media type: %s\n", header.Config.Digest, header.Config.MediaType)
if strict {
return error
}
fmt.Println(error)
}

for _, layer := range header.Layers {
if layer.MediaType != v1.MediaTypeImageLayer &&
layer.MediaType != v1.MediaTypeImageLayerNonDistributable {
error := fmt.Errorf("warning: layer %s has an unknown media type: %s\n", layer.Digest, layer.MediaType)
if strict {
return error
}
fmt.Println(error)
}
}

return nil
}
77 changes: 42 additions & 35 deletions schema/manifest_backwards_compatibility_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,11 @@
package schema_test

import (
"crypto/sha256"
"encoding/hex"
"fmt"
"bytes"
"strings"
"testing"

"github.com/opencontainers/go-digest"
"github.com/opencontainers/image-spec/schema"
"github.com/opencontainers/image-spec/specs-go/v1"
)
Expand All @@ -45,13 +44,13 @@ func convertFormats(input string) string {

func TestBackwardsCompatibilityManifestList(t *testing.T) {
for i, tt := range []struct {
manifest string
digest string
fail bool
manifestList string
digest string
fail bool
}{
{
digest: "sha256:219f4b61132fe9d09b0ec5c15517be2ca712e4744b0e0cc3be71295b35b2a467",
manifest: `{
manifestList: `{
"schemaVersion": 2,
"mediaType": "application/vnd.docker.distribution.manifest.list.v2+json",
"manifests": [
Expand Down Expand Up @@ -110,16 +109,18 @@ func TestBackwardsCompatibilityManifestList(t *testing.T) {
fail: false,
},
} {
sum := sha256.Sum256([]byte(tt.manifest))
got := fmt.Sprintf("sha256:%s", hex.EncodeToString(sum[:]))
if tt.digest != got {
t.Errorf("test %d: expected digest %s but got %s", i, tt.digest, got)
err := schema.ValidateByteDigest([]byte(tt.manifestList), &v1.Descriptor{Digest: tt.digest})
if err != nil {
t.Fatal(err)
}

manifest := convertFormats(tt.manifest)
r := strings.NewReader(manifest)
err := schema.MediaTypeManifestList.Validate(r)

manifestList := []byte(convertFormats(tt.manifestList))
reader := bytes.NewReader(manifestList)
descriptor := v1.Descriptor{
MediaType: v1.MediaTypeImageManifestList,
Digest: digest.FromBytes(manifestList).String(),
Size: int64(len(manifestList)),
}
err = schema.Validate(reader, &descriptor, true)
if got := err != nil; tt.fail != got {
t.Errorf("test %d: expected validation failure %t but got %t, err %v", i, tt.fail, got, err)
}
Expand All @@ -130,6 +131,7 @@ func TestBackwardsCompatibilityManifest(t *testing.T) {
for i, tt := range []struct {
manifest string
digest string
strict bool
fail bool
}{
// manifest pulled from docker hub using hash value
Expand Down Expand Up @@ -170,19 +172,22 @@ func TestBackwardsCompatibilityManifest(t *testing.T) {
}
]
}`,
fail: false,
strict: false, // unrecognized config media type application/octet-stream
fail: false,
},
} {
sum := sha256.Sum256([]byte(tt.manifest))
got := fmt.Sprintf("sha256:%s", hex.EncodeToString(sum[:]))
if tt.digest != got {
t.Errorf("test %d: expected digest %s but got %s", i, tt.digest, got)
err := schema.ValidateByteDigest([]byte(tt.manifest), &v1.Descriptor{Digest: tt.digest})
if err != nil {
t.Fatal(err)
}

manifest := convertFormats(tt.manifest)
r := strings.NewReader(manifest)
err := schema.MediaTypeManifest.Validate(r)

manifest := []byte(convertFormats(tt.manifest))
reader := bytes.NewReader(manifest)
descriptor := v1.Descriptor{
MediaType: v1.MediaTypeImageManifest,
Digest: digest.FromBytes(manifest).String(),
Size: int64(len(manifest)),
}
err = schema.Validate(reader, &descriptor, tt.strict)
if got := err != nil; tt.fail != got {
t.Errorf("test %d: expected validation failure %t but got %t, err %v", i, tt.fail, got, err)
}
Expand Down Expand Up @@ -213,16 +218,18 @@ func TestBackwardsCompatibilityConfig(t *testing.T) {
fail: false,
},
} {
sum := sha256.Sum256([]byte(tt.config))
got := fmt.Sprintf("sha256:%s", hex.EncodeToString(sum[:]))
if tt.digest != got {
t.Errorf("test %d: expected digest %s but got %s", i, tt.digest, got)
err := schema.ValidateByteDigest([]byte(tt.config), &v1.Descriptor{Digest: tt.digest})
if err != nil {
t.Fatal(err)
}

config := convertFormats(tt.config)
r := strings.NewReader(config)
err := schema.MediaTypeImageConfig.Validate(r)

config := []byte(convertFormats(tt.config))
reader := bytes.NewReader(config)
descriptor := v1.Descriptor{
MediaType: v1.MediaTypeImageConfig,
Digest: digest.FromBytes(config).String(),
Size: int64(len(config)),
}
err = schema.Validate(reader, &descriptor, true)
if got := err != nil; tt.fail != got {
t.Errorf("test %d: expected validation failure %t but got %t, err %v", i, tt.fail, got, err)
}
Expand Down
74 changes: 67 additions & 7 deletions schema/manifest_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,15 @@ import (
"strings"
"testing"

"github.com/opencontainers/go-digest"
"github.com/opencontainers/image-spec/schema"
"github.com/opencontainers/image-spec/specs-go/v1"
)

func TestManifest(t *testing.T) {
for i, tt := range []struct {
manifest string
strict bool
fail bool
}{
// expected failure: mediaType does not match pattern
Expand All @@ -46,7 +49,8 @@ func TestManifest(t *testing.T) {
]
}
`,
fail: true,
strict: true,
fail: true,
},

// expected failure: config.size is a string, expected integer
Expand All @@ -69,7 +73,8 @@ func TestManifest(t *testing.T) {
]
}
`,
fail: true,
strict: true,
fail: true,
},

// expected failure: layers.size is string, expected integer
Expand All @@ -92,7 +97,56 @@ func TestManifest(t *testing.T) {
]
}
`,
fail: true,
strict: true,
fail: true,
},

// expected failure: unrecognized layer media type and strict is true
{
manifest: `
{
"schemaVersion": 2,
"mediaType": "application/vnd.oci.image.manifest.v1+json",
"config": {
"mediaType": "application/vnd.oci.image.config.v1+json",
"size": 1470,
"digest": "sha256:c86f7763873b6c0aae22d963bab59b4f5debbed6685761b5951584f6efb0633b"
},
"layers": [
{
"mediaType": "application/vnd.other.layer",
"size": "675598",
"digest": "sha256:c86f7763873b6c0aae22d963bab59b4f5debbed6685761b5951584f6efb0633b"
}
]
}
`,
strict: true,
fail: true,
},

// expected success: unrecognized layer media type, but strict is false
{
manifest: `
{
"schemaVersion": 2,
"mediaType": "application/vnd.oci.image.manifest.v1+json",
"config": {
"mediaType": "application/vnd.oci.image.config.v1+json",
"size": 1470,
"digest": "sha256:c86f7763873b6c0aae22d963bab59b4f5debbed6685761b5951584f6efb0633b"
},
"layers": [
{
"mediaType": "application/vnd.other.layer",
"size": "675598",
"digest": "sha256:c86f7763873b6c0aae22d963bab59b4f5debbed6685761b5951584f6efb0633b"
}
]
}
`,
strict: false,
fail: true,
},

// valid manifest with optional fields
Expand Down Expand Up @@ -129,7 +183,8 @@ func TestManifest(t *testing.T) {
}
}
`,
fail: false,
strict: true,
fail: false,
},

// valid manifest with only required fields
Expand Down Expand Up @@ -182,9 +237,14 @@ func TestManifest(t *testing.T) {
fail: true,
},
} {
r := strings.NewReader(tt.manifest)
err := schema.MediaTypeManifest.Validate(r)

manifestBytes := []byte(tt.manifest)
reader := strings.NewReader(tt.manifest)
descriptor := v1.Descriptor{
MediaType: v1.MediaTypeImageManifest,
Digest: digest.FromBytes(manifestBytes).String(),
Size: int64(len(manifestBytes)),
}
err := schema.Validate(reader, &descriptor, tt.strict)
if got := err != nil; tt.fail != got {
t.Errorf("test %d: expected validation failure %t but got %t, err %v", i, tt.fail, got, err)
}
Expand Down
21 changes: 6 additions & 15 deletions schema/schema.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,26 +20,17 @@ import (
"github.com/opencontainers/image-spec/specs-go/v1"
)

// Media types for the OCI image formats
const (
MediaTypeDescriptor Validator = v1.MediaTypeDescriptor
MediaTypeManifest Validator = v1.MediaTypeImageManifest
MediaTypeManifestList Validator = v1.MediaTypeImageManifestList
MediaTypeImageConfig Validator = v1.MediaTypeImageConfig
MediaTypeImageLayer unimplemented = v1.MediaTypeImageLayer
)

var (
// fs stores the embedded http.FileSystem
// having the OCI JSON schema files in root "/".
fs = _escFS(false)

// specs maps OCI schema media types to schema files.
specs = map[Validator]string{
MediaTypeDescriptor: "content-descriptor.json",
MediaTypeManifest: "image-manifest-schema.json",
MediaTypeManifestList: "manifest-list-schema.json",
MediaTypeImageConfig: "config-schema.json",
// Schemas maps OCI media types to JSON Schema files.
Schemas = map[string]string{
v1.MediaTypeDescriptor: "content-descriptor.json",
v1.MediaTypeImageManifest: "image-manifest-schema.json",
v1.MediaTypeImageManifestList: "manifest-list-schema.json",
v1.MediaTypeImageConfig: "config-schema.json",
}
)

Expand Down
Loading

0 comments on commit f2b9500

Please sign in to comment.