scan_suggest.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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 utils
  14. import (
  15. "encoding/json"
  16. "fmt"
  17. "io/ioutil"
  18. "os"
  19. "path/filepath"
  20. pluginmanager "github.com/docker/cli/cli-plugins/manager"
  21. "github.com/docker/cli/cli/command"
  22. cliConfig "github.com/docker/cli/cli/config"
  23. )
  24. // ScanSuggestMsg display a message after a successful build to suggest use of `docker scan` command
  25. const ScanSuggestMsg = "Use 'docker scan' to run Snyk tests against images to find vulnerabilities and learn how to fix them"
  26. // DisplayScanSuggestMsg displlay a message suggesting users can scan new image
  27. func DisplayScanSuggestMsg() {
  28. if os.Getenv("DOCKER_SCAN_SUGGEST") == "false" {
  29. return
  30. }
  31. if !scanAvailable() {
  32. return
  33. }
  34. if scanAlreadyInvoked() {
  35. return
  36. }
  37. fmt.Fprintf(os.Stderr, "\n"+ScanSuggestMsg+"\n")
  38. }
  39. func scanAlreadyInvoked() bool {
  40. filename := filepath.Join(cliConfig.Dir(), "scan", "config.json")
  41. f, err := os.Stat(filename)
  42. if os.IsNotExist(err) {
  43. return false
  44. }
  45. if f.IsDir() { // should never happen, do not bother user with suggestion if something goes wrong
  46. return true
  47. }
  48. type scanOptin struct {
  49. Optin bool `json:"optin"`
  50. }
  51. data, err := ioutil.ReadFile(filename)
  52. if err != nil {
  53. return true
  54. }
  55. scanConfig := scanOptin{}
  56. err = json.Unmarshal(data, &scanConfig)
  57. if err != nil {
  58. return true
  59. }
  60. return scanConfig.Optin
  61. }
  62. func scanAvailable() bool {
  63. cli, err := command.NewDockerCli()
  64. if err != nil {
  65. return false
  66. }
  67. plugins, err := pluginmanager.ListPlugins(cli, nil)
  68. if err != nil {
  69. return false
  70. }
  71. for _, plugin := range plugins {
  72. if plugin.Name == "scan" {
  73. return true
  74. }
  75. }
  76. return false
  77. }