scan_suggest.go 2.0 KB

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