scan_suggest.go 2.0 KB

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