publish.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517
  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 compose
  14. import (
  15. "bytes"
  16. "context"
  17. "crypto/sha256"
  18. "encoding/json"
  19. "errors"
  20. "fmt"
  21. "io"
  22. "os"
  23. "github.com/DefangLabs/secret-detector/pkg/scanner"
  24. "github.com/DefangLabs/secret-detector/pkg/secrets"
  25. "github.com/compose-spec/compose-go/v2/loader"
  26. "github.com/compose-spec/compose-go/v2/types"
  27. "github.com/distribution/reference"
  28. "github.com/docker/cli/cli/command"
  29. "github.com/docker/compose/v2/internal/oci"
  30. "github.com/docker/compose/v2/pkg/api"
  31. "github.com/docker/compose/v2/pkg/compose/transform"
  32. "github.com/docker/compose/v2/pkg/progress"
  33. "github.com/docker/compose/v2/pkg/prompt"
  34. "github.com/opencontainers/go-digest"
  35. "github.com/opencontainers/image-spec/specs-go"
  36. v1 "github.com/opencontainers/image-spec/specs-go/v1"
  37. )
  38. func (s *composeService) Publish(ctx context.Context, project *types.Project, repository string, options api.PublishOptions) error {
  39. return progress.RunWithTitle(ctx, func(ctx context.Context) error {
  40. return s.publish(ctx, project, repository, options)
  41. }, s.stdinfo(), "Publishing")
  42. }
  43. //nolint:gocyclo
  44. func (s *composeService) publish(ctx context.Context, project *types.Project, repository string, options api.PublishOptions) error {
  45. project, err := project.WithProfiles([]string{"*"})
  46. if err != nil {
  47. return err
  48. }
  49. accept, err := s.preChecks(project, options)
  50. if err != nil {
  51. return err
  52. }
  53. if !accept {
  54. return nil
  55. }
  56. err = s.Push(ctx, project, api.PushOptions{IgnoreFailures: true, ImageMandatory: true})
  57. if err != nil {
  58. return err
  59. }
  60. named, err := reference.ParseDockerRef(repository)
  61. if err != nil {
  62. return err
  63. }
  64. config := s.dockerCli.ConfigFile()
  65. resolver := oci.NewResolver(config)
  66. var layers []v1.Descriptor
  67. extFiles := map[string]string{}
  68. for _, file := range project.ComposeFiles {
  69. data, err := processFile(ctx, file, project, extFiles)
  70. if err != nil {
  71. return err
  72. }
  73. layerDescriptor := oci.DescriptorForComposeFile(file, data)
  74. layers = append(layers, layerDescriptor)
  75. }
  76. extLayers, err := processExtends(ctx, project, extFiles)
  77. if err != nil {
  78. return err
  79. }
  80. layers = append(layers, extLayers...)
  81. if options.WithEnvironment {
  82. layers = append(layers, envFileLayers(project)...)
  83. }
  84. if options.ResolveImageDigests {
  85. yaml, err := s.generateImageDigestsOverride(ctx, project)
  86. if err != nil {
  87. return err
  88. }
  89. layerDescriptor := oci.DescriptorForComposeFile("image-digests.yaml", yaml)
  90. layers = append(layers, layerDescriptor)
  91. }
  92. w := progress.ContextWriter(ctx)
  93. w.Event(progress.Event{
  94. ID: repository,
  95. Text: "publishing",
  96. Status: progress.Working,
  97. })
  98. if !s.dryRun {
  99. descriptor, err := oci.PushManifest(ctx, resolver, named, layers, options.OCIVersion)
  100. if err != nil {
  101. w.Event(progress.Event{
  102. ID: repository,
  103. Text: "publishing",
  104. Status: progress.Error,
  105. })
  106. return err
  107. }
  108. if options.Application {
  109. manifests := []v1.Descriptor{}
  110. for _, service := range project.Services {
  111. ref, err := reference.ParseDockerRef(service.Image)
  112. if err != nil {
  113. return err
  114. }
  115. manifest, err := oci.Copy(ctx, resolver, ref, named)
  116. if err != nil {
  117. return err
  118. }
  119. manifests = append(manifests, manifest)
  120. }
  121. descriptor.Data = nil
  122. index, err := json.Marshal(v1.Index{
  123. Versioned: specs.Versioned{SchemaVersion: 2},
  124. MediaType: v1.MediaTypeImageIndex,
  125. Manifests: manifests,
  126. Subject: &descriptor,
  127. Annotations: map[string]string{
  128. "com.docker.compose.version": api.ComposeVersion,
  129. },
  130. })
  131. if err != nil {
  132. return err
  133. }
  134. imagesDescriptor := v1.Descriptor{
  135. MediaType: v1.MediaTypeImageIndex,
  136. ArtifactType: oci.ComposeProjectArtifactType,
  137. Digest: digest.FromString(string(index)),
  138. Size: int64(len(index)),
  139. Annotations: map[string]string{
  140. "com.docker.compose.version": api.ComposeVersion,
  141. },
  142. Data: index,
  143. }
  144. err = oci.Push(ctx, resolver, reference.TrimNamed(named), imagesDescriptor)
  145. if err != nil {
  146. return err
  147. }
  148. }
  149. }
  150. w.Event(progress.Event{
  151. ID: repository,
  152. Text: "published",
  153. Status: progress.Done,
  154. })
  155. return nil
  156. }
  157. func processExtends(ctx context.Context, project *types.Project, extFiles map[string]string) ([]v1.Descriptor, error) {
  158. var layers []v1.Descriptor
  159. moreExtFiles := map[string]string{}
  160. for xf, hash := range extFiles {
  161. data, err := processFile(ctx, xf, project, moreExtFiles)
  162. if err != nil {
  163. return nil, err
  164. }
  165. layerDescriptor := oci.DescriptorForComposeFile(hash, data)
  166. layerDescriptor.Annotations["com.docker.compose.extends"] = "true"
  167. layers = append(layers, layerDescriptor)
  168. }
  169. for f, hash := range moreExtFiles {
  170. if _, ok := extFiles[f]; ok {
  171. delete(moreExtFiles, f)
  172. }
  173. extFiles[f] = hash
  174. }
  175. if len(moreExtFiles) > 0 {
  176. extLayers, err := processExtends(ctx, project, moreExtFiles)
  177. if err != nil {
  178. return nil, err
  179. }
  180. layers = append(layers, extLayers...)
  181. }
  182. return layers, nil
  183. }
  184. func processFile(ctx context.Context, file string, project *types.Project, extFiles map[string]string) ([]byte, error) {
  185. f, err := os.ReadFile(file)
  186. if err != nil {
  187. return nil, err
  188. }
  189. base, err := loader.LoadWithContext(ctx, types.ConfigDetails{
  190. WorkingDir: project.WorkingDir,
  191. Environment: project.Environment,
  192. ConfigFiles: []types.ConfigFile{
  193. {
  194. Filename: file,
  195. Content: f,
  196. },
  197. },
  198. }, func(options *loader.Options) {
  199. options.SkipValidation = true
  200. options.SkipExtends = true
  201. options.SkipConsistencyCheck = true
  202. options.ResolvePaths = true
  203. options.Profiles = project.Profiles
  204. })
  205. if err != nil {
  206. return nil, err
  207. }
  208. for name, service := range base.Services {
  209. if service.Extends == nil {
  210. continue
  211. }
  212. xf := service.Extends.File
  213. if xf == "" {
  214. continue
  215. }
  216. if _, err = os.Stat(service.Extends.File); os.IsNotExist(err) {
  217. // No local file, while we loaded the project successfully: This is actually a remote resource
  218. continue
  219. }
  220. hash := fmt.Sprintf("%x.yaml", sha256.Sum256([]byte(xf)))
  221. extFiles[xf] = hash
  222. f, err = transform.ReplaceExtendsFile(f, name, hash)
  223. if err != nil {
  224. return nil, err
  225. }
  226. }
  227. return f, nil
  228. }
  229. func (s *composeService) generateImageDigestsOverride(ctx context.Context, project *types.Project) ([]byte, error) {
  230. project, err := project.WithImagesResolved(ImageDigestResolver(ctx, s.configFile(), s.apiClient()))
  231. if err != nil {
  232. return nil, err
  233. }
  234. override := types.Project{
  235. Services: types.Services{},
  236. }
  237. for name, service := range project.Services {
  238. override.Services[name] = types.ServiceConfig{
  239. Image: service.Image,
  240. }
  241. }
  242. return override.MarshalYAML()
  243. }
  244. //nolint:gocyclo
  245. func (s *composeService) preChecks(project *types.Project, options api.PublishOptions) (bool, error) {
  246. if ok, err := s.checkOnlyBuildSection(project); !ok || err != nil {
  247. return false, err
  248. }
  249. if options.AssumeYes {
  250. return true, nil
  251. }
  252. bindMounts := s.checkForBindMount(project)
  253. if len(bindMounts) > 0 {
  254. fmt.Println("you are about to publish bind mounts declaration within your OCI artifact.\n" +
  255. "only the bind mount declarations will be added to the OCI artifact (not content)\n" +
  256. "please double check that you are not mounting potential user's sensitive directories or data")
  257. for key, val := range bindMounts {
  258. _, _ = fmt.Fprintln(s.dockerCli.Out(), key)
  259. for _, v := range val {
  260. _, _ = fmt.Fprintf(s.dockerCli.Out(), "%s\n", v.String())
  261. }
  262. }
  263. if ok, err := acceptPublishBindMountDeclarations(s.dockerCli); err != nil || !ok {
  264. return false, err
  265. }
  266. }
  267. detectedSecrets, err := s.checkForSensitiveData(project)
  268. if err != nil {
  269. return false, err
  270. }
  271. if len(detectedSecrets) > 0 {
  272. fmt.Println("you are about to publish sensitive data within your OCI artifact.\n" +
  273. "please double check that you are not leaking sensitive data")
  274. for _, val := range detectedSecrets {
  275. _, _ = fmt.Fprintln(s.dockerCli.Out(), val.Type)
  276. _, _ = fmt.Fprintf(s.dockerCli.Out(), "%q: %s\n", val.Key, val.Value)
  277. }
  278. if ok, err := acceptPublishSensitiveData(s.dockerCli); err != nil || !ok {
  279. return false, err
  280. }
  281. }
  282. envVariables, err := s.checkEnvironmentVariables(project, options)
  283. if err != nil {
  284. return false, err
  285. }
  286. if len(envVariables) > 0 {
  287. fmt.Println("you are about to publish environment variables within your OCI artifact.\n" +
  288. "please double check that you are not leaking sensitive data")
  289. for key, val := range envVariables {
  290. _, _ = fmt.Fprintln(s.dockerCli.Out(), "Service/Config ", key)
  291. for k, v := range val {
  292. _, _ = fmt.Fprintf(s.dockerCli.Out(), "%s=%v\n", k, *v)
  293. }
  294. }
  295. if ok, err := acceptPublishEnvVariables(s.dockerCli); err != nil || !ok {
  296. return false, err
  297. }
  298. }
  299. return true, nil
  300. }
  301. func (s *composeService) checkEnvironmentVariables(project *types.Project, options api.PublishOptions) (map[string]types.MappingWithEquals, error) {
  302. envVarList := map[string]types.MappingWithEquals{}
  303. errorList := map[string][]string{}
  304. for _, service := range project.Services {
  305. if len(service.EnvFiles) > 0 {
  306. errorList[service.Name] = append(errorList[service.Name], fmt.Sprintf("service %q has env_file declared.", service.Name))
  307. }
  308. if len(service.Environment) > 0 {
  309. errorList[service.Name] = append(errorList[service.Name], fmt.Sprintf("service %q has environment variable(s) declared.", service.Name))
  310. envVarList[service.Name] = service.Environment
  311. }
  312. }
  313. for _, config := range project.Configs {
  314. if config.Environment != "" {
  315. errorList[config.Name] = append(errorList[config.Name], fmt.Sprintf("config %q is declare as an environment variable.", config.Name))
  316. envVarList[config.Name] = types.NewMappingWithEquals([]string{fmt.Sprintf("%s=%s", config.Name, config.Environment)})
  317. }
  318. }
  319. if !options.WithEnvironment && len(errorList) > 0 {
  320. errorMsgSuffix := "To avoid leaking sensitive data, you must either explicitly allow the sending of environment variables by using the --with-env flag,\n" +
  321. "or remove sensitive data from your Compose configuration"
  322. errorMsg := ""
  323. for _, errors := range errorList {
  324. for _, err := range errors {
  325. errorMsg += fmt.Sprintf("%s\n", err)
  326. }
  327. }
  328. return nil, fmt.Errorf("%s%s", errorMsg, errorMsgSuffix)
  329. }
  330. return envVarList, nil
  331. }
  332. func acceptPublishEnvVariables(cli command.Cli) (bool, error) {
  333. msg := "Are you ok to publish these environment variables? [y/N]: "
  334. confirm, err := prompt.NewPrompt(cli.In(), cli.Out()).Confirm(msg, false)
  335. return confirm, err
  336. }
  337. func acceptPublishSensitiveData(cli command.Cli) (bool, error) {
  338. msg := "Are you ok to publish these sensitive data? [y/N]: "
  339. confirm, err := prompt.NewPrompt(cli.In(), cli.Out()).Confirm(msg, false)
  340. return confirm, err
  341. }
  342. func acceptPublishBindMountDeclarations(cli command.Cli) (bool, error) {
  343. msg := "Are you ok to publish these bind mount declarations? [y/N]: "
  344. confirm, err := prompt.NewPrompt(cli.In(), cli.Out()).Confirm(msg, false)
  345. return confirm, err
  346. }
  347. func envFileLayers(project *types.Project) []v1.Descriptor {
  348. var layers []v1.Descriptor
  349. for _, service := range project.Services {
  350. for _, envFile := range service.EnvFiles {
  351. f, err := os.ReadFile(envFile.Path)
  352. if err != nil {
  353. // if we can't read the file, skip to the next one
  354. continue
  355. }
  356. layerDescriptor := oci.DescriptorForEnvFile(envFile.Path, f)
  357. layers = append(layers, layerDescriptor)
  358. }
  359. }
  360. return layers
  361. }
  362. func (s *composeService) checkOnlyBuildSection(project *types.Project) (bool, error) {
  363. errorList := []string{}
  364. for _, service := range project.Services {
  365. if service.Image == "" && service.Build != nil {
  366. errorList = append(errorList, service.Name)
  367. }
  368. }
  369. if len(errorList) > 0 {
  370. errMsg := "your Compose stack cannot be published as it only contains a build section for service(s):\n"
  371. for _, serviceInError := range errorList {
  372. errMsg += fmt.Sprintf("- %q\n", serviceInError)
  373. }
  374. return false, errors.New(errMsg)
  375. }
  376. return true, nil
  377. }
  378. func (s *composeService) checkForBindMount(project *types.Project) map[string][]types.ServiceVolumeConfig {
  379. allFindings := map[string][]types.ServiceVolumeConfig{}
  380. for serviceName, config := range project.Services {
  381. bindMounts := []types.ServiceVolumeConfig{}
  382. for _, volume := range config.Volumes {
  383. if volume.Type == types.VolumeTypeBind {
  384. bindMounts = append(bindMounts, volume)
  385. }
  386. }
  387. if len(bindMounts) > 0 {
  388. allFindings[serviceName] = bindMounts
  389. }
  390. }
  391. return allFindings
  392. }
  393. func (s *composeService) checkForSensitiveData(project *types.Project) ([]secrets.DetectedSecret, error) {
  394. var allFindings []secrets.DetectedSecret
  395. scan := scanner.NewDefaultScanner()
  396. // Check all compose files
  397. for _, file := range project.ComposeFiles {
  398. in, err := composeFileAsByteReader(file, project)
  399. if err != nil {
  400. return nil, err
  401. }
  402. findings, err := scan.ScanReader(in)
  403. if err != nil {
  404. return nil, fmt.Errorf("failed to scan compose file %s: %w", file, err)
  405. }
  406. allFindings = append(allFindings, findings...)
  407. }
  408. for _, service := range project.Services {
  409. // Check env files
  410. for _, envFile := range service.EnvFiles {
  411. findings, err := scan.ScanFile(envFile.Path)
  412. if err != nil {
  413. return nil, fmt.Errorf("failed to scan env file %s: %w", envFile.Path, err)
  414. }
  415. allFindings = append(allFindings, findings...)
  416. }
  417. }
  418. // Check configs defined by files
  419. for _, config := range project.Configs {
  420. if config.File != "" {
  421. findings, err := scan.ScanFile(config.File)
  422. if err != nil {
  423. return nil, fmt.Errorf("failed to scan config file %s: %w", config.File, err)
  424. }
  425. allFindings = append(allFindings, findings...)
  426. }
  427. }
  428. // Check secrets defined by files
  429. for _, secret := range project.Secrets {
  430. if secret.File != "" {
  431. findings, err := scan.ScanFile(secret.File)
  432. if err != nil {
  433. return nil, fmt.Errorf("failed to scan secret file %s: %w", secret.File, err)
  434. }
  435. allFindings = append(allFindings, findings...)
  436. }
  437. }
  438. return allFindings, nil
  439. }
  440. func composeFileAsByteReader(filePath string, project *types.Project) (io.Reader, error) {
  441. composeFile, err := os.ReadFile(filePath)
  442. if err != nil {
  443. return nil, fmt.Errorf("failed to open compose file %s: %w", filePath, err)
  444. }
  445. base, err := loader.LoadWithContext(context.TODO(), types.ConfigDetails{
  446. WorkingDir: project.WorkingDir,
  447. Environment: project.Environment,
  448. ConfigFiles: []types.ConfigFile{
  449. {
  450. Filename: filePath,
  451. Content: composeFile,
  452. },
  453. },
  454. }, func(options *loader.Options) {
  455. options.SkipValidation = true
  456. options.SkipExtends = true
  457. options.SkipConsistencyCheck = true
  458. options.ResolvePaths = true
  459. options.SkipInterpolation = true
  460. options.SkipResolveEnvironment = true
  461. })
  462. if err != nil {
  463. return nil, err
  464. }
  465. in, err := base.MarshalYAML()
  466. if err != nil {
  467. return nil, err
  468. }
  469. return bytes.NewBuffer(in), nil
  470. }