-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathaskpass.go
89 lines (78 loc) · 2.22 KB
/
askpass.go
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
package keyring
import (
"errors"
"fmt"
"os"
"runtime"
"strings"
"golang.org/x/term"
)
// AskPass defines basic interface to retrieve passphrase.
type AskPass interface {
GetPass() (string, error)
NewPass() (string, error)
}
func withTerminal(f func(in, out *os.File) error) error {
if runtime.GOOS == "windows" {
in, err := os.OpenFile("CONIN$", os.O_RDWR, 0)
if err != nil {
return err
}
defer in.Close()
out, err := os.OpenFile("CONOUT$", os.O_WRONLY, 0)
if err != nil {
return err
}
defer out.Close()
return f(in, out)
} else if tty, err := os.OpenFile("/dev/tty", os.O_RDWR, 0); err == nil {
defer tty.Close()
return f(tty, tty)
} else if term.IsTerminal(int(os.Stdin.Fd())) {
return f(os.Stdin, os.Stdin)
} else { //nolint revive
return fmt.Errorf("standard input is not a terminal, and /dev/tty is not available: %v", err)
}
}
// AskPassWithTerminal implements AskPass and uses tty to retrieve passphrase.
// @todo support pipe and stdin
type AskPassWithTerminal struct{}
// GetPass implements AskPass interface.
func (a AskPassWithTerminal) GetPass() (string, error) {
return a.readPass("Enter passphrase to unlock the keyring: ")
}
// NewPass implements AskPass interface.
func (a AskPassWithTerminal) NewPass() (string, error) {
pass1, err := a.readPass("Enter passphrase for a new keyring: ")
if err != nil {
return "", err
}
pass2, err := a.readPass("Confirm passphrase: ")
if err != nil {
return "", err
}
if pass1 != pass2 {
return "", errors.New("the passphrases don't match")
}
return pass1, nil
}
func (a AskPassWithTerminal) readPass(prompt string) (string, error) {
var bytePassword []byte
var err error
err = withTerminal(func(in, _ *os.File) error {
fmt.Print(prompt)
bytePassword, err = term.ReadPassword(int(in.Fd()))
fmt.Println()
return err
})
if err != nil {
return "", err
}
return strings.TrimSpace(string(bytePassword)), nil
}
// AskPassConstFlow implements AskPass and returns constant.
type AskPassConstFlow string
// GetPass implements AskPass interface.
func (a AskPassConstFlow) GetPass() (string, error) { return string(a), nil }
// NewPass implements AskPass interface.
func (a AskPassConstFlow) NewPass() (string, error) { return string(a), nil }