Debian Codegraph @

registry/repository.go

raw
1 // Copyright The Notary Project Authors.
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package registry
15
16 import (
17 "bytes"
18 "context"
19 "encoding/json"
20 "errors"
21 "fmt"
22 "os"
23
24 "github.com/notaryproject/notation-go/registry/internal/artifactspec"
25 ocispec "github.com/opencontainers/image-spec/specs-go/v1"
26 "oras.land/oras-go/v2"
27 "oras.land/oras-go/v2/content"
28 "oras.land/oras-go/v2/content/oci"
29 "oras.land/oras-go/v2/errdef"
30 "oras.land/oras-go/v2/registry"
31 )
32
33 const (
34 maxBlobSizeLimit = 32 * 1024 * 1024 // 32 MiB
35 maxManifestSizeLimit = 4 * 1024 * 1024 // 4 MiB
36 )
37
38 var (
39 // notationEmptyConfigDesc is the descriptor of an empty notation manifest
40 // config
41 // reference: https://github.com/notaryproject/specifications/blob/v1.0.0/specs/signature-specification.md#storage
42 notationEmptyConfigDesc = ocispec.Descriptor{
43 MediaType: ArtifactTypeNotation,
44 Digest: ocispec.DescriptorEmptyJSON.Digest,
45 Size: ocispec.DescriptorEmptyJSON.Size,
46 }
47 // notationEmptyConfigData is the data of an empty notation manifest config
48 notationEmptyConfigData = ocispec.DescriptorEmptyJSON.Data
49 )
50
51 // RepositoryOptions provides user options when creating a Repository
52 // it is kept for future extensibility
53 type RepositoryOptions struct{}
54
55 // repositoryClient implements Repository
56 type repositoryClient struct {
57 oras.GraphTarget
58 RepositoryOptions
59 }
60
61 // NewRepository returns a new Repository.
62 // Known implementations of oras.GraphTarget:
63 // - [remote.Repository](https://pkg.go.dev/oras.land/oras-go/v2/registry/remote#Repository)
64 // - [oci.Store](https://pkg.go.dev/oras.land/oras-go/v2/content/oci#Store)
65 func NewRepository(target oras.GraphTarget) Repository {
66 return &repositoryClient{
67 GraphTarget: target,
68 }
69 }
70
71 // NewRepositoryWithOptions returns a new Repository with user specified
72 // options.
73 func NewRepositoryWithOptions(target oras.GraphTarget, opts RepositoryOptions) Repository {
74 return &repositoryClient{
75 GraphTarget: target,
76 RepositoryOptions: opts,
77 }
78 }
79
80 // NewOCIRepository returns a new Repository with oci.Store as
81 // its oras.GraphTarget. `path` denotes directory path to the target OCI layout.
82 func NewOCIRepository(path string, opts RepositoryOptions) (Repository, error) {
83 fileInfo, err := os.Stat(path)
84 if err != nil {
85 return nil, fmt.Errorf("failed to create OCI store: %w", err)
86 }
87 if !fileInfo.IsDir() {
88 return nil, fmt.Errorf("failed to create OCI store: the input path is not a directory")
89 }
90 ociStore, err := oci.New(path)
91 if err != nil {
92 return nil, fmt.Errorf("failed to create OCI store: %w", err)
93 }
94 return NewRepositoryWithOptions(ociStore, opts), nil
95 }
96
97 // Resolve resolves a reference(tag or digest) to a manifest descriptor
98 func (c *repositoryClient) Resolve(ctx context.Context, reference string) (ocispec.Descriptor, error) {
99 if repo, ok := c.GraphTarget.(registry.Repository); ok {
100 return repo.Manifests().Resolve(ctx, reference)
101 }
102 return c.GraphTarget.Resolve(ctx, reference)
103 }
104
105 // ListSignatures returns signature manifests filtered by fn given the
106 // target artifact's manifest descriptor
107 func (c *repositoryClient) ListSignatures(ctx context.Context, desc ocispec.Descriptor, fn func(signatureManifests []ocispec.Descriptor) error) error {
108 if repo, ok := c.GraphTarget.(registry.ReferrerLister); ok {
109 return repo.Referrers(ctx, desc, ArtifactTypeNotation, fn)
110 }
111
112 signatureManifests, err := signatureReferrers(ctx, c.GraphTarget, desc)
113 if err != nil {
114 return fmt.Errorf("failed to get referrers during ListSignatures due to %w", err)
115 }
116 return fn(signatureManifests)
117 }
118
119 // FetchSignatureBlob returns signature envelope blob and descriptor given
120 // signature manifest descriptor
121 func (c *repositoryClient) FetchSignatureBlob(ctx context.Context, desc ocispec.Descriptor) ([]byte, ocispec.Descriptor, error) {
122 sigBlobDesc, err := c.getSignatureBlobDesc(ctx, desc)
123 if err != nil {
124 return nil, ocispec.Descriptor{}, err
125 }
126 if sigBlobDesc.Size > maxBlobSizeLimit {
127 return nil, ocispec.Descriptor{}, fmt.Errorf("signature blob too large: %d bytes", sigBlobDesc.Size)
128 }
129
130 var fetcher content.Fetcher = c.GraphTarget
131 if repo, ok := c.GraphTarget.(registry.Repository); ok {
132 fetcher = repo.Blobs()
133 }
134 sigBlob, err := content.FetchAll(ctx, fetcher, sigBlobDesc)
135 if err != nil {
136 return nil, ocispec.Descriptor{}, err
137 }
138 return sigBlob, sigBlobDesc, nil
139 }
140
141 // PushSignature creates and uploads an signature manifest along with its
142 // linked signature envelope blob. Upon successful, PushSignature returns
143 // signature envelope blob and manifest descriptors.
144 func (c *repositoryClient) PushSignature(ctx context.Context, mediaType string, blob []byte, subject ocispec.Descriptor, annotations map[string]string) (blobDesc, manifestDesc ocispec.Descriptor, err error) {
145 var pusher content.Pusher = c.GraphTarget
146 if repo, ok := c.GraphTarget.(registry.Repository); ok {
147 pusher = repo.Blobs()
148 }
149 blobDesc, err = oras.PushBytes(ctx, pusher, mediaType, blob)
150 if err != nil {
151 return ocispec.Descriptor{}, ocispec.Descriptor{}, err
152 }
153 manifestDesc, err = c.uploadSignatureManifest(ctx, subject, blobDesc, annotations)
154 if err != nil {
155 return ocispec.Descriptor{}, ocispec.Descriptor{}, err
156 }
157 return blobDesc, manifestDesc, nil
158 }
159
160 // getSignatureBlobDesc returns signature blob descriptor from
161 // signature manifest blobs or layers given signature manifest descriptor
162 func (c *repositoryClient) getSignatureBlobDesc(ctx context.Context, sigManifestDesc ocispec.Descriptor) (ocispec.Descriptor, error) {
163 if sigManifestDesc.MediaType != artifactspec.MediaTypeArtifactManifest && sigManifestDesc.MediaType != ocispec.MediaTypeImageManifest {
164 return ocispec.Descriptor{}, fmt.Errorf("sigManifestDesc.MediaType requires %q or %q, got %q", artifactspec.MediaTypeArtifactManifest, ocispec.MediaTypeImageManifest, sigManifestDesc.MediaType)
165 }
166 if sigManifestDesc.Size > maxManifestSizeLimit {
167 return ocispec.Descriptor{}, fmt.Errorf("signature manifest too large: %d bytes", sigManifestDesc.Size)
168 }
169
170 // get the signature manifest from sigManifestDesc
171 var fetcher content.Fetcher = c.GraphTarget
172 if repo, ok := c.GraphTarget.(registry.Repository); ok {
173 fetcher = repo.Manifests()
174 }
175 manifestJSON, err := content.FetchAll(ctx, fetcher, sigManifestDesc)
176 if err != nil {
177 return ocispec.Descriptor{}, err
178 }
179
180 // get the signature blob descriptor from signature manifest
181 var signatureBlobs []ocispec.Descriptor
182 // OCI image manifest
183 if sigManifestDesc.MediaType == ocispec.MediaTypeImageManifest {
184 var sigManifest ocispec.Manifest
185 if err := json.Unmarshal(manifestJSON, &sigManifest); err != nil {
186 return ocispec.Descriptor{}, err
187 }
188 signatureBlobs = sigManifest.Layers
189 } else { // OCI artifact manifest
190 var sigManifest artifactspec.Artifact
191 if err := json.Unmarshal(manifestJSON, &sigManifest); err != nil {
192 return ocispec.Descriptor{}, err
193 }
194 signatureBlobs = sigManifest.Blobs
195 }
196
197 if len(signatureBlobs) != 1 {
198 return ocispec.Descriptor{}, fmt.Errorf("signature manifest requries exactly one signature envelope blob, got %d", len(signatureBlobs))
199 }
200
201 return signatureBlobs[0], nil
202 }
203
204 // uploadSignatureManifest uploads the signature manifest to the registry
205 func (c *repositoryClient) uploadSignatureManifest(ctx context.Context, subject, blobDesc ocispec.Descriptor, annotations map[string]string) (ocispec.Descriptor, error) {
206 configDesc, err := pushNotationManifestConfig(ctx, c.GraphTarget)
207 if err != nil {
208 return ocispec.Descriptor{}, fmt.Errorf("failed to push notation manifest config: %w", err)
209 }
210
211 opts := oras.PackManifestOptions{
212 Subject: &subject,
213 ManifestAnnotations: annotations,
214 Layers: []ocispec.Descriptor{blobDesc},
215 ConfigDescriptor: &configDesc,
216 }
217
218 return oras.PackManifest(ctx, c.GraphTarget, oras.PackManifestVersion1_1, "", opts)
219 }
220
221 // pushNotationManifestConfig pushes an empty notation manifest config, if it
222 // doesn't exist.
223 //
224 // if the config exists, it returns the descriptor of the config without error.
225 func pushNotationManifestConfig(ctx context.Context, pusher content.Storage) (ocispec.Descriptor, error) {
226 // check if the config exists
227 exists, err := pusher.Exists(ctx, notationEmptyConfigDesc)
228 if err != nil {
229 return ocispec.Descriptor{}, fmt.Errorf("unable to verify existence: %s: %s. Details: %w", notationEmptyConfigDesc.Digest.String(), notationEmptyConfigDesc.MediaType, err)
230 }
231 if exists {
232 return notationEmptyConfigDesc, nil
233 }
234
235 // return nil if the config pushed successfully or it already exists
236 if err := pusher.Push(ctx, notationEmptyConfigDesc, bytes.NewReader(notationEmptyConfigData)); err != nil && !errors.Is(err, errdef.ErrAlreadyExists) {
237 return ocispec.Descriptor{}, fmt.Errorf("unable to push: %s: %s. Details: %w", notationEmptyConfigDesc.Digest.String(), notationEmptyConfigDesc.MediaType, err)
238 }
239 return notationEmptyConfigDesc, nil
240 }
241
242 // signatureReferrers returns referrer nodes of desc in target filtered by
243 // the "application/vnd.cncf.notary.signature" artifact type
244 func signatureReferrers(ctx context.Context, target content.ReadOnlyGraphStorage, desc ocispec.Descriptor) ([]ocispec.Descriptor, error) {
245 var results []ocispec.Descriptor
246 predecessors, err := target.Predecessors(ctx, desc)
247 if err != nil {
248 return nil, err
249 }
250 for _, node := range predecessors {
251 switch node.MediaType {
252 case artifactspec.MediaTypeArtifactManifest:
253 if node.Size > maxManifestSizeLimit {
254 return nil, fmt.Errorf("referrer node too large: %d bytes", node.Size)
255 }
256 fetched, err := content.FetchAll(ctx, target, node)
257 if err != nil {
258 return nil, err
259 }
260 var artifact artifactspec.Artifact
261 if err := json.Unmarshal(fetched, &artifact); err != nil {
262 return nil, err
263 }
264 if artifact.Subject == nil || !content.Equal(*artifact.Subject, desc) {
265 continue
266 }
267 node.ArtifactType = artifact.ArtifactType
268 node.Annotations = artifact.Annotations
269 case ocispec.MediaTypeImageManifest:
270 if node.Size > maxManifestSizeLimit {
271 return nil, fmt.Errorf("referrer node too large: %d bytes", node.Size)
272 }
273 fetched, err := content.FetchAll(ctx, target, node)
274 if err != nil {
275 return nil, err
276 }
277 var image ocispec.Manifest
278 if err := json.Unmarshal(fetched, &image); err != nil {
279 return nil, err
280 }
281 if image.Subject == nil || !content.Equal(*image.Subject, desc) {
282 continue
283 }
284 node.ArtifactType = image.Config.MediaType
285 node.Annotations = image.Annotations
286 default:
287 continue
288 }
289 // only keep nodes of "application/vnd.cncf.notary.signature"
290 if node.ArtifactType == ArtifactTypeNotation {
291 results = append(results, node)
292 }
293 }
294 return results, nil
295 }