push.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  1. /*
  2. Copyright 2023 Docker Compose CLI 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. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package ocipush
  14. import (
  15. "context"
  16. "encoding/json"
  17. "errors"
  18. "fmt"
  19. "net/http"
  20. "path/filepath"
  21. "time"
  22. pusherrors "github.com/containerd/containerd/remotes/errors"
  23. "github.com/distribution/reference"
  24. "github.com/docker/buildx/util/imagetools"
  25. "github.com/docker/compose/v2/pkg/api"
  26. "github.com/opencontainers/go-digest"
  27. "github.com/opencontainers/image-spec/specs-go"
  28. v1 "github.com/opencontainers/image-spec/specs-go/v1"
  29. )
  30. const (
  31. // ComposeProjectArtifactType is the OCI 1.1-compliant artifact type value
  32. // for the generated image manifest.
  33. ComposeProjectArtifactType = "application/vnd.docker.compose.project"
  34. // ComposeYAMLMediaType is the media type for each layer (Compose file)
  35. // in the image manifest.
  36. ComposeYAMLMediaType = "application/vnd.docker.compose.file+yaml"
  37. // ComposeEmptyConfigMediaType is a media type used for the config descriptor
  38. // when doing OCI 1.0-style pushes.
  39. //
  40. // The content is always `{}`, the same as a normal empty descriptor, but
  41. // the specific media type allows clients to fall back to the config media
  42. // type to recognize the manifest as a Compose project since the artifact
  43. // type field is not available in OCI 1.0.
  44. //
  45. // This is based on guidance from the OCI 1.1 spec:
  46. // > Implementers note: artifacts have historically been created without
  47. // > an artifactType field, and tooling to work with artifacts should
  48. // > fallback to the config.mediaType value.
  49. ComposeEmptyConfigMediaType = "application/vnd.docker.compose.config.empty.v1+json"
  50. )
  51. // clientAuthStatusCodes are client (4xx) errors that are authentication
  52. // related.
  53. var clientAuthStatusCodes = []int{
  54. http.StatusUnauthorized,
  55. http.StatusForbidden,
  56. http.StatusProxyAuthRequired,
  57. }
  58. type Pushable struct {
  59. Descriptor v1.Descriptor
  60. Data []byte
  61. }
  62. func DescriptorForComposeFile(path string, content []byte) v1.Descriptor {
  63. return v1.Descriptor{
  64. MediaType: ComposeYAMLMediaType,
  65. Digest: digest.FromString(string(content)),
  66. Size: int64(len(content)),
  67. Annotations: map[string]string{
  68. "com.docker.compose.version": api.ComposeVersion,
  69. "com.docker.compose.file": filepath.Base(path),
  70. },
  71. }
  72. }
  73. func PushManifest(
  74. ctx context.Context,
  75. resolver *imagetools.Resolver,
  76. named reference.Named,
  77. layers []Pushable,
  78. ociVersion api.OCIVersion,
  79. ) error {
  80. // prepare to push the manifest by pushing the layers
  81. layerDescriptors := make([]v1.Descriptor, len(layers))
  82. for i := range layers {
  83. layerDescriptors[i] = layers[i].Descriptor
  84. if err := resolver.Push(ctx, named, layers[i].Descriptor, layers[i].Data); err != nil {
  85. return err
  86. }
  87. }
  88. if ociVersion != "" {
  89. // if a version was explicitly specified, use it
  90. return createAndPushManifest(ctx, resolver, named, layerDescriptors, ociVersion)
  91. }
  92. // try to push in the OCI 1.1 format but fallback to OCI 1.0 on 4xx errors
  93. // (other than auth) since it's most likely the result of the registry not
  94. // having support
  95. err := createAndPushManifest(ctx, resolver, named, layerDescriptors, api.OCIVersion1_1)
  96. var pushErr pusherrors.ErrUnexpectedStatus
  97. if errors.As(err, &pushErr) && isNonAuthClientError(pushErr.StatusCode) {
  98. // TODO(milas): show a warning here (won't work with logrus)
  99. return createAndPushManifest(ctx, resolver, named, layerDescriptors, api.OCIVersion1_0)
  100. }
  101. return err
  102. }
  103. func createAndPushManifest(
  104. ctx context.Context,
  105. resolver *imagetools.Resolver,
  106. named reference.Named,
  107. layers []v1.Descriptor,
  108. ociVersion api.OCIVersion,
  109. ) error {
  110. toPush, err := generateManifest(layers, ociVersion)
  111. if err != nil {
  112. return err
  113. }
  114. for _, p := range toPush {
  115. err = resolver.Push(ctx, named, p.Descriptor, p.Data)
  116. if err != nil {
  117. return err
  118. }
  119. }
  120. return nil
  121. }
  122. func isNonAuthClientError(statusCode int) bool {
  123. if statusCode < 400 || statusCode >= 500 {
  124. // not a client error
  125. return false
  126. }
  127. for _, v := range clientAuthStatusCodes {
  128. if statusCode == v {
  129. // client auth error
  130. return false
  131. }
  132. }
  133. // any other 4xx client error
  134. return true
  135. }
  136. func generateManifest(layers []v1.Descriptor, ociCompat api.OCIVersion) ([]Pushable, error) {
  137. var toPush []Pushable
  138. var config v1.Descriptor
  139. var artifactType string
  140. switch ociCompat {
  141. case api.OCIVersion1_0:
  142. // "Content other than OCI container images MAY be packaged using the image manifest.
  143. // When this is done, the config.mediaType value MUST be set to a value specific to
  144. // the artifact type or the empty value."
  145. // Source: https://github.com/opencontainers/image-spec/blob/main/manifest.md#guidelines-for-artifact-usage
  146. //
  147. // The `ComposeEmptyConfigMediaType` is used specifically for this purpose:
  148. // there is no config, and an empty descriptor is used for OCI 1.1 in
  149. // conjunction with the `ArtifactType`, but for OCI 1.0 compatibility,
  150. // tooling falls back to the config media type, so this is used to
  151. // indicate that it's not a container image but custom content.
  152. configData := []byte("{}")
  153. config = v1.Descriptor{
  154. MediaType: ComposeEmptyConfigMediaType,
  155. Digest: digest.FromBytes(configData),
  156. Size: int64(len(configData)),
  157. }
  158. // N.B. OCI 1.0 does NOT support specifying the artifact type, so it's
  159. // left as an empty string to omit it from the marshaled JSON
  160. artifactType = ""
  161. toPush = append(toPush, Pushable{Descriptor: config, Data: configData})
  162. case api.OCIVersion1_1:
  163. config = v1.DescriptorEmptyJSON
  164. artifactType = ComposeProjectArtifactType
  165. // N.B. the descriptor has the data embedded in it
  166. toPush = append(toPush, Pushable{Descriptor: config, Data: nil})
  167. default:
  168. return nil, fmt.Errorf("unsupported OCI version: %s", ociCompat)
  169. }
  170. manifest, err := json.Marshal(v1.Manifest{
  171. Versioned: specs.Versioned{SchemaVersion: 2},
  172. MediaType: v1.MediaTypeImageManifest,
  173. ArtifactType: artifactType,
  174. Config: config,
  175. Layers: layers,
  176. Annotations: map[string]string{
  177. "org.opencontainers.image.created": time.Now().Format(time.RFC3339),
  178. },
  179. })
  180. if err != nil {
  181. return nil, err
  182. }
  183. manifestDescriptor := v1.Descriptor{
  184. MediaType: v1.MediaTypeImageManifest,
  185. Digest: digest.FromString(string(manifest)),
  186. Size: int64(len(manifest)),
  187. Annotations: map[string]string{
  188. "com.docker.compose.version": api.ComposeVersion,
  189. },
  190. ArtifactType: artifactType,
  191. }
  192. toPush = append(toPush, Pushable{Descriptor: manifestDescriptor, Data: manifest})
  193. return toPush, nil
  194. }