oci.go 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. /*
  2. Copyright 2020 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 remote
  14. import (
  15. "context"
  16. "encoding/json"
  17. "fmt"
  18. "os"
  19. "path/filepath"
  20. "strconv"
  21. "strings"
  22. "github.com/compose-spec/compose-go/v2/loader"
  23. "github.com/containerd/containerd/v2/core/images"
  24. "github.com/containerd/containerd/v2/core/remotes"
  25. "github.com/distribution/reference"
  26. "github.com/docker/cli/cli/command"
  27. "github.com/docker/compose/v2/internal/oci"
  28. "github.com/docker/compose/v2/pkg/api"
  29. spec "github.com/opencontainers/image-spec/specs-go/v1"
  30. )
  31. const (
  32. OCI_REMOTE_ENABLED = "COMPOSE_EXPERIMENTAL_OCI_REMOTE"
  33. OciPrefix = "oci://"
  34. )
  35. // validatePathInBase ensures a file path is contained within the base directory,
  36. // as OCI artifacts resources must all live within the same folder.
  37. func validatePathInBase(base, unsafePath string) error {
  38. // Reject paths with path separators regardless of OS
  39. if strings.ContainsAny(unsafePath, "\\/") {
  40. return fmt.Errorf("invalid OCI artifact")
  41. }
  42. // Join the base with the untrusted path
  43. targetPath := filepath.Join(base, unsafePath)
  44. // Get the directory of the target path
  45. targetDir := filepath.Dir(targetPath)
  46. // Clean both paths to resolve any .. or . components
  47. cleanBase := filepath.Clean(base)
  48. cleanTargetDir := filepath.Clean(targetDir)
  49. // Check if the target directory is the same as base directory
  50. if cleanTargetDir != cleanBase {
  51. return fmt.Errorf("invalid OCI artifact")
  52. }
  53. return nil
  54. }
  55. func ociRemoteLoaderEnabled() (bool, error) {
  56. if v := os.Getenv(OCI_REMOTE_ENABLED); v != "" {
  57. enabled, err := strconv.ParseBool(v)
  58. if err != nil {
  59. return false, fmt.Errorf("COMPOSE_EXPERIMENTAL_OCI_REMOTE environment variable expects boolean value: %w", err)
  60. }
  61. return enabled, err
  62. }
  63. return true, nil
  64. }
  65. func NewOCIRemoteLoader(dockerCli command.Cli, offline bool, options api.OCIOptions) loader.ResourceLoader {
  66. return ociRemoteLoader{
  67. dockerCli: dockerCli,
  68. offline: offline,
  69. known: map[string]string{},
  70. insecureRegistries: options.InsecureRegistries,
  71. }
  72. }
  73. type ociRemoteLoader struct {
  74. dockerCli command.Cli
  75. offline bool
  76. known map[string]string
  77. insecureRegistries []string
  78. }
  79. func (g ociRemoteLoader) Accept(path string) bool {
  80. return strings.HasPrefix(path, OciPrefix)
  81. }
  82. //nolint:gocyclo
  83. func (g ociRemoteLoader) Load(ctx context.Context, path string) (string, error) {
  84. enabled, err := ociRemoteLoaderEnabled()
  85. if err != nil {
  86. return "", err
  87. }
  88. if !enabled {
  89. return "", fmt.Errorf("OCI remote resource is disabled by %q", OCI_REMOTE_ENABLED)
  90. }
  91. if g.offline {
  92. return "", nil
  93. }
  94. local, ok := g.known[path]
  95. if !ok {
  96. ref, err := reference.ParseDockerRef(path[len(OciPrefix):])
  97. if err != nil {
  98. return "", err
  99. }
  100. resolver := oci.NewResolver(g.dockerCli.ConfigFile(), g.insecureRegistries...)
  101. descriptor, content, err := oci.Get(ctx, resolver, ref)
  102. if err != nil {
  103. return "", fmt.Errorf("failed to pull OCI resource %q: %w", ref, err)
  104. }
  105. cache, err := cacheDir()
  106. if err != nil {
  107. return "", fmt.Errorf("initializing remote resource cache: %w", err)
  108. }
  109. local = filepath.Join(cache, descriptor.Digest.Hex())
  110. if _, err = os.Stat(local); os.IsNotExist(err) {
  111. // a Compose application bundle is published as image index
  112. if images.IsIndexType(descriptor.MediaType) {
  113. var index spec.Index
  114. err = json.Unmarshal(content, &index)
  115. if err != nil {
  116. return "", err
  117. }
  118. found := false
  119. for _, manifest := range index.Manifests {
  120. if manifest.ArtifactType != oci.ComposeProjectArtifactType {
  121. continue
  122. }
  123. found = true
  124. digested, err := reference.WithDigest(ref, manifest.Digest)
  125. if err != nil {
  126. return "", err
  127. }
  128. descriptor, content, err = oci.Get(ctx, resolver, digested)
  129. if err != nil {
  130. return "", fmt.Errorf("failed to pull OCI resource %q: %w", ref, err)
  131. }
  132. }
  133. if !found {
  134. return "", fmt.Errorf("OCI index %s doesn't refer to compose artifacts", ref)
  135. }
  136. }
  137. var manifest spec.Manifest
  138. err = json.Unmarshal(content, &manifest)
  139. if err != nil {
  140. return "", err
  141. }
  142. err = g.pullComposeFiles(ctx, local, manifest, ref, resolver)
  143. if err != nil {
  144. // we need to clean up the directory to be sure we won't let empty files present
  145. _ = os.RemoveAll(local)
  146. return "", err
  147. }
  148. }
  149. g.known[path] = local
  150. }
  151. return filepath.Join(local, "compose.yaml"), nil
  152. }
  153. func (g ociRemoteLoader) Dir(path string) string {
  154. return g.known[path]
  155. }
  156. func (g ociRemoteLoader) pullComposeFiles(ctx context.Context, local string, manifest spec.Manifest, ref reference.Named, resolver remotes.Resolver) error {
  157. err := os.MkdirAll(local, 0o700)
  158. if err != nil {
  159. return err
  160. }
  161. if (manifest.ArtifactType != "" && manifest.ArtifactType != oci.ComposeProjectArtifactType) ||
  162. (manifest.ArtifactType == "" && manifest.Config.MediaType != oci.ComposeEmptyConfigMediaType) {
  163. return fmt.Errorf("%s is not a compose project OCI artifact, but %s", ref.String(), manifest.ArtifactType)
  164. }
  165. for i, layer := range manifest.Layers {
  166. digested, err := reference.WithDigest(ref, layer.Digest)
  167. if err != nil {
  168. return err
  169. }
  170. _, content, err := oci.Get(ctx, resolver, digested)
  171. if err != nil {
  172. return err
  173. }
  174. switch layer.MediaType {
  175. case oci.ComposeYAMLMediaType:
  176. if err := writeComposeFile(layer, i, local, content); err != nil {
  177. return err
  178. }
  179. case oci.ComposeEnvFileMediaType:
  180. if err := writeEnvFile(layer, local, content); err != nil {
  181. return err
  182. }
  183. case oci.ComposeEmptyConfigMediaType:
  184. }
  185. }
  186. return nil
  187. }
  188. func writeComposeFile(layer spec.Descriptor, i int, local string, content []byte) error {
  189. file := "compose.yaml"
  190. if _, ok := layer.Annotations["com.docker.compose.extends"]; ok {
  191. file = layer.Annotations["com.docker.compose.file"]
  192. if err := validatePathInBase(local, file); err != nil {
  193. return err
  194. }
  195. }
  196. f, err := os.OpenFile(filepath.Join(local, file), os.O_RDWR|os.O_CREATE|os.O_APPEND, 0o600)
  197. if err != nil {
  198. return err
  199. }
  200. defer func() { _ = f.Close() }()
  201. if _, ok := layer.Annotations["com.docker.compose.file"]; i > 0 && ok {
  202. _, err := f.Write([]byte("\n---\n"))
  203. if err != nil {
  204. return err
  205. }
  206. }
  207. _, err = f.Write(content)
  208. return err
  209. }
  210. func writeEnvFile(layer spec.Descriptor, local string, content []byte) error {
  211. envfilePath, ok := layer.Annotations["com.docker.compose.envfile"]
  212. if !ok {
  213. return fmt.Errorf("missing annotation com.docker.compose.envfile in layer %q", layer.Digest)
  214. }
  215. if err := validatePathInBase(local, envfilePath); err != nil {
  216. return err
  217. }
  218. otherFile, err := os.Create(filepath.Join(local, envfilePath))
  219. if err != nil {
  220. return err
  221. }
  222. defer func() { _ = otherFile.Close() }()
  223. _, err = otherFile.Write(content)
  224. return err
  225. }
  226. var _ loader.ResourceLoader = ociRemoteLoader{}