GetMasterKey returns the cached master key, prompting for it if necessary.
()
| 30 | |
| 31 | // GetMasterKey returns the cached master key, prompting for it if necessary. |
| 32 | func GetMasterKey() ([]byte, error) { |
| 33 | masterKeyMu.Lock() |
| 34 | defer masterKeyMu.Unlock() |
| 35 | |
| 36 | if len(masterKey) > 0 { |
| 37 | return masterKey, nil |
| 38 | } |
| 39 | |
| 40 | // Try environment variable first |
| 41 | if envKey := os.Getenv(keyEnvVar); envKey != "" { |
| 42 | key, err := deriveKey([]byte(envKey)) |
| 43 | if err != nil { |
| 44 | return nil, err |
| 45 | } |
| 46 | masterKey = key |
| 47 | return masterKey, nil |
| 48 | } |
| 49 | |
| 50 | // Prompt interactively |
| 51 | fmt.Print("Enter master password: ") |
| 52 | pwdBytes, err := term.ReadPassword(int(os.Stdin.Fd())) |
| 53 | fmt.Println() |
| 54 | if err != nil { |
| 55 | return nil, fmt.Errorf("failed to read master password: %w", err) |
| 56 | } |
| 57 | if len(pwdBytes) == 0 { |
| 58 | return nil, nil |
| 59 | } |
| 60 | |
| 61 | key, err := deriveKey(pwdBytes) |
| 62 | for i := range pwdBytes { |
| 63 | pwdBytes[i] = 0 |
| 64 | } |
| 65 | if err != nil { |
| 66 | return nil, err |
| 67 | } |
| 68 | masterKey = key |
| 69 | return masterKey, nil |
| 70 | } |
| 71 | |
| 72 | // GetCachedMasterKey returns the master key only if already cached or available |
| 73 | // via the environment variable, without prompting interactively. |