publish.go 14 KB

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