push.go 7.5 KB

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