github.com/turbot/steampipe@v1.7.0-rc.0.0.20240517123944-7cef272d4458/pkg/db/db_local/password.go (about) 1 package db_local 2 3 import ( 4 "encoding/json" 5 "os" 6 "strings" 7 8 "github.com/google/uuid" 9 filehelpers "github.com/turbot/go-kit/files" 10 "github.com/turbot/steampipe/pkg/filepaths" 11 "github.com/turbot/steampipe/pkg/utils" 12 ) 13 14 // Passwords :: structure for working with DB passwords 15 type Passwords struct { 16 Root string 17 Steampipe string 18 } 19 20 func writePasswordFile(password string) error { 21 return os.WriteFile(filepaths.GetPasswordFileLocation(), []byte(password), 0600) 22 } 23 24 // readPasswordFile reads the password file and returns it contents. 25 // the password file could not be found, then it generates a new 26 // password and writes it to the password file, before returning it 27 func readPasswordFile() (string, error) { 28 if !filehelpers.FileExists(filepaths.GetPasswordFileLocation()) { 29 p := generatePassword() 30 if err := writePasswordFile(p); err != nil { 31 return "", err 32 } 33 return p, nil 34 } 35 contentBytes, err := os.ReadFile(filepaths.GetPasswordFileLocation()) 36 if err != nil { 37 return "", err 38 } 39 return strings.TrimSpace(string(contentBytes)), nil 40 } 41 42 func generatePassword() string { 43 // Create a simple, random password of the form f9fe-442f-90fb 44 // Simple to read / write, and has a strength rating of 4 per https://lowe.github.io/tryzxcvbn/ 45 // Yes, this UUIDv4 does always include a 4, but good enough for our needs. 46 u, err := uuid.NewRandom() 47 if err != nil { 48 // Should never happen? 49 panic(err) 50 } 51 s := u.String() 52 return strings.ReplaceAll(s[9:23], "-", "_") 53 } 54 55 func migrateLegacyPasswordFile() error { 56 utils.LogTime("db_local.migrateLegacyPasswordFile start") 57 defer utils.LogTime("db_local.migrateLegacyPasswordFile end") 58 if filehelpers.FileExists(filepaths.GetLegacyPasswordFileLocation()) { 59 p, err := getLegacyPasswords() 60 if err != nil { 61 return err 62 } 63 os.Remove(filepaths.GetLegacyPasswordFileLocation()) 64 return writePasswordFile(p.Steampipe) 65 } 66 return nil 67 } 68 69 func getLegacyPasswords() (*Passwords, error) { 70 contentBytes, err := os.ReadFile(filepaths.GetLegacyPasswordFileLocation()) 71 if err != nil { 72 return nil, err 73 } 74 var passwords = new(Passwords) 75 err = json.Unmarshal(contentBytes, passwords) 76 if err != nil { 77 return nil, err 78 } 79 return passwords, nil 80 }