Debian Codegraph @

registry/remote/repository.go

raw
1 /*
2 Copyright The ORAS Authors.
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
16 package remote
17
18 import (
19 "bytes"
20 "context"
21 "encoding/json"
22 "errors"
23 "fmt"
24 "io"
25 "mime"
26 "net/http"
27 "net/url"
28 "slices"
29 "strconv"
30 "strings"
31 "sync"
32 "sync/atomic"
33
34 "github.com/opencontainers/go-digest"
35 specs "github.com/opencontainers/image-spec/specs-go"
36 ocispec "github.com/opencontainers/image-spec/specs-go/v1"
37 "oras.land/oras-go/v2/content"
38 "oras.land/oras-go/v2/errdef"
39 "oras.land/oras-go/v2/internal/cas"
40 "oras.land/oras-go/v2/internal/httputil"
41 "oras.land/oras-go/v2/internal/ioutil"
42 "oras.land/oras-go/v2/internal/spec"
43 "oras.land/oras-go/v2/internal/syncutil"
44 "oras.land/oras-go/v2/registry"
45 "oras.land/oras-go/v2/registry/remote/auth"
46 "oras.land/oras-go/v2/registry/remote/errcode"
47 "oras.land/oras-go/v2/registry/remote/internal/errutil"
48 )
49
50 const (
51 // headerDockerContentDigest is the "Docker-Content-Digest" header.
52 // If present on the response, it contains the canonical digest of the
53 // uploaded blob.
54 //
55 // References:
56 // - https://distribution.github.io/distribution/spec/api/#digest-header
57 // - https://github.com/opencontainers/distribution-spec/blob/v1.1.1/spec.md#pull
58 headerDockerContentDigest = "Docker-Content-Digest"
59
60 // headerOCIFiltersApplied is the "OCI-Filters-Applied" header.
61 // If present on the response, it contains a comma-separated list of the
62 // applied filters.
63 //
64 // Reference:
65 // - https://github.com/opencontainers/distribution-spec/blob/v1.1.1/spec.md#listing-referrers
66 headerOCIFiltersApplied = "OCI-Filters-Applied"
67
68 // headerOCISubject is the "OCI-Subject" header.
69 // If present on the response, it contains the digest of the subject,
70 // indicating that Referrers API is supported by the registry.
71 headerOCISubject = "OCI-Subject"
72 )
73
74 // filterTypeArtifactType is the "artifactType" filter applied on the list of
75 // referrers.
76 //
77 // References:
78 // - Latest spec: https://github.com/opencontainers/distribution-spec/blob/v1.1.1/spec.md#listing-referrers
79 // - Compatible spec: https://github.com/opencontainers/distribution-spec/blob/v1.1.0-rc1/spec.md#listing-referrers
80 const filterTypeArtifactType = "artifactType"
81
82 // Client is an interface for a HTTP client.
83 type Client interface {
84 // Do sends an HTTP request and returns an HTTP response.
85 //
86 // Unlike http.RoundTripper, Client can attempt to interpret the response
87 // and handle higher-level protocol details such as redirects and
88 // authentication.
89 //
90 // Like http.RoundTripper, Client should not modify the request, and must
91 // always close the request body.
92 Do(*http.Request) (*http.Response, error)
93 }
94
95 // Repository is an HTTP client to a remote repository.
96 type Repository struct {
97 // Client is the underlying HTTP client used to access the remote registry.
98 // If nil, auth.DefaultClient is used.
99 Client Client
100
101 // Reference references the remote repository.
102 Reference registry.Reference
103
104 // PlainHTTP signals the transport to access the remote repository via HTTP
105 // instead of HTTPS.
106 PlainHTTP bool
107
108 // ManifestMediaTypes is used in `Accept` header for resolving manifests
109 // from references. It is also used in identifying manifests and blobs from
110 // descriptors. If an empty list is present, default manifest media types
111 // are used.
112 ManifestMediaTypes []string
113
114 // TagListPageSize specifies the page size when invoking the tag list API.
115 // If zero, the page size is determined by the remote registry.
116 // Reference: https://distribution.github.io/distribution/spec/api/#tags
117 TagListPageSize int
118
119 // ReferrerListPageSize specifies the page size when invoking the Referrers
120 // API.
121 // If zero, the page size is determined by the remote registry.
122 //
123 // NOTE: Pagination for the Referrers API is not defined in the distribution
124 // spec, so not all registries support it. ReferrerListPageSize may be
125 // ignored if pagination is unsupported by the remote registry.
126 //
127 // Reference: https://github.com/oras-project/oras-go/issues/841
128 ReferrerListPageSize int
129
130 // TagListMaxPages limits the total number of pages fetched during tag
131 // listing, bounding server-driven pagination so a malicious or misbehaving
132 // registry cannot force unbounded requests.
133 // If zero, tag listing is unlimited.
134 TagListMaxPages int
135
136 // ReferrerListMaxPages limits the total number of pages fetched during
137 // referrer listing, bounding server-driven pagination so a malicious or
138 // misbehaving registry cannot force unbounded requests.
139 // If zero, referrer listing is unlimited.
140 ReferrerListMaxPages int
141
142 // MaxMetadataBytes specifies a limit on how many response bytes are allowed
143 // in the server's response to the metadata APIs, such as catalog list, tag
144 // list, and referrers list.
145 // If less than or equal to zero, a default (currently 4MiB) is used.
146 MaxMetadataBytes int64
147
148 // SkipReferrersGC specifies whether to delete the dangling referrers
149 // index when referrers tag schema is utilized.
150 // - If false, the old referrers index will be deleted after the new one
151 // is successfully uploaded.
152 // - If true, the old referrers index is kept.
153 // By default, it is disabled (set to false). See also:
154 // - https://github.com/opencontainers/distribution-spec/blob/v1.1.1/spec.md#referrers-tag-schema
155 // - https://github.com/opencontainers/distribution-spec/blob/v1.1.1/spec.md#pushing-manifests-with-subject
156 // - https://github.com/opencontainers/distribution-spec/blob/v1.1.1/spec.md#deleting-manifests
157 SkipReferrersGC bool
158
159 // HandleWarning handles the warning returned by the remote server.
160 // Callers SHOULD deduplicate warnings from multiple associated responses.
161 //
162 // References:
163 // - https://github.com/opencontainers/distribution-spec/blob/v1.1.1/spec.md#warnings
164 // - https://www.rfc-editor.org/rfc/rfc7234#section-5.5
165 HandleWarning func(warning Warning)
166
167 // NOTE: Must keep fields in sync with clone().
168
169 // referrersState represents that if the repository supports Referrers API.
170 // default: referrersStateUnknown
171 referrersState referrersState
172
173 // referrersPingLock locks the pingReferrers() method and allows only
174 // one go-routine to send the request.
175 referrersPingLock sync.Mutex
176
177 // referrersMergePool provides a way to manage concurrent updates to a
178 // referrers index tagged by referrers tag schema.
179 referrersMergePool syncutil.Pool[syncutil.Merge[referrerChange]]
180 }
181
182 // NewRepository creates a client to the remote repository identified by a
183 // reference.
184 // Example: localhost:5000/hello-world
185 func NewRepository(reference string) (*Repository, error) {
186 ref, err := registry.ParseReference(reference)
187 if err != nil {
188 return nil, err
189 }
190 return &Repository{
191 Reference: ref,
192 }, nil
193 }
194
195 // newRepositoryWithOptions returns a Repository with the given Reference and
196 // RepositoryOptions.
197 //
198 // RepositoryOptions are part of the Registry struct and set its defaults.
199 // RepositoryOptions shares the same struct definition as Repository, which
200 // contains unexported state that must not be copied to multiple Repositories.
201 // To handle this we explicitly copy only the fields that we want to reproduce.
202 func newRepositoryWithOptions(ref registry.Reference, opts *RepositoryOptions) (*Repository, error) {
203 if err := ref.ValidateRepository(); err != nil {
204 return nil, err
205 }
206 repo := (*Repository)(opts).clone()
207 repo.Reference = ref
208 return repo, nil
209 }
210
211 // clone makes a copy of the Repository being careful not to copy non-copyable fields (sync.Mutex and syncutil.Pool types)
212 func (r *Repository) clone() *Repository {
213 return &Repository{
214 Client: r.Client,
215 Reference: r.Reference,
216 PlainHTTP: r.PlainHTTP,
217 ManifestMediaTypes: slices.Clone(r.ManifestMediaTypes),
218 TagListPageSize: r.TagListPageSize,
219 ReferrerListPageSize: r.ReferrerListPageSize,
220 TagListMaxPages: r.TagListMaxPages,
221 ReferrerListMaxPages: r.ReferrerListMaxPages,
222 MaxMetadataBytes: r.MaxMetadataBytes,
223 SkipReferrersGC: r.SkipReferrersGC,
224 HandleWarning: r.HandleWarning,
225 }
226 }
227
228 // SetReferrersCapability indicates the Referrers API capability of the remote
229 // repository. true: capable; false: not capable.
230 //
231 // SetReferrersCapability is valid only when it is called for the first time.
232 // SetReferrersCapability returns ErrReferrersCapabilityAlreadySet if the
233 // Referrers API capability has been already set.
234 // - When the capability is set to true, the Referrers() function will always
235 // request the Referrers API. Reference: https://github.com/opencontainers/distribution-spec/blob/v1.1.1/spec.md#listing-referrers
236 // - When the capability is set to false, the Referrers() function will always
237 // request the Referrers Tag. Reference: https://github.com/opencontainers/distribution-spec/blob/v1.1.1/spec.md#referrers-tag-schema
238 // - When the capability is not set, the Referrers() function will automatically
239 // determine which API to use.
240 func (r *Repository) SetReferrersCapability(capable bool) error {
241 var state referrersState
242 if capable {
243 state = referrersStateSupported
244 } else {
245 state = referrersStateUnsupported
246 }
247 if swapped := atomic.CompareAndSwapInt32(&r.referrersState, referrersStateUnknown, state); !swapped {
248 if fact := r.loadReferrersState(); fact != state {
249 return fmt.Errorf("%w: current capability = %v, new capability = %v",
250 ErrReferrersCapabilityAlreadySet,
251 fact == referrersStateSupported,
252 capable)
253 }
254 }
255 return nil
256 }
257
258 // setReferrersState atomically loads r.referrersState.
259 func (r *Repository) loadReferrersState() referrersState {
260 return atomic.LoadInt32(&r.referrersState)
261 }
262
263 // client returns an HTTP client used to access the remote repository.
264 // A default HTTP client is return if the client is not configured.
265 func (r *Repository) client() Client {
266 if r.Client == nil {
267 return auth.DefaultClient
268 }
269 return r.Client
270 }
271
272 // do sends an HTTP request and returns an HTTP response using the HTTP client
273 // returned by r.client().
274 func (r *Repository) do(req *http.Request) (*http.Response, error) {
275 if r.HandleWarning == nil {
276 return r.client().Do(req)
277 }
278
279 resp, err := r.client().Do(req)
280 if err != nil {
281 return nil, err
282 }
283 handleWarningHeaders(resp.Header.Values(headerWarning), r.HandleWarning)
284 return resp, nil
285 }
286
287 // blobStore detects the blob store for the given descriptor.
288 func (r *Repository) blobStore(desc ocispec.Descriptor) registry.BlobStore {
289 if isManifest(r.ManifestMediaTypes, desc) {
290 return r.Manifests()
291 }
292 return r.Blobs()
293 }
294
295 // Fetch fetches the content identified by the descriptor.
296 func (r *Repository) Fetch(ctx context.Context, target ocispec.Descriptor) (io.ReadCloser, error) {
297 return r.blobStore(target).Fetch(ctx, target)
298 }
299
300 // Push pushes the content, matching the expected descriptor.
301 func (r *Repository) Push(ctx context.Context, expected ocispec.Descriptor, content io.Reader) error {
302 return r.blobStore(expected).Push(ctx, expected, content)
303 }
304
305 // Mount makes the blob with the given digest in fromRepo
306 // available in the repository signified by the receiver.
307 //
308 // This avoids the need to pull content down from fromRepo only to push it to r.
309 //
310 // If the registry does not implement mounting, getContent will be used to get the
311 // content to push. If getContent is nil, the content will be pulled from the source
312 // repository. If getContent returns an error, it will be wrapped inside the error
313 // returned from Mount.
314 func (r *Repository) Mount(ctx context.Context, desc ocispec.Descriptor, fromRepo string, getContent func() (io.ReadCloser, error)) error {
315 return r.Blobs().(registry.Mounter).Mount(ctx, desc, fromRepo, getContent)
316 }
317
318 // Exists returns true if the described content exists.
319 func (r *Repository) Exists(ctx context.Context, target ocispec.Descriptor) (bool, error) {
320 return r.blobStore(target).Exists(ctx, target)
321 }
322
323 // Delete removes the content identified by the descriptor.
324 func (r *Repository) Delete(ctx context.Context, target ocispec.Descriptor) error {
325 return r.blobStore(target).Delete(ctx, target)
326 }
327
328 // Blobs provides access to the blob CAS only, which contains config blobs,
329 // layers, and other generic blobs.
330 func (r *Repository) Blobs() registry.BlobStore {
331 return &blobStore{repo: r}
332 }
333
334 // Manifests provides access to the manifest CAS only.
335 func (r *Repository) Manifests() registry.ManifestStore {
336 return &manifestStore{repo: r}
337 }
338
339 // Resolve resolves a reference to a manifest descriptor.
340 // See also `ManifestMediaTypes`.
341 func (r *Repository) Resolve(ctx context.Context, reference string) (ocispec.Descriptor, error) {
342 return r.Manifests().Resolve(ctx, reference)
343 }
344
345 // Tag tags a manifest descriptor with a reference string.
346 func (r *Repository) Tag(ctx context.Context, desc ocispec.Descriptor, reference string) error {
347 return r.Manifests().Tag(ctx, desc, reference)
348 }
349
350 // PushReference pushes the manifest with a reference tag.
351 func (r *Repository) PushReference(ctx context.Context, expected ocispec.Descriptor, content io.Reader, reference string) error {
352 return r.Manifests().PushReference(ctx, expected, content, reference)
353 }
354
355 // FetchReference fetches the manifest identified by the reference.
356 // The reference can be a tag or digest.
357 func (r *Repository) FetchReference(ctx context.Context, reference string) (ocispec.Descriptor, io.ReadCloser, error) {
358 return r.Manifests().FetchReference(ctx, reference)
359 }
360
361 // ParseReference resolves a tag or a digest reference to a fully qualified
362 // reference from a base reference r.Reference.
363 // Tag, digest, or fully qualified references are accepted as input.
364 //
365 // If reference is a fully qualified reference, then ParseReference parses it
366 // and returns the parsed reference. If the parsed reference does not share
367 // the same base reference with the Repository r, ParseReference returns a
368 // wrapped error ErrInvalidReference.
369 func (r *Repository) ParseReference(reference string) (registry.Reference, error) {
370 ref, err := registry.ParseReference(reference)
371 if err != nil {
372 ref = registry.Reference{
373 Registry: r.Reference.Registry,
374 Repository: r.Reference.Repository,
375 Reference: reference,
376 }
377
378 // reference is not a FQDN
379 if index := strings.IndexByte(reference, '@'); index != -1 {
380 // `@` implies *digest*, so drop the *tag* (irrespective of what it is).
381 ref.Reference = reference[index+1:]
382 err = ref.ValidateReferenceAsDigest()
383 } else {
384 err = ref.ValidateReference()
385 }
386
387 if err != nil {
388 return registry.Reference{}, err
389 }
390 } else if ref.Registry != r.Reference.Registry || ref.Repository != r.Reference.Repository {
391 return registry.Reference{}, fmt.Errorf(
392 "%w: mismatch between received %q and expected %q",
393 errdef.ErrInvalidReference, ref, r.Reference,
394 )
395 }
396
397 if len(ref.Reference) == 0 {
398 return registry.Reference{}, errdef.ErrInvalidReference
399 }
400
401 return ref, nil
402 }
403
404 // Tags lists the tags available in the repository.
405 // See also `TagListPageSize`.
406 // If `last` is NOT empty, the entries in the response start after the
407 // tag specified by `last`. Otherwise, the response starts from the top
408 // of the Tags list.
409 //
410 // References:
411 // - https://github.com/opencontainers/distribution-spec/blob/v1.1.1/spec.md#content-discovery
412 // - https://distribution.github.io/distribution/spec/api/#tags
413 func (r *Repository) Tags(ctx context.Context, last string, fn func(tags []string) error) error {
414 ctx = auth.AppendRepositoryScope(ctx, r.Reference, auth.ActionPull)
415 url := buildRepositoryTagListURL(r.PlainHTTP, r.Reference)
416 var err error
417 for page := 0; err == nil; page++ {
418 if r.TagListMaxPages > 0 && page >= r.TagListMaxPages {
419 return fmt.Errorf("tag listing exceeded %d pages: %w", r.TagListMaxPages, errdef.ErrTooManyPages)
420 }
421 url, err = r.tags(ctx, last, fn, url)
422 // clear `last` for subsequent pages
423 last = ""
424 }
425 if err != errNoLink {
426 return err
427 }
428 return nil
429 }
430
431 // tags returns a single page of tag list with the next link.
432 func (r *Repository) tags(ctx context.Context, last string, fn func(tags []string) error, url string) (string, error) {
433 req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
434 if err != nil {
435 return "", err
436 }
437 if r.TagListPageSize > 0 || last != "" {
438 q := req.URL.Query()
439 if r.TagListPageSize > 0 {
440 q.Set("n", strconv.Itoa(r.TagListPageSize))
441 }
442 if last != "" {
443 q.Set("last", last)
444 }
445 req.URL.RawQuery = q.Encode()
446 }
447 resp, err := r.do(req)
448 if err != nil {
449 return "", err
450 }
451 defer resp.Body.Close()
452
453 if resp.StatusCode != http.StatusOK {
454 return "", errutil.ParseErrorResponse(resp)
455 }
456 var page struct {
457 Tags []string `json:"tags"`
458 }
459 lr := limitReader(resp.Body, r.MaxMetadataBytes)
460 if err := json.NewDecoder(lr).Decode(&page); err != nil {
461 return "", fmt.Errorf("%s %q: failed to decode response: %w", resp.Request.Method, resp.Request.URL, err)
462 }
463 if err := fn(page.Tags); err != nil {
464 return "", err
465 }
466
467 return parseLink(resp)
468 }
469
470 // Predecessors returns the descriptors of image or artifact manifests directly
471 // referencing the given manifest descriptor.
472 // Predecessors internally leverages Referrers.
473 // Reference: https://github.com/opencontainers/distribution-spec/blob/v1.1.1/spec.md#listing-referrers
474 func (r *Repository) Predecessors(ctx context.Context, desc ocispec.Descriptor) ([]ocispec.Descriptor, error) {
475 var res []ocispec.Descriptor
476 if err := r.Referrers(ctx, desc, "", func(referrers []ocispec.Descriptor) error {
477 res = append(res, referrers...)
478 return nil
479 }); err != nil {
480 return nil, err
481 }
482 return res, nil
483 }
484
485 // Referrers lists the descriptors of image or artifact manifests directly
486 // referencing the given manifest descriptor.
487 //
488 // fn is called for each page of the referrers result.
489 // If artifactType is not empty, only referrers of the same artifact type are
490 // fed to fn.
491 //
492 // Reference: https://github.com/opencontainers/distribution-spec/blob/v1.1.1/spec.md#listing-referrers
493 func (r *Repository) Referrers(ctx context.Context, desc ocispec.Descriptor, artifactType string, fn func(referrers []ocispec.Descriptor) error) error {
494 state := r.loadReferrersState()
495 if state == referrersStateUnsupported {
496 // The repository is known to not support Referrers API, fallback to
497 // referrers tag schema.
498 return r.referrersByTagSchema(ctx, desc, artifactType, fn)
499 }
500
501 err := r.referrersByAPI(ctx, desc, artifactType, fn)
502 if state == referrersStateSupported {
503 // The repository is known to support Referrers API, no fallback.
504 return err
505 }
506
507 // The referrers state is unknown.
508 if err != nil {
509 if errors.Is(err, errdef.ErrUnsupported) {
510 // Referrers API is not supported, fallback to referrers tag schema.
511 r.SetReferrersCapability(false)
512 return r.referrersByTagSchema(ctx, desc, artifactType, fn)
513 }
514 return err
515 }
516
517 r.SetReferrersCapability(true)
518 return nil
519 }
520
521 // referrersByAPI lists the descriptors of manifests directly referencing
522 // the given manifest descriptor by requesting Referrers API.
523 // fn is called for the referrers result. If artifactType is not empty,
524 // only referrers of the same artifact type are fed to fn.
525 func (r *Repository) referrersByAPI(ctx context.Context, desc ocispec.Descriptor, artifactType string, fn func(referrers []ocispec.Descriptor) error) error {
526 ref := r.Reference
527 ref.Reference = desc.Digest.String()
528 ctx = auth.AppendRepositoryScope(ctx, ref, auth.ActionPull)
529
530 url := buildReferrersURL(r.PlainHTTP, ref, artifactType)
531 var err error
532 for page := 0; err == nil; page++ {
533 if r.ReferrerListMaxPages > 0 && page >= r.ReferrerListMaxPages {
534 return fmt.Errorf("referrer listing exceeded %d pages: %w", r.ReferrerListMaxPages, errdef.ErrTooManyPages)
535 }
536 url, err = r.referrersPageByAPI(ctx, artifactType, fn, url)
537 }
538 if err == errNoLink {
539 return nil
540 }
541 return err
542 }
543
544 // referrersPageByAPI lists a single page of the descriptors of manifests
545 // directly referencing the given manifest descriptor. fn is called for
546 // a page of referrersPageByAPI result.
547 // If artifactType is not empty, only referrersPageByAPI of the same
548 // artifact type are fed to fn.
549 // referrersPageByAPI returns the link url for the next page.
550 func (r *Repository) referrersPageByAPI(ctx context.Context, artifactType string, fn func(referrers []ocispec.Descriptor) error, url string) (string, error) {
551 req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
552 if err != nil {
553 return "", err
554 }
555 if r.ReferrerListPageSize > 0 {
556 q := req.URL.Query()
557 q.Set("n", strconv.Itoa(r.ReferrerListPageSize))
558 req.URL.RawQuery = q.Encode()
559 }
560
561 resp, err := r.do(req)
562 if err != nil {
563 return "", err
564 }
565 defer resp.Body.Close()
566
567 switch resp.StatusCode {
568 case http.StatusOK:
569 case http.StatusNotFound:
570 if errResp := errutil.ParseErrorResponse(resp); errutil.IsErrorCode(errResp, errcode.ErrorCodeNameUnknown) {
571 // The repository is not found, Referrers API status is unknown
572 return "", errResp
573 }
574 // Referrers API is not supported.
575 return "", fmt.Errorf("failed to query referrers API: %w", errdef.ErrUnsupported)
576 default:
577 return "", errutil.ParseErrorResponse(resp)
578 }
579
580 // also check the content type
581 if ct := resp.Header.Get("Content-Type"); ct != ocispec.MediaTypeImageIndex {
582 return "", fmt.Errorf("unknown content returned (%s), expecting image index: %w", ct, errdef.ErrUnsupported)
583 }
584
585 var index ocispec.Index
586 lr := limitReader(resp.Body, r.MaxMetadataBytes)
587 if err := json.NewDecoder(lr).Decode(&index); err != nil {
588 return "", fmt.Errorf("%s %q: failed to decode response: %w", resp.Request.Method, resp.Request.URL, err)
589 }
590
591 referrers := index.Manifests
592 if artifactType != "" {
593 // check both filters header and filters annotations for compatibility
594 // latest spec for filters header: https://github.com/opencontainers/distribution-spec/blob/v1.1.1/spec.md#listing-referrers
595 // older spec for filters annotations: https://github.com/opencontainers/distribution-spec/blob/v1.1.0-rc1/spec.md#listing-referrers
596 filtersHeader := resp.Header.Get(headerOCIFiltersApplied)
597 filtersAnnotation := index.Annotations[spec.AnnotationReferrersFiltersApplied]
598 if !isReferrersFilterApplied(filtersHeader, filterTypeArtifactType) &&
599 !isReferrersFilterApplied(filtersAnnotation, filterTypeArtifactType) {
600 // perform client side filtering if the filter is not applied on the server side
601 referrers = filterReferrers(referrers, artifactType)
602 }
603 }
604 if len(referrers) > 0 {
605 if err := fn(referrers); err != nil {
606 return "", err
607 }
608 }
609 return parseLink(resp)
610 }
611
612 // referrersByTagSchema lists the descriptors of manifests directly
613 // referencing the given manifest descriptor by requesting referrers tag.
614 // fn is called for the referrers result. If artifactType is not empty,
615 // only referrers of the same artifact type are fed to fn.
616 // reference: https://github.com/opencontainers/distribution-spec/blob/v1.1.1/spec.md#backwards-compatibility
617 func (r *Repository) referrersByTagSchema(ctx context.Context, desc ocispec.Descriptor, artifactType string, fn func(referrers []ocispec.Descriptor) error) error {
618 referrersTag, err := buildReferrersTag(desc)
619 if err != nil {
620 return err
621 }
622 _, referrers, err := r.referrersFromIndex(ctx, referrersTag)
623 if err != nil {
624 if errors.Is(err, errdef.ErrNotFound) {
625 // no referrers to the manifest
626 return nil
627 }
628 return err
629 }
630
631 filtered := filterReferrers(referrers, artifactType)
632 if len(filtered) == 0 {
633 return nil
634 }
635 return fn(filtered)
636 }
637
638 // referrersFromIndex queries the referrers index using the the given referrers
639 // tag. If Succeeded, returns the descriptor of referrers index and the
640 // referrers list.
641 func (r *Repository) referrersFromIndex(ctx context.Context, referrersTag string) (ocispec.Descriptor, []ocispec.Descriptor, error) {
642 desc, rc, err := r.FetchReference(ctx, referrersTag)
643 if err != nil {
644 return ocispec.Descriptor{}, nil, err
645 }
646 defer rc.Close()
647
648 if err := limitSize(desc, r.MaxMetadataBytes); err != nil {
649 return ocispec.Descriptor{}, nil, fmt.Errorf("failed to read referrers index from referrers tag %s: %w", referrersTag, err)
650 }
651 var index ocispec.Index
652 if err := decodeJSON(rc, desc, &index); err != nil {
653 return ocispec.Descriptor{}, nil, fmt.Errorf("failed to decode referrers index from referrers tag %s: %w", referrersTag, err)
654 }
655
656 return desc, index.Manifests, nil
657 }
658
659 // pingReferrers returns true if the Referrers API is available for r.
660 func (r *Repository) pingReferrers(ctx context.Context) (bool, error) {
661 switch r.loadReferrersState() {
662 case referrersStateSupported:
663 return true, nil
664 case referrersStateUnsupported:
665 return false, nil
666 }
667
668 // referrers state is unknown
669 // limit the rate of pinging referrers API
670 r.referrersPingLock.Lock()
671 defer r.referrersPingLock.Unlock()
672
673 switch r.loadReferrersState() {
674 case referrersStateSupported:
675 return true, nil
676 case referrersStateUnsupported:
677 return false, nil
678 }
679
680 ref := r.Reference
681 ref.Reference = zeroDigest
682 ctx = auth.AppendRepositoryScope(ctx, ref, auth.ActionPull)
683
684 url := buildReferrersURL(r.PlainHTTP, ref, "")
685 req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
686 if err != nil {
687 return false, err
688 }
689 resp, err := r.do(req)
690 if err != nil {
691 return false, err
692 }
693 defer resp.Body.Close()
694
695 switch resp.StatusCode {
696 case http.StatusOK:
697 supported := resp.Header.Get("Content-Type") == ocispec.MediaTypeImageIndex
698 r.SetReferrersCapability(supported)
699 return supported, nil
700 case http.StatusNotFound:
701 if err := errutil.ParseErrorResponse(resp); errutil.IsErrorCode(err, errcode.ErrorCodeNameUnknown) {
702 // repository not found
703 return false, err
704 }
705 r.SetReferrersCapability(false)
706 return false, nil
707 default:
708 return false, errutil.ParseErrorResponse(resp)
709 }
710 }
711
712 // delete removes the content identified by the descriptor in the entity "blobs"
713 // or "manifests".
714 func (r *Repository) delete(ctx context.Context, target ocispec.Descriptor, isManifest bool) error {
715 ref := r.Reference
716 ref.Reference = target.Digest.String()
717 ctx = auth.AppendRepositoryScope(ctx, ref, auth.ActionDelete)
718 buildURL := buildRepositoryBlobURL
719 if isManifest {
720 buildURL = buildRepositoryManifestURL
721 }
722 url := buildURL(r.PlainHTTP, ref)
723 req, err := http.NewRequestWithContext(ctx, http.MethodDelete, url, nil)
724 if err != nil {
725 return err
726 }
727
728 resp, err := r.do(req)
729 if err != nil {
730 return err
731 }
732 defer resp.Body.Close()
733
734 switch resp.StatusCode {
735 case http.StatusAccepted:
736 return verifyContentDigest(resp, target.Digest)
737 case http.StatusNotFound:
738 return fmt.Errorf("%s: %w", target.Digest, errdef.ErrNotFound)
739 default:
740 return errutil.ParseErrorResponse(resp)
741 }
742 }
743
744 // blobStore accesses the blob part of the repository.
745 type blobStore struct {
746 repo *Repository
747 }
748
749 // Fetch fetches the content identified by the descriptor.
750 func (s *blobStore) Fetch(ctx context.Context, target ocispec.Descriptor) (rc io.ReadCloser, err error) {
751 ref := s.repo.Reference
752 ref.Reference = target.Digest.String()
753 ctx = auth.AppendRepositoryScope(ctx, ref, auth.ActionPull)
754 url := buildRepositoryBlobURL(s.repo.PlainHTTP, ref)
755 req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
756 if err != nil {
757 return nil, err
758 }
759
760 resp, err := s.repo.do(req)
761 if err != nil {
762 return nil, err
763 }
764 defer func() {
765 if err != nil {
766 resp.Body.Close()
767 }
768 }()
769
770 switch resp.StatusCode {
771 case http.StatusOK:
772 if size := resp.ContentLength; size != -1 && size != target.Size {
773 return nil, fmt.Errorf("%s %q: mismatch Content-Length", resp.Request.Method, resp.Request.URL)
774 }
775 if err := verifyContentDigest(resp, target.Digest); err != nil {
776 return nil, err
777 }
778
779 // check server range request capability.
780 // Docker spec allows range header form of "Range: bytes=<start>-<end>".
781 // However, the remote server may still not RFC 7233 compliant.
782 // Reference: https://distribution.github.io/distribution/spec/api/#blob
783 if rangeUnit := resp.Header.Get("Accept-Ranges"); rangeUnit == "bytes" {
784 return httputil.NewReadSeekCloser(s.repo.client(), req, resp.Body, target.Size), nil
785 }
786 return resp.Body, nil
787 case http.StatusNotFound:
788 return nil, fmt.Errorf("%s: %w", target.Digest, errdef.ErrNotFound)
789 default:
790 return nil, errutil.ParseErrorResponse(resp)
791 }
792 }
793
794 // Mount mounts the given descriptor from fromRepo into s.
795 func (s *blobStore) Mount(ctx context.Context, desc ocispec.Descriptor, fromRepo string, getContent func() (io.ReadCloser, error)) error {
796 // pushing usually requires both pull and push actions.
797 // Reference: https://github.com/distribution/distribution/blob/v2.7.1/registry/handlers/app.go#L921-L930
798 ctx = auth.AppendRepositoryScope(ctx, s.repo.Reference, auth.ActionPull, auth.ActionPush)
799
800 // We also need pull access to the source repo.
801 fromRef := s.repo.Reference
802 fromRef.Repository = fromRepo
803 ctx = auth.AppendRepositoryScope(ctx, fromRef, auth.ActionPull)
804
805 url := buildRepositoryBlobMountURL(s.repo.PlainHTTP, s.repo.Reference, desc.Digest, fromRepo)
806 req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, nil)
807 if err != nil {
808 return err
809 }
810 resp, err := s.repo.do(req)
811 if err != nil {
812 return err
813 }
814 if resp.StatusCode == http.StatusCreated {
815 defer resp.Body.Close()
816 // Check the server seems to be behaving.
817 return verifyContentDigest(resp, desc.Digest)
818 }
819 if resp.StatusCode != http.StatusAccepted {
820 defer resp.Body.Close()
821 return errutil.ParseErrorResponse(resp)
822 }
823 resp.Body.Close()
824 // From the [spec]:
825 //
826 // "If a registry does not support cross-repository mounting
827 // or is unable to mount the requested blob,
828 // it SHOULD return a 202.
829 // This indicates that the upload session has begun
830 // and that the client MAY proceed with the upload."
831 //
832 // So we need to get the content from somewhere in order to
833 // push it. If the caller has provided a getContent function, we
834 // can use that, otherwise pull the content from the source repository.
835 //
836 // [spec]: https://github.com/opencontainers/distribution-spec/blob/v1.1.1/spec.md#mounting-a-blob-from-another-repository
837
838 var r io.ReadCloser
839 if getContent != nil {
840 r, err = getContent()
841 } else {
842 r, err = s.sibling(fromRepo).Fetch(ctx, desc)
843 }
844 if err != nil {
845 return fmt.Errorf("cannot read source blob: %w", err)
846 }
847 defer r.Close()
848 return s.completePushAfterInitialPost(ctx, req, resp, desc, r)
849 }
850
851 // sibling returns a blob store for another repository in the same
852 // registry.
853 func (s *blobStore) sibling(otherRepoName string) *blobStore {
854 otherRepo := s.repo.clone()
855 otherRepo.Reference.Repository = otherRepoName
856 return &blobStore{
857 repo: otherRepo,
858 }
859 }
860
861 // Push pushes the content, matching the expected descriptor.
862 // Existing content is not checked by Push() to minimize the number of out-going
863 // requests.
864 // Push is done by conventional 2-step monolithic upload instead of a single
865 // `POST` request for better overall performance. It also allows early fail on
866 // authentication errors.
867 //
868 // References:
869 // - https://distribution.github.io/distribution/spec/api/#pushing-an-image
870 // - https://distribution.github.io/distribution/spec/api/#initiate-blob-upload
871 // - https://github.com/opencontainers/distribution-spec/blob/v1.1.1/spec.md#pushing-a-blob-monolithically
872 func (s *blobStore) Push(ctx context.Context, expected ocispec.Descriptor, content io.Reader) error {
873 // start an upload
874 // pushing usually requires both pull and push actions.
875 // Reference: https://github.com/distribution/distribution/blob/v2.7.1/registry/handlers/app.go#L921-L930
876 ctx = auth.AppendRepositoryScope(ctx, s.repo.Reference, auth.ActionPull, auth.ActionPush)
877 url := buildRepositoryBlobUploadURL(s.repo.PlainHTTP, s.repo.Reference)
878 req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, nil)
879 if err != nil {
880 return err
881 }
882
883 resp, err := s.repo.do(req)
884 if err != nil {
885 return err
886 }
887
888 if resp.StatusCode != http.StatusAccepted {
889 defer resp.Body.Close()
890 return errutil.ParseErrorResponse(resp)
891 }
892 resp.Body.Close()
893 return s.completePushAfterInitialPost(ctx, req, resp, expected, content)
894 }
895
896 // sameUploadHost reports whether location and reqURL refer to the same host,
897 // normalizing implicit default ports (80 for http, 443 for https) so that
898 // e.g. "example.com" and "example.com:443" compare equal over HTTPS.
899 func sameUploadHost(location, reqURL *url.URL) bool {
900 if location.Hostname() != reqURL.Hostname() {
901 return false
902 }
903 canonicalPort := func(u *url.URL) string {
904 if p := u.Port(); p != "" {
905 return p
906 }
907 if u.Scheme == "https" {
908 return "443"
909 }
910 return "80"
911 }
912 return canonicalPort(location) == canonicalPort(reqURL)
913 }
914
915 // completePushAfterInitialPost implements step 2 of the push protocol. This can be invoked either by
916 // Push or by Mount when the receiving repository does not implement the
917 // mount endpoint.
918 func (s *blobStore) completePushAfterInitialPost(ctx context.Context, req *http.Request, resp *http.Response, expected ocispec.Descriptor, content io.Reader) error {
919 reqHostname := req.URL.Hostname()
920 reqPort := req.URL.Port()
921 // monolithic upload
922 location, err := resp.Location()
923 if err != nil {
924 return err
925 }
926 // work-around solution for https://github.com/oras-project/oras-go/issues/177
927 // For some registries, if the port 443 is explicitly set to the hostname
928 // like registry.wabbit-networks.io:443/myrepo, blob push will fail since
929 // the hostname of the Location header in the response is set to
930 // registry.wabbit-networks.io instead of registry.wabbit-networks.io:443.
931 locationHostname := location.Hostname()
932 locationPort := location.Port()
933 // if location port 443 is missing, add it back
934 if reqPort == "443" && locationHostname == reqHostname && locationPort == "" {
935 location.Host = locationHostname + ":" + reqPort
936 }
937 // Validate the Location stays on the same host to prevent credentials from
938 // being forwarded to an attacker-controlled endpoint.
939 // Reference: https://github.com/oras-project/oras-go/security/advisories/GHSA-jxpm-75mh-9fp7
940 if !sameUploadHost(location, req.URL) {
941 return fmt.Errorf("blob upload Location %q is on a different host than the registry %q", location.Host, req.URL.Host)
942 }
943 if req.URL.Scheme == "https" && location.Scheme != "https" {
944 return fmt.Errorf("blob upload Location %q downgrades scheme from https", location.Host)
945 }
946 url := location.String()
947 req, err = http.NewRequestWithContext(ctx, http.MethodPut, url, content)
948 if err != nil {
949 return err
950 }
951 if req.GetBody != nil && req.ContentLength != expected.Size {
952 // short circuit a size mismatch for built-in types.
953 return fmt.Errorf("mismatch content length %d: expect %d", req.ContentLength, expected.Size)
954 }
955 req.ContentLength = expected.Size
956 // the expected media type is ignored as in the API doc.
957 req.Header.Set("Content-Type", "application/octet-stream")
958 q := req.URL.Query()
959 q.Set("digest", expected.Digest.String())
960 req.URL.RawQuery = q.Encode()
961
962 // reuse credential from previous POST request
963 if auth := resp.Request.Header.Get("Authorization"); auth != "" {
964 req.Header.Set("Authorization", auth)
965 }
966 resp, err = s.repo.do(req)
967 if err != nil {
968 return err
969 }
970 defer resp.Body.Close()
971
972 if resp.StatusCode != http.StatusCreated {
973 return errutil.ParseErrorResponse(resp)
974 }
975 return nil
976 }
977
978 // Exists returns true if the described content exists.
979 func (s *blobStore) Exists(ctx context.Context, target ocispec.Descriptor) (bool, error) {
980 _, err := s.Resolve(ctx, target.Digest.String())
981 if err == nil {
982 return true, nil
983 }
984 if errors.Is(err, errdef.ErrNotFound) {
985 return false, nil
986 }
987 return false, err
988 }
989
990 // Delete removes the content identified by the descriptor.
991 func (s *blobStore) Delete(ctx context.Context, target ocispec.Descriptor) error {
992 return s.repo.delete(ctx, target, false)
993 }
994
995 // Resolve resolves a reference to a descriptor.
996 func (s *blobStore) Resolve(ctx context.Context, reference string) (ocispec.Descriptor, error) {
997 ref, err := s.repo.ParseReference(reference)
998 if err != nil {
999 return ocispec.Descriptor{}, err
1000 }
1001 refDigest, err := ref.Digest()
1002 if err != nil {
1003 return ocispec.Descriptor{}, err
1004 }
1005 ctx = auth.AppendRepositoryScope(ctx, ref, auth.ActionPull)
1006 url := buildRepositoryBlobURL(s.repo.PlainHTTP, ref)
1007 req, err := http.NewRequestWithContext(ctx, http.MethodHead, url, nil)
1008 if err != nil {
1009 return ocispec.Descriptor{}, err
1010 }
1011
1012 resp, err := s.repo.do(req)
1013 if err != nil {
1014 return ocispec.Descriptor{}, err
1015 }
1016 defer resp.Body.Close()
1017
1018 switch resp.StatusCode {
1019 case http.StatusOK:
1020 return generateBlobDescriptor(resp, refDigest)
1021 case http.StatusNotFound:
1022 return ocispec.Descriptor{}, fmt.Errorf("%s: %w", ref, errdef.ErrNotFound)
1023 default:
1024 return ocispec.Descriptor{}, errutil.ParseErrorResponse(resp)
1025 }
1026 }
1027
1028 // FetchReference fetches the blob identified by the reference.
1029 // The reference must be a digest.
1030 func (s *blobStore) FetchReference(ctx context.Context, reference string) (desc ocispec.Descriptor, rc io.ReadCloser, err error) {
1031 ref, err := s.repo.ParseReference(reference)
1032 if err != nil {
1033 return ocispec.Descriptor{}, nil, err
1034 }
1035 refDigest, err := ref.Digest()
1036 if err != nil {
1037 return ocispec.Descriptor{}, nil, err
1038 }
1039
1040 ctx = auth.AppendRepositoryScope(ctx, ref, auth.ActionPull)
1041 url := buildRepositoryBlobURL(s.repo.PlainHTTP, ref)
1042 req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
1043 if err != nil {
1044 return ocispec.Descriptor{}, nil, err
1045 }
1046
1047 resp, err := s.repo.do(req)
1048 if err != nil {
1049 return ocispec.Descriptor{}, nil, err
1050 }
1051 defer func() {
1052 if err != nil {
1053 resp.Body.Close()
1054 }
1055 }()
1056
1057 switch resp.StatusCode {
1058 case http.StatusOK: // server does not support seek as `Range` was ignored.
1059 if resp.ContentLength == -1 {
1060 desc, err = s.Resolve(ctx, reference)
1061 } else {
1062 desc, err = generateBlobDescriptor(resp, refDigest)
1063 }
1064 if err != nil {
1065 return ocispec.Descriptor{}, nil, err
1066 }
1067
1068 // check server range request capability.
1069 // Docker spec allows range header form of "Range: bytes=<start>-<end>".
1070 // However, the remote server may still not RFC 7233 compliant.
1071 // Reference: https://distribution.github.io/distribution/spec/api/#blob
1072 if rangeUnit := resp.Header.Get("Accept-Ranges"); rangeUnit == "bytes" {
1073 return desc, httputil.NewReadSeekCloser(s.repo.client(), req, resp.Body, desc.Size), nil
1074 }
1075 return desc, resp.Body, nil
1076 case http.StatusNotFound:
1077 return ocispec.Descriptor{}, nil, fmt.Errorf("%s: %w", ref, errdef.ErrNotFound)
1078 default:
1079 return ocispec.Descriptor{}, nil, errutil.ParseErrorResponse(resp)
1080 }
1081 }
1082
1083 // generateBlobDescriptor returns a descriptor generated from the response.
1084 func generateBlobDescriptor(resp *http.Response, refDigest digest.Digest) (ocispec.Descriptor, error) {
1085 mediaType, _, _ := mime.ParseMediaType(resp.Header.Get("Content-Type"))
1086 if mediaType == "" {
1087 mediaType = "application/octet-stream"
1088 }
1089
1090 size := resp.ContentLength
1091 if size == -1 {
1092 return ocispec.Descriptor{}, fmt.Errorf("%s %q: unknown response Content-Length", resp.Request.Method, resp.Request.URL)
1093 }
1094
1095 if err := verifyContentDigest(resp, refDigest); err != nil {
1096 return ocispec.Descriptor{}, err
1097 }
1098
1099 return ocispec.Descriptor{
1100 MediaType: mediaType,
1101 Digest: refDigest,
1102 Size: size,
1103 }, nil
1104 }
1105
1106 // manifestStore accesses the manifest part of the repository.
1107 type manifestStore struct {
1108 repo *Repository
1109 }
1110
1111 // Fetch fetches the content identified by the descriptor.
1112 func (s *manifestStore) Fetch(ctx context.Context, target ocispec.Descriptor) (rc io.ReadCloser, err error) {
1113 ref := s.repo.Reference
1114 ref.Reference = target.Digest.String()
1115 ctx = auth.AppendRepositoryScope(ctx, ref, auth.ActionPull)
1116 url := buildRepositoryManifestURL(s.repo.PlainHTTP, ref)
1117 req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
1118 if err != nil {
1119 return nil, err
1120 }
1121 req.Header.Set("Accept", target.MediaType)
1122
1123 resp, err := s.repo.do(req)
1124 if err != nil {
1125 return nil, err
1126 }
1127 defer func() {
1128 if err != nil {
1129 resp.Body.Close()
1130 }
1131 }()
1132
1133 switch resp.StatusCode {
1134 case http.StatusOK:
1135 // no-op
1136 case http.StatusNotFound:
1137 return nil, fmt.Errorf("%s: %w", target.Digest, errdef.ErrNotFound)
1138 default:
1139 return nil, errutil.ParseErrorResponse(resp)
1140 }
1141 mediaType, _, err := mime.ParseMediaType(resp.Header.Get("Content-Type"))
1142 if err != nil {
1143 return nil, fmt.Errorf("%s %q: invalid response Content-Type: %w", resp.Request.Method, resp.Request.URL, err)
1144 }
1145 if mediaType != target.MediaType {
1146 return nil, fmt.Errorf("%s %q: mismatch response Content-Type %q: expect %q", resp.Request.Method, resp.Request.URL, mediaType, target.MediaType)
1147 }
1148 if size := resp.ContentLength; size != -1 && size != target.Size {
1149 return nil, fmt.Errorf("%s %q: mismatch Content-Length", resp.Request.Method, resp.Request.URL)
1150 }
1151 if err := verifyContentDigest(resp, target.Digest); err != nil {
1152 return nil, err
1153 }
1154 return resp.Body, nil
1155 }
1156
1157 // Push pushes the content, matching the expected descriptor.
1158 func (s *manifestStore) Push(ctx context.Context, expected ocispec.Descriptor, content io.Reader) error {
1159 return s.pushWithIndexing(ctx, expected, content, expected.Digest.String())
1160 }
1161
1162 // Exists returns true if the described content exists.
1163 func (s *manifestStore) Exists(ctx context.Context, target ocispec.Descriptor) (bool, error) {
1164 _, err := s.Resolve(ctx, target.Digest.String())
1165 if err == nil {
1166 return true, nil
1167 }
1168 if errors.Is(err, errdef.ErrNotFound) {
1169 return false, nil
1170 }
1171 return false, err
1172 }
1173
1174 // Delete removes the manifest content identified by the descriptor.
1175 func (s *manifestStore) Delete(ctx context.Context, target ocispec.Descriptor) error {
1176 return s.deleteWithIndexing(ctx, target)
1177 }
1178
1179 // deleteWithIndexing removes the manifest content identified by the descriptor,
1180 // and indexes referrers for the manifest when needed.
1181 func (s *manifestStore) deleteWithIndexing(ctx context.Context, target ocispec.Descriptor) error {
1182 switch target.MediaType {
1183 case spec.MediaTypeArtifactManifest, ocispec.MediaTypeImageManifest, ocispec.MediaTypeImageIndex:
1184 if state := s.repo.loadReferrersState(); state == referrersStateSupported {
1185 // referrers API is available, no client-side indexing needed
1186 return s.repo.delete(ctx, target, true)
1187 }
1188
1189 if err := limitSize(target, s.repo.MaxMetadataBytes); err != nil {
1190 return err
1191 }
1192 ctx = auth.AppendRepositoryScope(ctx, s.repo.Reference, auth.ActionPull, auth.ActionDelete)
1193 manifestJSON, err := content.FetchAll(ctx, s, target)
1194 if err != nil {
1195 return err
1196 }
1197 if err := s.indexReferrersForDelete(ctx, target, manifestJSON); err != nil {
1198 return err
1199 }
1200 }
1201
1202 return s.repo.delete(ctx, target, true)
1203 }
1204
1205 // indexReferrersForDelete indexes referrers for manifests with a subject field
1206 // on manifest delete.
1207 //
1208 // References:
1209 // - Latest spec: https://github.com/opencontainers/distribution-spec/blob/v1.1.1/spec.md#deleting-manifests
1210 // - Compatible spec: https://github.com/opencontainers/distribution-spec/blob/v1.1.0-rc1/spec.md#deleting-manifests
1211 func (s *manifestStore) indexReferrersForDelete(ctx context.Context, desc ocispec.Descriptor, manifestJSON []byte) error {
1212 var manifest struct {
1213 Subject *ocispec.Descriptor `json:"subject"`
1214 }
1215 if err := json.Unmarshal(manifestJSON, &manifest); err != nil {
1216 return fmt.Errorf("failed to decode manifest: %s: %s: %w", desc.Digest, desc.MediaType, err)
1217 }
1218 if manifest.Subject == nil {
1219 // no subject, no indexing needed
1220 return nil
1221 }
1222
1223 subject := *manifest.Subject
1224 ok, err := s.repo.pingReferrers(ctx)
1225 if err != nil {
1226 return err
1227 }
1228 if ok {
1229 // referrers API is available, no client-side indexing needed
1230 return nil
1231 }
1232 return s.updateReferrersIndex(ctx, subject, referrerChange{desc, referrerOperationRemove})
1233 }
1234
1235 // Resolve resolves a reference to a descriptor.
1236 // See also `ManifestMediaTypes`.
1237 func (s *manifestStore) Resolve(ctx context.Context, reference string) (ocispec.Descriptor, error) {
1238 ref, err := s.repo.ParseReference(reference)
1239 if err != nil {
1240 return ocispec.Descriptor{}, err
1241 }
1242 ctx = auth.AppendRepositoryScope(ctx, ref, auth.ActionPull)
1243 url := buildRepositoryManifestURL(s.repo.PlainHTTP, ref)
1244 req, err := http.NewRequestWithContext(ctx, http.MethodHead, url, nil)
1245 if err != nil {
1246 return ocispec.Descriptor{}, err
1247 }
1248 req.Header.Set("Accept", manifestAcceptHeader(s.repo.ManifestMediaTypes))
1249
1250 resp, err := s.repo.do(req)
1251 if err != nil {
1252 return ocispec.Descriptor{}, err
1253 }
1254 defer resp.Body.Close()
1255
1256 switch resp.StatusCode {
1257 case http.StatusOK:
1258 return s.generateDescriptor(resp, ref, req.Method)
1259 case http.StatusNotFound:
1260 return ocispec.Descriptor{}, fmt.Errorf("%s: %w", ref, errdef.ErrNotFound)
1261 default:
1262 return ocispec.Descriptor{}, errutil.ParseErrorResponse(resp)
1263 }
1264 }
1265
1266 // FetchReference fetches the manifest identified by the reference.
1267 // The reference can be a tag or digest.
1268 func (s *manifestStore) FetchReference(ctx context.Context, reference string) (desc ocispec.Descriptor, rc io.ReadCloser, err error) {
1269 ref, err := s.repo.ParseReference(reference)
1270 if err != nil {
1271 return ocispec.Descriptor{}, nil, err
1272 }
1273
1274 ctx = auth.AppendRepositoryScope(ctx, ref, auth.ActionPull)
1275 url := buildRepositoryManifestURL(s.repo.PlainHTTP, ref)
1276 req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
1277 if err != nil {
1278 return ocispec.Descriptor{}, nil, err
1279 }
1280 req.Header.Set("Accept", manifestAcceptHeader(s.repo.ManifestMediaTypes))
1281
1282 resp, err := s.repo.do(req)
1283 if err != nil {
1284 return ocispec.Descriptor{}, nil, err
1285 }
1286 defer func() {
1287 if err != nil {
1288 resp.Body.Close()
1289 }
1290 }()
1291
1292 switch resp.StatusCode {
1293 case http.StatusOK:
1294 if resp.ContentLength == -1 {
1295 desc, err = s.Resolve(ctx, reference)
1296 } else {
1297 desc, err = s.generateDescriptor(resp, ref, req.Method)
1298 }
1299 if err != nil {
1300 return ocispec.Descriptor{}, nil, err
1301 }
1302 return desc, resp.Body, nil
1303 case http.StatusNotFound:
1304 return ocispec.Descriptor{}, nil, fmt.Errorf("%s: %w", ref, errdef.ErrNotFound)
1305 default:
1306 return ocispec.Descriptor{}, nil, errutil.ParseErrorResponse(resp)
1307 }
1308 }
1309
1310 // Tag tags a manifest descriptor with a reference string.
1311 func (s *manifestStore) Tag(ctx context.Context, desc ocispec.Descriptor, reference string) error {
1312 ref, err := s.repo.ParseReference(reference)
1313 if err != nil {
1314 return err
1315 }
1316
1317 ctx = auth.AppendRepositoryScope(ctx, ref, auth.ActionPull, auth.ActionPush)
1318 rc, err := s.Fetch(ctx, desc)
1319 if err != nil {
1320 return err
1321 }
1322 defer rc.Close()
1323
1324 return s.push(ctx, desc, rc, ref.Reference)
1325 }
1326
1327 // PushReference pushes the manifest with a reference tag.
1328 func (s *manifestStore) PushReference(ctx context.Context, expected ocispec.Descriptor, content io.Reader, reference string) error {
1329 ref, err := s.repo.ParseReference(reference)
1330 if err != nil {
1331 return err
1332 }
1333 return s.pushWithIndexing(ctx, expected, content, ref.Reference)
1334 }
1335
1336 // push pushes the manifest content, matching the expected descriptor.
1337 func (s *manifestStore) push(ctx context.Context, expected ocispec.Descriptor, content io.Reader, reference string) error {
1338 ref := s.repo.Reference
1339 ref.Reference = reference
1340 // pushing usually requires both pull and push actions.
1341 // Reference: https://github.com/distribution/distribution/blob/v2.7.1/registry/handlers/app.go#L921-L930
1342 ctx = auth.AppendRepositoryScope(ctx, ref, auth.ActionPull, auth.ActionPush)
1343 url := buildRepositoryManifestURL(s.repo.PlainHTTP, ref)
1344 // unwrap the content for optimizations of built-in types.
1345 body := ioutil.UnwrapNopCloser(content)
1346 if _, ok := body.(io.ReadCloser); ok {
1347 // undo unwrap if the nopCloser is intended.
1348 body = content
1349 }
1350 req, err := http.NewRequestWithContext(ctx, http.MethodPut, url, body)
1351 if err != nil {
1352 return err
1353 }
1354 if req.GetBody != nil && req.ContentLength != expected.Size {
1355 // short circuit a size mismatch for built-in types.
1356 return fmt.Errorf("mismatch content length %d: expect %d", req.ContentLength, expected.Size)
1357 }
1358 req.ContentLength = expected.Size
1359 req.Header.Set("Content-Type", expected.MediaType)
1360
1361 // if the underlying client is an auth client, the content might be read
1362 // more than once for obtaining the auth challenge and the actual request.
1363 // To prevent double reading, the manifest is read and stored in the memory,
1364 // and serve from the memory.
1365 client := s.repo.client()
1366 if _, ok := client.(*auth.Client); ok && req.GetBody == nil {
1367 store := cas.NewMemory()
1368 err := store.Push(ctx, expected, content)
1369 if err != nil {
1370 return err
1371 }
1372 req.GetBody = func() (io.ReadCloser, error) {
1373 return store.Fetch(ctx, expected)
1374 }
1375 req.Body, err = req.GetBody()
1376 if err != nil {
1377 return err
1378 }
1379 }
1380 resp, err := s.repo.do(req)
1381 if err != nil {
1382 return err
1383 }
1384 defer resp.Body.Close()
1385
1386 if resp.StatusCode != http.StatusCreated {
1387 return errutil.ParseErrorResponse(resp)
1388 }
1389 s.checkOCISubjectHeader(resp)
1390 return verifyContentDigest(resp, expected.Digest)
1391 }
1392
1393 // checkOCISubjectHeader checks the "OCI-Subject" header in the response and
1394 // sets referrers capability accordingly.
1395 // Reference: https://github.com/opencontainers/distribution-spec/blob/v1.1.1/spec.md#pushing-manifests-with-subject
1396 func (s *manifestStore) checkOCISubjectHeader(resp *http.Response) {
1397 // If the "OCI-Subject" header is set, it indicates that the registry
1398 // supports the Referrers API and has processed the subject of the manifest.
1399 if subjectHeader := resp.Header.Get(headerOCISubject); subjectHeader != "" {
1400 s.repo.SetReferrersCapability(true)
1401 }
1402
1403 // If the "OCI-Subject" header is NOT set, it means that either the manifest
1404 // has no subject OR the referrers API is NOT supported by the registry.
1405 //
1406 // Since we don't know whether the pushed manifest has a subject or not,
1407 // we do not set the referrers capability to false at here.
1408 }
1409
1410 // pushWithIndexing pushes the manifest content matching the expected descriptor,
1411 // and indexes referrers for the manifest when needed.
1412 func (s *manifestStore) pushWithIndexing(ctx context.Context, expected ocispec.Descriptor, r io.Reader, reference string) error {
1413 switch expected.MediaType {
1414 case spec.MediaTypeArtifactManifest, ocispec.MediaTypeImageManifest, ocispec.MediaTypeImageIndex:
1415 if state := s.repo.loadReferrersState(); state == referrersStateSupported {
1416 // referrers API is available, no client-side indexing needed
1417 return s.push(ctx, expected, r, reference)
1418 }
1419
1420 if err := limitSize(expected, s.repo.MaxMetadataBytes); err != nil {
1421 return err
1422 }
1423 manifestJSON, err := content.ReadAll(r, expected)
1424 if err != nil {
1425 return err
1426 }
1427 if err := s.push(ctx, expected, bytes.NewReader(manifestJSON), reference); err != nil {
1428 return err
1429 }
1430 // check referrers API availability again after push
1431 if state := s.repo.loadReferrersState(); state == referrersStateSupported {
1432 // the subject has been processed the registry, no client-side
1433 // indexing needed
1434 return nil
1435 }
1436 return s.indexReferrersForPush(ctx, expected, manifestJSON)
1437 default:
1438 return s.push(ctx, expected, r, reference)
1439 }
1440 }
1441
1442 // indexReferrersForPush indexes referrers for manifests with a subject field
1443 // on manifest push.
1444 //
1445 // References:
1446 // - Latest spec: https://github.com/opencontainers/distribution-spec/blob/v1.1.1/spec.md#pushing-manifests-with-subject
1447 // - Compatible spec: https://github.com/opencontainers/distribution-spec/blob/v1.1.0-rc1/spec.md#pushing-manifests-with-subject
1448 func (s *manifestStore) indexReferrersForPush(ctx context.Context, desc ocispec.Descriptor, manifestJSON []byte) error {
1449 var subject ocispec.Descriptor
1450 switch desc.MediaType {
1451 case spec.MediaTypeArtifactManifest:
1452 var manifest spec.Artifact
1453 if err := json.Unmarshal(manifestJSON, &manifest); err != nil {
1454 return fmt.Errorf("failed to decode manifest: %s: %s: %w", desc.Digest, desc.MediaType, err)
1455 }
1456 if manifest.Subject == nil {
1457 // no subject, no indexing needed
1458 return nil
1459 }
1460 subject = *manifest.Subject
1461 desc.ArtifactType = manifest.ArtifactType
1462 desc.Annotations = manifest.Annotations
1463 case ocispec.MediaTypeImageManifest:
1464 var manifest ocispec.Manifest
1465 if err := json.Unmarshal(manifestJSON, &manifest); err != nil {
1466 return fmt.Errorf("failed to decode manifest: %s: %s: %w", desc.Digest, desc.MediaType, err)
1467 }
1468 if manifest.Subject == nil {
1469 // no subject, no indexing needed
1470 return nil
1471 }
1472 subject = *manifest.Subject
1473 desc.ArtifactType = manifest.ArtifactType
1474 if desc.ArtifactType == "" {
1475 desc.ArtifactType = manifest.Config.MediaType
1476 }
1477 desc.Annotations = manifest.Annotations
1478 case ocispec.MediaTypeImageIndex:
1479 var manifest ocispec.Index
1480 if err := json.Unmarshal(manifestJSON, &manifest); err != nil {
1481 return fmt.Errorf("failed to decode manifest: %s: %s: %w", desc.Digest, desc.MediaType, err)
1482 }
1483 if manifest.Subject == nil {
1484 // no subject, no indexing needed
1485 return nil
1486 }
1487 subject = *manifest.Subject
1488 desc.ArtifactType = manifest.ArtifactType
1489 desc.Annotations = manifest.Annotations
1490 default:
1491 return nil
1492 }
1493
1494 // if the manifest has a subject but the remote registry does not process it,
1495 // it means that the Referrers API is not supported by the registry.
1496 s.repo.SetReferrersCapability(false)
1497 return s.updateReferrersIndex(ctx, subject, referrerChange{desc, referrerOperationAdd})
1498 }
1499
1500 // updateReferrersIndex updates the referrers index for desc referencing subject
1501 // on manifest push and manifest delete.
1502 // References:
1503 // - https://github.com/opencontainers/distribution-spec/blob/v1.1.1/spec.md#pushing-manifests-with-subject
1504 // - https://github.com/opencontainers/distribution-spec/blob/v1.1.1/spec.md#deleting-manifests
1505 func (s *manifestStore) updateReferrersIndex(ctx context.Context, subject ocispec.Descriptor, change referrerChange) (err error) {
1506 referrersTag, err := buildReferrersTag(subject)
1507 if err != nil {
1508 return err
1509 }
1510
1511 var oldIndexDesc *ocispec.Descriptor
1512 var oldReferrers []ocispec.Descriptor
1513 prepare := func() error {
1514 // 1. pull the original referrers list using the referrers tag schema
1515 indexDesc, referrers, err := s.repo.referrersFromIndex(ctx, referrersTag)
1516 if err != nil {
1517 if errors.Is(err, errdef.ErrNotFound) {
1518 // valid case: no old referrers index
1519 return nil
1520 }
1521 return err
1522 }
1523 oldIndexDesc = &indexDesc
1524 oldReferrers = referrers
1525 return nil
1526 }
1527 update := func(referrerChanges []referrerChange) error {
1528 // 2. apply the referrer changes on the referrers list
1529 updatedReferrers, err := applyReferrerChanges(oldReferrers, referrerChanges)
1530 if err != nil {
1531 if err == errNoReferrerUpdate {
1532 return nil
1533 }
1534 return err
1535 }
1536
1537 // 3. push the updated referrers list using referrers tag schema
1538 if len(updatedReferrers) > 0 || s.repo.SkipReferrersGC {
1539 // push a new index in either case:
1540 // 1. the referrers list has been updated with a non-zero size
1541 // 2. OR the updated referrers list is empty but referrers GC
1542 // is skipped, in this case an empty index should still be pushed
1543 // as the old index won't get deleted
1544 newIndexDesc, newIndex, err := generateIndex(updatedReferrers)
1545 if err != nil {
1546 return fmt.Errorf("failed to generate referrers index for referrers tag %s: %w", referrersTag, err)
1547 }
1548 if err := s.push(ctx, newIndexDesc, bytes.NewReader(newIndex), referrersTag); err != nil {
1549 return fmt.Errorf("failed to push referrers index tagged by %s: %w", referrersTag, err)
1550 }
1551 }
1552
1553 // 4. delete the dangling original referrers index, if applicable
1554 if s.repo.SkipReferrersGC || oldIndexDesc == nil {
1555 return nil
1556 }
1557 if err := s.repo.delete(ctx, *oldIndexDesc, true); err != nil {
1558 return &ReferrersError{
1559 Op: opDeleteReferrersIndex,
1560 Err: fmt.Errorf("failed to delete dangling referrers index %s for referrers tag %s: %w", oldIndexDesc.Digest.String(), referrersTag, err),
1561 Subject: subject,
1562 }
1563 }
1564 return nil
1565 }
1566
1567 merge, done := s.repo.referrersMergePool.Get(referrersTag)
1568 defer done()
1569 return merge.Do(change, prepare, update)
1570 }
1571
1572 // ParseReference parses a reference to a fully qualified reference.
1573 func (s *manifestStore) ParseReference(reference string) (registry.Reference, error) {
1574 return s.repo.ParseReference(reference)
1575 }
1576
1577 // generateDescriptor returns a descriptor generated from the response.
1578 // See the truth table at the top of `repository_test.go`
1579 func (s *manifestStore) generateDescriptor(resp *http.Response, ref registry.Reference, httpMethod string) (ocispec.Descriptor, error) {
1580 // 1. Validate Content-Type
1581 mediaType, _, err := mime.ParseMediaType(resp.Header.Get("Content-Type"))
1582 if err != nil {
1583 return ocispec.Descriptor{}, fmt.Errorf(
1584 "%s %q: invalid response `Content-Type` header; %w",
1585 resp.Request.Method,
1586 resp.Request.URL,
1587 err,
1588 )
1589 }
1590
1591 // 2. Validate Size
1592 if resp.ContentLength == -1 {
1593 return ocispec.Descriptor{}, fmt.Errorf(
1594 "%s %q: unknown response Content-Length",
1595 resp.Request.Method,
1596 resp.Request.URL,
1597 )
1598 }
1599
1600 // 3. Validate Client Reference
1601 var refDigest digest.Digest
1602 if d, err := ref.Digest(); err == nil {
1603 refDigest = d
1604 }
1605
1606 // 4. Validate Server Digest (if present)
1607 var serverHeaderDigest digest.Digest
1608 if serverHeaderDigestStr := resp.Header.Get(headerDockerContentDigest); serverHeaderDigestStr != "" {
1609 if serverHeaderDigest, err = digest.Parse(serverHeaderDigestStr); err != nil {
1610 return ocispec.Descriptor{}, fmt.Errorf(
1611 "%s %q: invalid response header value: `%s: %s`; %w",
1612 resp.Request.Method,
1613 resp.Request.URL,
1614 headerDockerContentDigest,
1615 serverHeaderDigestStr,
1616 err,
1617 )
1618 }
1619 }
1620
1621 /* 5. Now, look for specific error conditions; see truth table in method docstring */
1622 var contentDigest digest.Digest
1623
1624 if len(serverHeaderDigest) == 0 {
1625 if httpMethod == http.MethodHead {
1626 if len(refDigest) == 0 {
1627 // HEAD without server `Docker-Content-Digest` header is an
1628 // immediate fail
1629 return ocispec.Descriptor{}, fmt.Errorf(
1630 "HTTP %s request missing required header %q",
1631 httpMethod, headerDockerContentDigest,
1632 )
1633 }
1634 // Otherwise, just trust the client-supplied digest
1635 contentDigest = refDigest
1636 } else {
1637 // GET without server `Docker-Content-Digest` header forces the
1638 // expensive calculation
1639 var calculatedDigest digest.Digest
1640 if calculatedDigest, err = calculateDigestFromResponse(resp, s.repo.MaxMetadataBytes); err != nil {
1641 return ocispec.Descriptor{}, fmt.Errorf("failed to calculate digest on response body; %w", err)
1642 }
1643 contentDigest = calculatedDigest
1644 }
1645 } else {
1646 contentDigest = serverHeaderDigest
1647 }
1648
1649 if len(refDigest) > 0 && refDigest != contentDigest {
1650 return ocispec.Descriptor{}, fmt.Errorf(
1651 "%s %q: invalid response; digest mismatch in %s: received %q when expecting %q",
1652 resp.Request.Method, resp.Request.URL,
1653 headerDockerContentDigest, contentDigest,
1654 refDigest,
1655 )
1656 }
1657
1658 // 6. Finally, if we made it this far, then all is good; return.
1659 return ocispec.Descriptor{
1660 MediaType: mediaType,
1661 Digest: contentDigest,
1662 Size: resp.ContentLength,
1663 }, nil
1664 }
1665
1666 // calculateDigestFromResponse calculates the actual digest of the response body
1667 // taking care not to destroy it in the process.
1668 func calculateDigestFromResponse(resp *http.Response, maxMetadataBytes int64) (digest.Digest, error) {
1669 defer resp.Body.Close()
1670
1671 body := limitReader(resp.Body, maxMetadataBytes)
1672 content, err := io.ReadAll(body)
1673 if err != nil {
1674 return "", fmt.Errorf("%s %q: failed to read response body: %w", resp.Request.Method, resp.Request.URL, err)
1675 }
1676 resp.Body = io.NopCloser(bytes.NewReader(content))
1677
1678 return digest.FromBytes(content), nil
1679 }
1680
1681 // verifyContentDigest verifies "Docker-Content-Digest" header if present.
1682 // OCI distribution-spec states the Docker-Content-Digest header is optional.
1683 // Reference: https://github.com/opencontainers/distribution-spec/blob/v1.0.1/spec.md#legacy-docker-support-http-headers
1684 func verifyContentDigest(resp *http.Response, expected digest.Digest) error {
1685 digestStr := resp.Header.Get(headerDockerContentDigest)
1686
1687 if len(digestStr) == 0 {
1688 return nil
1689 }
1690
1691 contentDigest, err := digest.Parse(digestStr)
1692 if err != nil {
1693 return fmt.Errorf(
1694 "%s %q: invalid response header: `%s: %s`",
1695 resp.Request.Method, resp.Request.URL,
1696 headerDockerContentDigest, digestStr,
1697 )
1698 }
1699
1700 if contentDigest != expected {
1701 return fmt.Errorf(
1702 "%s %q: invalid response; digest mismatch in %s: received %q when expecting %q",
1703 resp.Request.Method, resp.Request.URL,
1704 headerDockerContentDigest, contentDigest,
1705 expected,
1706 )
1707 }
1708
1709 return nil
1710 }
1711
1712 // generateIndex generates an image index containing the given manifests list.
1713 func generateIndex(manifests []ocispec.Descriptor) (ocispec.Descriptor, []byte, error) {
1714 if manifests == nil {
1715 manifests = []ocispec.Descriptor{} // make it an empty array to prevent potential server-side bugs
1716 }
1717 index := ocispec.Index{
1718 Versioned: specs.Versioned{
1719 SchemaVersion: 2, // historical value. does not pertain to OCI or docker version
1720 },
1721 MediaType: ocispec.MediaTypeImageIndex,
1722 Manifests: manifests,
1723 }
1724 indexJSON, err := json.Marshal(index)
1725 if err != nil {
1726 return ocispec.Descriptor{}, nil, err
1727 }
1728 indexDesc := content.NewDescriptorFromBytes(index.MediaType, indexJSON)
1729 return indexDesc, indexJSON, nil
1730 }