push.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  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. // Check if we need an extra empty layer for the manifest config
  81. if ociVersion == api.OCIVersion1_1 || ociVersion == "" {
  82. layers = append(layers, Pushable{Descriptor: v1.DescriptorEmptyJSON, Data: []byte("{}")})
  83. }
  84. // prepare to push the manifest by pushing the layers
  85. layerDescriptors := make([]v1.Descriptor, len(layers))
  86. for i := range layers {
  87. layerDescriptors[i] = layers[i].Descriptor
  88. if err := resolver.Push(ctx, named, layers[i].Descriptor, layers[i].Data); err != nil {
  89. return err
  90. }
  91. }
  92. if ociVersion != "" {
  93. // if a version was explicitly specified, use it
  94. return createAndPushManifest(ctx, resolver, named, layerDescriptors, ociVersion)
  95. }
  96. // try to push in the OCI 1.1 format but fallback to OCI 1.0 on 4xx errors
  97. // (other than auth) since it's most likely the result of the registry not
  98. // having support
  99. err := createAndPushManifest(ctx, resolver, named, layerDescriptors, api.OCIVersion1_1)
  100. var pushErr pusherrors.ErrUnexpectedStatus
  101. if errors.As(err, &pushErr) && isNonAuthClientError(pushErr.StatusCode) {
  102. // TODO(milas): show a warning here (won't work with logrus)
  103. return createAndPushManifest(ctx, resolver, named, layerDescriptors, api.OCIVersion1_0)
  104. }
  105. return err
  106. }
  107. func createAndPushManifest(
  108. ctx context.Context,
  109. resolver *imagetools.Resolver,
  110. named reference.Named,
  111. layers []v1.Descriptor,
  112. ociVersion api.OCIVersion,
  113. ) error {
  114. toPush, err := generateManifest(layers, ociVersion)
  115. if err != nil {
  116. return err
  117. }
  118. for _, p := range toPush {
  119. err = resolver.Push(ctx, named, p.Descriptor, p.Data)
  120. if err != nil {
  121. return err
  122. }
  123. }
  124. return nil
  125. }
  126. func isNonAuthClientError(statusCode int) bool {
  127. if statusCode < 400 || statusCode >= 500 {
  128. // not a client error
  129. return false
  130. }
  131. for _, v := range clientAuthStatusCodes {
  132. if statusCode == v {
  133. // client auth error
  134. return false
  135. }
  136. }
  137. // any other 4xx client error
  138. return true
  139. }
  140. func generateManifest(layers []v1.Descriptor, ociCompat api.OCIVersion) ([]Pushable, error) {
  141. var toPush []Pushable
  142. var config v1.Descriptor
  143. var artifactType string
  144. switch ociCompat {
  145. case api.OCIVersion1_0:
  146. // "Content other than OCI container images MAY be packaged using the image manifest.
  147. // When this is done, the config.mediaType value MUST be set to a value specific to
  148. // the artifact type or the empty value."
  149. // Source: https://github.com/opencontainers/image-spec/blob/main/manifest.md#guidelines-for-artifact-usage
  150. //
  151. // The `ComposeEmptyConfigMediaType` is used specifically for this purpose:
  152. // there is no config, and an empty descriptor is used for OCI 1.1 in
  153. // conjunction with the `ArtifactType`, but for OCI 1.0 compatibility,
  154. // tooling falls back to the config media type, so this is used to
  155. // indicate that it's not a container image but custom content.
  156. configData := []byte("{}")
  157. config = v1.Descriptor{
  158. MediaType: ComposeEmptyConfigMediaType,
  159. Digest: digest.FromBytes(configData),
  160. Size: int64(len(configData)),
  161. }
  162. // N.B. OCI 1.0 does NOT support specifying the artifact type, so it's
  163. // left as an empty string to omit it from the marshaled JSON
  164. artifactType = ""
  165. toPush = append(toPush, Pushable{Descriptor: config, Data: configData})
  166. case api.OCIVersion1_1:
  167. config = v1.DescriptorEmptyJSON
  168. artifactType = ComposeProjectArtifactType
  169. // N.B. the descriptor has the data embedded in it
  170. toPush = append(toPush, Pushable{Descriptor: config, Data: make([]byte, len(config.Data))})
  171. default:
  172. return nil, fmt.Errorf("unsupported OCI version: %s", ociCompat)
  173. }
  174. manifest, err := json.Marshal(v1.Manifest{
  175. Versioned: specs.Versioned{SchemaVersion: 2},
  176. MediaType: v1.MediaTypeImageManifest,
  177. ArtifactType: artifactType,
  178. Config: config,
  179. Layers: layers,
  180. Annotations: map[string]string{
  181. "org.opencontainers.image.created": time.Now().Format(time.RFC3339),
  182. },
  183. })
  184. if err != nil {
  185. return nil, err
  186. }
  187. manifestDescriptor := v1.Descriptor{
  188. MediaType: v1.MediaTypeImageManifest,
  189. Digest: digest.FromString(string(manifest)),
  190. Size: int64(len(manifest)),
  191. Annotations: map[string]string{
  192. "com.docker.compose.version": api.ComposeVersion,
  193. },
  194. ArtifactType: artifactType,
  195. }
  196. toPush = append(toPush, Pushable{Descriptor: manifestDescriptor, Data: manifest})
  197. return toPush, nil
  198. }