pat_suggest.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. "fmt"
  16. "os"
  17. "strings"
  18. "github.com/docker/cli/cli/config"
  19. "github.com/docker/docker/registry"
  20. "github.com/google/uuid"
  21. )
  22. const (
  23. // patSuggestMsg is a message to suggest the use of PAT (personal access tokens).
  24. patSuggestMsg = `Logging in with your password grants your terminal complete access to your account.
  25. For better security, log in with a limited-privilege personal access token. Learn more at https://docs.docker.com/docker-hub/access-tokens/`
  26. // patPrefix represents a docker personal access token prefix.
  27. patPrefix = "dckrp_"
  28. )
  29. // DisplayPATSuggestMsg displays a message suggesting users to use PATs instead of passwords to reduce scope.
  30. func DisplayPATSuggestMsg(cmdArgs []string) {
  31. if os.Getenv("DOCKER_PAT_SUGGEST") == "false" {
  32. return
  33. }
  34. if !isUsingDefaultRegistry(cmdArgs) {
  35. return
  36. }
  37. authCfg, err := config.LoadDefaultConfigFile(os.Stderr).GetAuthConfig(registry.IndexServer)
  38. if err != nil {
  39. return
  40. }
  41. if !isUsingPassword(authCfg.Password) {
  42. return
  43. }
  44. fmt.Fprintf(os.Stderr, "\n"+patSuggestMsg+"\n")
  45. }
  46. func isUsingDefaultRegistry(cmdArgs []string) bool {
  47. for i := 1; i < len(cmdArgs); i++ {
  48. if strings.HasPrefix(cmdArgs[i], "-") {
  49. i++
  50. continue
  51. }
  52. return cmdArgs[i] == registry.IndexServer
  53. }
  54. return true
  55. }
  56. func isUsingPassword(pass string) bool {
  57. if _, err := uuid.Parse(pass); err == nil {
  58. return false
  59. }
  60. if strings.HasPrefix(pass, patPrefix) {
  61. return false
  62. }
  63. return true
  64. }