Skip to content

Commit c2f815c

Browse files
committed
schema: Use Validators map and prepare to extend beyond JSON Schema
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. In situations where you don't know the blob digest, the new DigestByte will help you calculate it (for a byte array). 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. [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 <[email protected]>
1 parent a5ecf31 commit c2f815c

File tree

8 files changed

+317
-108
lines changed

8 files changed

+317
-108
lines changed

schema/config_test.go

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ import (
1919
"testing"
2020

2121
"github.com/opencontainers/image-spec/schema"
22+
"github.com/opencontainers/image-spec/specs-go/v1"
2223
)
2324

2425
func TestConfig(t *testing.T) {
@@ -155,9 +156,19 @@ func TestConfig(t *testing.T) {
155156
fail: false,
156157
},
157158
} {
158-
r := strings.NewReader(tt.config)
159-
err := schema.MediaTypeImageConfig.Validate(r)
159+
configBytes := []byte(tt.config)
160+
digest, err := schema.DigestByte(configBytes, "sha256")
161+
if err != nil {
162+
t.Fatal(err)
163+
}
160164

165+
reader := strings.NewReader(tt.config)
166+
descriptor := v1.Descriptor{
167+
MediaType: v1.MediaTypeImageConfig,
168+
Digest: digest,
169+
Size: int64(len(configBytes)),
170+
}
171+
err = schema.Validate(reader, &descriptor, true)
161172
if got := err != nil; tt.fail != got {
162173
t.Errorf("test %d: expected validation failure %t but got %t, err %v", i, tt.fail, got, err)
163174
}

schema/descriptor.go

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
// Copyright 2016 The Linux Foundation
2+
//
3+
// Licensed under the Apache License, Version 2.0 (the "License");
4+
// you may not use this file except in compliance with the License.
5+
// You may obtain a copy of the License at
6+
//
7+
// http://www.apache.org/licenses/LICENSE-2.0
8+
//
9+
// Unless required by applicable law or agreed to in writing, software
10+
// distributed under the License is distributed on an "AS IS" BASIS,
11+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
// See the License for the specific language governing permissions and
13+
// limitations under the License.
14+
15+
package schema
16+
17+
import (
18+
"crypto/sha256"
19+
"encoding/hex"
20+
"fmt"
21+
"hash"
22+
)
23+
24+
// DigestByte computes the digest of a blob using the requested
25+
// algorithm.
26+
func DigestByte(data []byte, algorithm string) (digest string, err error) {
27+
var hasher hash.Hash
28+
switch algorithm {
29+
case "sha256":
30+
hasher = sha256.New()
31+
default:
32+
return "", fmt.Errorf("unrecognized algorithm: %q", algorithm)
33+
}
34+
35+
_, err = hasher.Write(data)
36+
if err != nil {
37+
return "", err
38+
}
39+
40+
hashBytes := hasher.Sum(nil)
41+
hashHex := hex.EncodeToString(hashBytes[:])
42+
return fmt.Sprintf("%s:%s", algorithm, hashHex), nil
43+
}

schema/manifest.go

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
// Copyright 2016 The Linux Foundation
2+
//
3+
// Licensed under the Apache License, Version 2.0 (the "License");
4+
// you may not use this file except in compliance with the License.
5+
// You may obtain a copy of the License at
6+
//
7+
// http://www.apache.org/licenses/LICENSE-2.0
8+
//
9+
// Unless required by applicable law or agreed to in writing, software
10+
// distributed under the License is distributed on an "AS IS" BASIS,
11+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
// See the License for the specific language governing permissions and
13+
// limitations under the License.
14+
15+
package schema
16+
17+
import (
18+
"bytes"
19+
"encoding/json"
20+
"fmt"
21+
"io"
22+
"io/ioutil"
23+
24+
"github.com/opencontainers/image-spec/specs-go/v1"
25+
"github.com/pkg/errors"
26+
)
27+
28+
// ValidateManifest validates the given CAS blob as
29+
// application/vnd.oci.image.manifest.v1+json. Calls
30+
// ValidateJSONSchema as well.
31+
func ValidateManifest(blob io.Reader, descriptor *v1.Descriptor, strict bool) (err error) {
32+
if descriptor.MediaType != v1.MediaTypeImageManifest {
33+
return fmt.Errorf("unexpected descriptor media type: %q", descriptor.MediaType)
34+
}
35+
36+
buffer, err := ioutil.ReadAll(blob)
37+
if err != nil {
38+
return errors.Wrapf(err, "unable to read %s", descriptor.Digest)
39+
}
40+
41+
err = ValidateJSONSchema(bytes.NewReader(buffer), descriptor, strict)
42+
if err != nil {
43+
return err
44+
}
45+
46+
header := v1.Manifest{}
47+
err = json.Unmarshal(buffer, &header)
48+
if err != nil {
49+
return errors.Wrap(err, "manifest format mismatch")
50+
}
51+
52+
if header.Config.MediaType != v1.MediaTypeImageConfig {
53+
error := fmt.Errorf("warning: config %s has an unknown media type: %s\n", header.Config.Digest, header.Config.MediaType)
54+
if strict {
55+
return error
56+
} else {
57+
fmt.Println(error)
58+
}
59+
}
60+
61+
for _, layer := range header.Layers {
62+
if layer.MediaType != v1.MediaTypeImageLayer &&
63+
layer.MediaType != v1.MediaTypeImageLayerNonDistributable {
64+
error := fmt.Errorf("warning: layer %s has an unknown media type: %s\n", layer.Digest, layer.MediaType)
65+
if strict {
66+
return error
67+
} else {
68+
fmt.Println(error)
69+
}
70+
}
71+
}
72+
73+
return nil
74+
}

schema/manifest_backwards_compatibility_test.go

Lines changed: 24 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,6 @@
1515
package schema_test
1616

1717
import (
18-
"crypto/sha256"
19-
"encoding/hex"
20-
"fmt"
2118
"strings"
2219
"testing"
2320

@@ -110,16 +107,14 @@ func TestBackwardsCompatibilityManifestList(t *testing.T) {
110107
fail: false,
111108
},
112109
} {
113-
sum := sha256.Sum256([]byte(tt.manifest))
114-
got := fmt.Sprintf("sha256:%s", hex.EncodeToString(sum[:]))
115-
if tt.digest != got {
116-
t.Errorf("test %d: expected digest %s but got %s", i, tt.digest, got)
117-
}
118-
119110
manifest := convertFormats(tt.manifest)
120-
r := strings.NewReader(manifest)
121-
err := schema.MediaTypeManifestList.Validate(r)
122-
111+
reader := strings.NewReader(manifest)
112+
descriptor := v1.Descriptor{
113+
MediaType: v1.MediaTypeImageManifestList,
114+
Digest: tt.digest,
115+
Size: int64(len(manifest)),
116+
}
117+
err := schema.Validate(reader, &descriptor, true)
123118
if got := err != nil; tt.fail != got {
124119
t.Errorf("test %d: expected validation failure %t but got %t, err %v", i, tt.fail, got, err)
125120
}
@@ -130,6 +125,7 @@ func TestBackwardsCompatibilityManifest(t *testing.T) {
130125
for i, tt := range []struct {
131126
manifest string
132127
digest string
128+
strict bool
133129
fail bool
134130
}{
135131
// manifest pulled from docker hub using hash value
@@ -170,19 +166,18 @@ func TestBackwardsCompatibilityManifest(t *testing.T) {
170166
}
171167
]
172168
}`,
173-
fail: false,
169+
strict: false, // unrecognized config media type application/octet-stream
170+
fail: false,
174171
},
175172
} {
176-
sum := sha256.Sum256([]byte(tt.manifest))
177-
got := fmt.Sprintf("sha256:%s", hex.EncodeToString(sum[:]))
178-
if tt.digest != got {
179-
t.Errorf("test %d: expected digest %s but got %s", i, tt.digest, got)
180-
}
181-
182173
manifest := convertFormats(tt.manifest)
183-
r := strings.NewReader(manifest)
184-
err := schema.MediaTypeManifest.Validate(r)
185-
174+
reader := strings.NewReader(manifest)
175+
descriptor := v1.Descriptor{
176+
MediaType: v1.MediaTypeImageManifest,
177+
Digest: tt.digest,
178+
Size: int64(len(manifest)),
179+
}
180+
err := schema.Validate(reader, &descriptor, tt.strict)
186181
if got := err != nil; tt.fail != got {
187182
t.Errorf("test %d: expected validation failure %t but got %t, err %v", i, tt.fail, got, err)
188183
}
@@ -213,16 +208,14 @@ func TestBackwardsCompatibilityConfig(t *testing.T) {
213208
fail: false,
214209
},
215210
} {
216-
sum := sha256.Sum256([]byte(tt.manifest))
217-
got := fmt.Sprintf("sha256:%s", hex.EncodeToString(sum[:]))
218-
if tt.digest != got {
219-
t.Errorf("test %d: expected digest %s but got %s", i, tt.digest, got)
220-
}
221-
222211
manifest := convertFormats(tt.manifest)
223-
r := strings.NewReader(manifest)
224-
err := schema.MediaTypeImageConfig.Validate(r)
225-
212+
reader := strings.NewReader(manifest)
213+
descriptor := v1.Descriptor{
214+
MediaType: v1.MediaTypeImageConfig,
215+
Digest: tt.digest,
216+
Size: int64(len(manifest)),
217+
}
218+
err := schema.Validate(reader, &descriptor, true)
226219
if got := err != nil; tt.fail != got {
227220
t.Errorf("test %d: expected validation failure %t but got %t, err %v", i, tt.fail, got, err)
228221
}

schema/manifest_test.go

Lines changed: 70 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -19,11 +19,13 @@ import (
1919
"testing"
2020

2121
"github.com/opencontainers/image-spec/schema"
22+
"github.com/opencontainers/image-spec/specs-go/v1"
2223
)
2324

2425
func TestManifest(t *testing.T) {
2526
for i, tt := range []struct {
2627
manifest string
28+
strict bool
2729
fail bool
2830
}{
2931
// expected failure: mediaType does not match pattern
@@ -34,7 +36,8 @@ func TestManifest(t *testing.T) {
3436
"mediaType": "invalid"
3537
}
3638
`,
37-
fail: true,
39+
strict: true,
40+
fail: true,
3841
},
3942

4043
// expected failure: config.size is a string, expected integer
@@ -51,7 +54,8 @@ func TestManifest(t *testing.T) {
5154
"layers": []
5255
}
5356
`,
54-
fail: true,
57+
strict: true,
58+
fail: true,
5559
},
5660

5761
// expected failure: layers.size is string, expected integer
@@ -74,7 +78,56 @@ func TestManifest(t *testing.T) {
7478
]
7579
}
7680
`,
77-
fail: true,
81+
strict: true,
82+
fail: true,
83+
},
84+
85+
// expected failure: unrecognized layer media type and strict is true
86+
{
87+
manifest: `
88+
{
89+
"schemaVersion": 2,
90+
"mediaType": "application/vnd.oci.image.manifest.v1+json",
91+
"config": {
92+
"mediaType": "application/vnd.oci.image.config.v1+json",
93+
"size": 1470,
94+
"digest": "sha256:c86f7763873b6c0aae22d963bab59b4f5debbed6685761b5951584f6efb0633b"
95+
},
96+
"layers": [
97+
{
98+
"mediaType": "application/vnd.other.layer",
99+
"size": "675598",
100+
"digest": "sha256:c86f7763873b6c0aae22d963bab59b4f5debbed6685761b5951584f6efb0633b"
101+
}
102+
]
103+
}
104+
`,
105+
strict: true,
106+
fail: true,
107+
},
108+
109+
// expected success: unrecognized layer media type, but strict is false
110+
{
111+
manifest: `
112+
{
113+
"schemaVersion": 2,
114+
"mediaType": "application/vnd.oci.image.manifest.v1+json",
115+
"config": {
116+
"mediaType": "application/vnd.oci.image.config.v1+json",
117+
"size": 1470,
118+
"digest": "sha256:c86f7763873b6c0aae22d963bab59b4f5debbed6685761b5951584f6efb0633b"
119+
},
120+
"layers": [
121+
{
122+
"mediaType": "application/vnd.other.layer",
123+
"size": "675598",
124+
"digest": "sha256:c86f7763873b6c0aae22d963bab59b4f5debbed6685761b5951584f6efb0633b"
125+
}
126+
]
127+
}
128+
`,
129+
strict: false,
130+
fail: true,
78131
},
79132

