publish.go 15 KB

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