push.go 7.8 KB

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