scan_suggest.go 2.1 KB

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