scan_suggest.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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. "context"
  16. "encoding/json"
  17. "fmt"
  18. "io/ioutil"
  19. "os"
  20. "path/filepath"
  21. "strings"
  22. pluginmanager "github.com/docker/cli/cli-plugins/manager"
  23. "github.com/docker/cli/cli/command"
  24. "github.com/docker/compose-cli/api/config"
  25. )
  26. func displayScanSuggestMsg(ctx context.Context, builtImages []string) {
  27. if len(builtImages) <= 0 {
  28. return
  29. }
  30. if os.Getenv("DOCKER_SCAN_SUGGEST") == "false" {
  31. return
  32. }
  33. if !scanAvailable() || scanAlreadyInvoked(ctx) {
  34. return
  35. }
  36. commands := []string{}
  37. for _, image := range builtImages {
  38. commands = append(commands, fmt.Sprintf("docker scan %s", image))
  39. }
  40. allCommands := strings.Join(commands, ", ")
  41. fmt.Printf("Try scanning the image you have just built to identify vulnerabilities with Docker’s new security tool: %s\n", allCommands)
  42. }
  43. func scanAlreadyInvoked(ctx context.Context) bool {
  44. configDir := config.Dir(ctx)
  45. filename := filepath.Join(configDir, "scan", "config.json")
  46. f, err := os.Stat(filename)
  47. if os.IsNotExist(err) {
  48. return false
  49. }
  50. if f.IsDir() { // should never happen, do not bother user with suggestion if something goes wrong
  51. return true
  52. }
  53. type scanOptin struct {
  54. Optin bool `json:"optin"`
  55. }
  56. data, err := ioutil.ReadFile(filename)
  57. if err != nil {
  58. return true
  59. }
  60. scanConfig := scanOptin{}
  61. err = json.Unmarshal(data, &scanConfig)
  62. if err != nil {
  63. return true
  64. }
  65. return scanConfig.Optin
  66. }
  67. func scanAvailable() bool {
  68. cli, err := command.NewDockerCli()
  69. if err != nil {
  70. return false
  71. }
  72. plugins, err := pluginmanager.ListPlugins(cli, nil)
  73. if err != nil {
  74. return false
  75. }
  76. for _, plugin := range plugins {
  77. if plugin.Name == "scan" {
  78. return true
  79. }
  80. }
  81. return false
  82. }