-
Notifications
You must be signed in to change notification settings - Fork 514
/
remote.go
292 lines (258 loc) · 8.93 KB
/
remote.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
//
// Copyright 2021 The Sigstore Authors.
//
// 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 remote
import (
"errors"
"fmt"
"io"
"net/http"
"github.com/google/go-containerregistry/pkg/name"
v1 "github.com/google/go-containerregistry/pkg/v1"
"github.com/google/go-containerregistry/pkg/v1/remote"
"github.com/google/go-containerregistry/pkg/v1/remote/transport"
"github.com/google/go-containerregistry/pkg/v1/types"
payloadsize "github.com/sigstore/cosign/v2/internal/pkg/cosign/payload/size"
ociexperimental "github.com/sigstore/cosign/v2/internal/pkg/oci/remote"
"github.com/sigstore/cosign/v2/pkg/oci"
)
// These enable mocking for unit testing without faking an entire registry.
var (
remoteImage = remote.Image
remoteIndex = remote.Index
remoteGet = remote.Get
remoteWrite = remote.Write
)
// EntityNotFoundError is the error that SignedEntity returns when the
// provided ref does not exist.
type EntityNotFoundError struct {
baseErr error
}
func (e *EntityNotFoundError) Error() string {
return fmt.Sprintf("entity not found in registry, error: %v", e.baseErr)
}
func NewEntityNotFoundError(err error) error {
return &EntityNotFoundError{
baseErr: err,
}
}
// SignedEntity provides access to a remote reference, and its signatures.
// The SignedEntity will be one of SignedImage or SignedImageIndex.
func SignedEntity(ref name.Reference, options ...Option) (oci.SignedEntity, error) {
o := makeOptions(ref.Context(), options...)
got, err := remoteGet(ref, o.ROpt...)
var te *transport.Error
if errors.As(err, &te) && te.StatusCode == http.StatusNotFound {
return nil, NewEntityNotFoundError(err)
} else if err != nil {
return nil, err
}
switch got.MediaType {
case types.OCIImageIndex, types.DockerManifestList:
ii, err := got.ImageIndex()
if err != nil {
return nil, err
}
return &index{
v1Index: ii,
ref: ref.Context().Digest(got.Digest.String()),
opt: o,
}, nil
case types.OCIManifestSchema1, types.DockerManifestSchema2:
i, err := got.Image()
if err != nil {
return nil, err
}
return &image{
Image: i,
opt: o,
}, nil
default:
return nil, fmt.Errorf("unknown mime type: %v", got.MediaType)
}
}
// normalize turns image digests into tags with optional prefix & suffix:
// sha256:d34db33f -> [prefix]sha256-d34db33f[.suffix]
func normalize(h v1.Hash, prefix string, suffix string) string {
return normalizeWithSeparator(h, prefix, suffix, "-")
}
// normalizeWithSeparator turns image digests into tags with optional prefix & suffix:
// sha256:d34db33f -> [prefix]sha256[algorithmSeparator]d34db33f[.suffix]
func normalizeWithSeparator(h v1.Hash, prefix string, suffix string, algorithmSeparator string) string {
if suffix == "" {
return fmt.Sprint(prefix, h.Algorithm, algorithmSeparator, h.Hex)
}
return fmt.Sprint(prefix, h.Algorithm, algorithmSeparator, h.Hex, ".", suffix)
}
// SignatureTag returns the name.Tag that associated signatures with a particular digest.
func SignatureTag(ref name.Reference, opts ...Option) (name.Tag, error) {
o := makeOptions(ref.Context(), opts...)
return suffixTag(ref, o.SignatureSuffix, "-", o)
}
// AttestationTag returns the name.Tag that associated attestations with a particular digest.
func AttestationTag(ref name.Reference, opts ...Option) (name.Tag, error) {
o := makeOptions(ref.Context(), opts...)
return suffixTag(ref, o.AttestationSuffix, "-", o)
}
// SBOMTag returns the name.Tag that associated SBOMs with a particular digest.
func SBOMTag(ref name.Reference, opts ...Option) (name.Tag, error) {
o := makeOptions(ref.Context(), opts...)
return suffixTag(ref, o.SBOMSuffix, "-", o)
}
// DigestTag returns the name.Tag that associated SBOMs with a particular digest.
func DigestTag(ref name.Reference, opts ...Option) (name.Tag, error) {
o := makeOptions(ref.Context(), opts...)
return suffixTag(ref, "", ":", o)
}
// DockerContentDigest fetches the Docker-Content-Digest header for the referenced tag,
// which is required to delete the object in registry API v2.3 and greater.
// See https://github.com/distribution/distribution/blob/main/docs/content/spec/api.md#deleting-an-image
// and https://github.com/distribution/distribution/issues/1579
func DockerContentDigest(ref name.Tag, opts ...Option) (name.Tag, error) {
o := makeOptions(ref.Context(), opts...)
desc, err := remoteGet(ref, o.ROpt...)
if err != nil {
return name.Tag{}, err
}
h := desc.Digest
return o.TargetRepository.Tag(normalizeWithSeparator(h, o.TagPrefix, "", ":")), nil
}
func suffixTag(ref name.Reference, suffix string, algorithmSeparator string, o *options) (name.Tag, error) {
var h v1.Hash
if digest, ok := ref.(name.Digest); ok {
var err error
h, err = v1.NewHash(digest.DigestStr())
if err != nil { // This is effectively impossible.
return name.Tag{}, err
}
} else {
desc, err := remoteGet(ref, o.ROpt...)
if err != nil {
return name.Tag{}, err
}
h = desc.Digest
}
return o.TargetRepository.Tag(normalizeWithSeparator(h, o.TagPrefix, suffix, algorithmSeparator)), nil
}
// signatures is a shared implementation of the oci.Signed* Signatures method.
func signatures(digestable oci.SignedEntity, o *options) (oci.Signatures, error) {
h, err := digestable.Digest()
if err != nil {
return nil, err
}
return Signatures(o.TargetRepository.Tag(normalize(h, o.TagPrefix, o.SignatureSuffix)), o.OriginalOptions...)
}
// attestations is a shared implementation of the oci.Signed* Attestations method.
func attestations(digestable oci.SignedEntity, o *options) (oci.Signatures, error) {
h, err := digestable.Digest()
if err != nil {
return nil, err
}
return Signatures(o.TargetRepository.Tag(normalize(h, o.TagPrefix, o.AttestationSuffix)), o.OriginalOptions...)
}
// attachment is a shared implementation of the oci.Signed* Attachment method.
func attachment(digestable oci.SignedEntity, attName string, o *options) (oci.File, error) {
// Try using OCI 1.1 behavior
if file, err := attachmentExperimentalOCI(digestable, attName, o); err == nil {
return file, nil
}
h, err := digestable.Digest()
if err != nil {
return nil, err
}
img, err := SignedImage(o.TargetRepository.Tag(normalize(h, o.TagPrefix, attName)), o.OriginalOptions...)
if err != nil {
return nil, err
}
ls, err := img.Layers()
if err != nil {
return nil, err
}
if len(ls) != 1 {
return nil, fmt.Errorf("expected exactly one layer in attachment, got %d", len(ls))
}
return &attached{
SignedImage: img,
layer: ls[0],
}, nil
}
type attached struct {
oci.SignedImage
layer v1.Layer
}
var _ oci.File = (*attached)(nil)
// FileMediaType implements oci.File
func (f *attached) FileMediaType() (types.MediaType, error) {
return f.layer.MediaType()
}
// Payload implements oci.File
func (f *attached) Payload() ([]byte, error) {
size, err := f.layer.Size()
if err != nil {
return nil, err
}
err = payloadsize.CheckSize(uint64(size))
if err != nil {
return nil, err
}
// remote layers are believed to be stored
// compressed, but we don't compress attachments
// so use "Compressed" to access the raw byte
// stream.
rc, err := f.layer.Compressed()
if err != nil {
return nil, err
}
defer rc.Close()
return io.ReadAll(rc)
}
// attachmentExperimentalOCI is a shared implementation of the oci.Signed* Attachment method (for OCI 1.1+ behavior).
func attachmentExperimentalOCI(digestable oci.SignedEntity, attName string, o *options) (oci.File, error) {
h, err := digestable.Digest()
if err != nil {
return nil, err
}
d := o.TargetRepository.Digest(h.String())
artifactType := ociexperimental.ArtifactType(attName)
index, err := Referrers(d, artifactType, o.OriginalOptions...)
if err != nil {
return nil, err
}
results := index.Manifests
numResults := len(results)
if numResults == 0 {
return nil, fmt.Errorf("unable to locate reference with artifactType %s", artifactType)
} else if numResults > 1 {
// TODO: if there is more than 1 result.. what does that even mean?
// TODO: use ui.Warn
fmt.Printf("WARNING: there were a total of %d references with artifactType %s\n", numResults, artifactType)
}
// TODO: do this smarter using "created" annotations
lastResult := results[numResults-1]
img, err := SignedImage(o.TargetRepository.Digest(lastResult.Digest.String()), o.OriginalOptions...)
if err != nil {
return nil, err
}
ls, err := img.Layers()
if err != nil {
return nil, err
}
if len(ls) != 1 {
return nil, fmt.Errorf("expected exactly one layer in attachment, got %d", len(ls))
}
return &attached{
SignedImage: img,
layer: ls[0],
}, nil
}