-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathpassword.go
More file actions
90 lines (72 loc) · 1.99 KB
/
Copy pathpassword.go
File metadata and controls
90 lines (72 loc) · 1.99 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package main
import (
"fmt"
"os"
"sync"
"golang.org/x/term"
)
var (
// Cache the password for the duration of the program execution
cachedPassword string
passwordMu sync.Mutex
passwordSet bool
)
// PromptPassword prompts the user to enter a password from stdin without echoing.
// It uses the golang.org/x/term package for secure terminal input.
func PromptPassword() (string, error) {
fmt.Fprint(os.Stderr, "Enter password: ")
// Read password without echoing to terminal
passwordBytes, err := term.ReadPassword(int(os.Stdin.Fd()))
fmt.Fprintln(os.Stderr) // Print newline after password input
if err != nil {
return "", fmt.Errorf("failed to read password: %w", err)
}
if len(passwordBytes) == 0 {
return "", fmt.Errorf("password cannot be empty")
}
return string(passwordBytes), nil
}
// GetPassword returns the cached password or prompts for it if not set.
// The password is cached in memory for the duration of the program execution
// to avoid prompting multiple times for a single command.
func GetPassword() (string, error) {
passwordMu.Lock()
defer passwordMu.Unlock()
if passwordSet {
return cachedPassword, nil
}
password, err := PromptPassword()
if err != nil {
return "", err
}
// Validate minimum length
if len(password) < 12 {
return "", fmt.Errorf("password must be at least 12 characters long")
}
cachedPassword = password
passwordSet = true
return password, nil
}
// ClearPasswordCache clears the cached password from memory.
// This is primarily useful for testing.
func ClearPasswordCache() {
passwordMu.Lock()
defer passwordMu.Unlock()
// Zero out the password in memory
if cachedPassword != "" {
b := []byte(cachedPassword)
for i := range b {
b[i] = 0
}
cachedPassword = ""
}
passwordSet = false
}
// SetPasswordForTesting sets a password without prompting.
// This should only be used in tests.
func SetPasswordForTesting(password string) {
passwordMu.Lock()
defer passwordMu.Unlock()
cachedPassword = password
passwordSet = true
}