80133
// valid manifest
@@ -111,12 +164,23 @@ func TestManifest(t *testing.T) {
111164
}
112165
}
113166
`,
114-
fail: false,
167+
strict: true,
168+
fail: false,
115169
},
116170
} {
117-
r := strings.NewReader(tt.manifest)
118-
err := schema.MediaTypeManifest.Validate(r)
171+
manifestBytes := []byte(tt.manifest)
172+
digest, err := schema.DigestByte(manifestBytes, "sha256")
173+
if err != nil {
174+
t.Fatal(err)
175+
}
119176

177+
reader := strings.NewReader(tt.manifest)
178+
descriptor := v1.Descriptor{
179+
MediaType: v1.MediaTypeImageManifest,
180+
Digest: digest,
181+
Size: int64(len(manifestBytes)),
182+
}
183+
err = schema.Validate(reader, &descriptor, tt.strict)
120184
if got := err != nil; tt.fail != got {
121185
t.Errorf("test %d: expected validation failure %t but got %t, err %v", i, tt.fail, got, err)
122186
}

schema/schema.go

Lines changed: 6 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -20,26 +20,17 @@ import (
2020
"github.com/opencontainers/image-spec/specs-go/v1"
2121
)
2222

23-
// Media types for the OCI image formats
24-
const (
25-
MediaTypeDescriptor Validator = v1.MediaTypeDescriptor
26-
MediaTypeManifest Validator = v1.MediaTypeImageManifest
27-
MediaTypeManifestList Validator = v1.MediaTypeImageManifestList
28-
MediaTypeImageConfig Validator = v1.MediaTypeImageConfig
29-
MediaTypeImageLayer unimplemented = v1.MediaTypeImageLayer
30-
)
31-
3223
var (
3324
// fs stores the embedded http.FileSystem
3425
// having the OCI JSON schema files in root "/".
3526
fs = _escFS(false)
3627

37-
// specs maps OCI schema media types to schema files.
38-
specs = map[Validator]string{
39-
MediaTypeDescriptor: "content-descriptor.json",
40-
MediaTypeManifest: "image-manifest-schema.json",
41-
MediaTypeManifestList: "manifest-list-schema.json",
42-
MediaTypeImageConfig: "config-schema.json",
28+
// Schemas maps OCI media types to JSON Schema files.
29+
Schemas = map[string]string{
30+
v1.MediaTypeDescriptor: "content-descriptor.json",
31+
v1.MediaTypeImageManifest: "image-manifest-schema.json",
32+
v1.MediaTypeImageManifestList: "manifest-list-schema.json",
33+
v1.MediaTypeImageConfig: "config-schema.json",
4334
}
4435
)
4536

0 commit comments

Comments
 (0)