Skip to content

Commit

Permalink
Move the prompting/confirmation down into the password implementations.
Browse files Browse the repository at this point in the history
We don't need to read from stdin or the env var twice :)

Signed-off-by: Dan Lorenc <[email protected]>
  • Loading branch information
Dan Lorenc committed Aug 19, 2021
1 parent 001d55f commit 6eac142
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 25 deletions.
49 changes: 26 additions & 23 deletions cmd/cosign/cli/generate_key_pair.go
Original file line number Diff line number Diff line change
Expand Up @@ -121,30 +121,11 @@ func GenerateKeyPairCmd(ctx context.Context, kmsVal string, args []string) error
}

func GetPass(confirm bool) ([]byte, error) {
read := Read()
fmt.Fprint(os.Stderr, "Enter password for private key: ")
pw1, err := read()
fmt.Fprintln(os.Stderr)
if err != nil {
return nil, err
}
if !confirm {
return pw1, nil
}
fmt.Fprint(os.Stderr, "Enter again: ")
pw2, err := read()
fmt.Fprintln(os.Stderr)
if err != nil {
return nil, err
}

if string(pw1) != string(pw2) {
return nil, errors.New("passwords do not match")
}
return pw1, nil
read := Read(confirm)
return read()
}

func readPasswordFn() func() ([]byte, error) {
func readPasswordFn(confirm bool) func() ([]byte, error) {
pw, ok := os.LookupEnv("COSIGN_PASSWORD")
switch {
case ok:
Expand All @@ -153,7 +134,7 @@ func readPasswordFn() func() ([]byte, error) {
}
case term.IsTerminal(0):
return func() ([]byte, error) {
return term.ReadPassword(0)
return getPassFromTerm(confirm)
}
// Handle piped in passwords.
default:
Expand All @@ -162,3 +143,25 @@ func readPasswordFn() func() ([]byte, error) {
}
}
}

func getPassFromTerm(confirm bool) ([]byte, error) {
fmt.Fprint(os.Stderr, "Enter password for private key: ")
pw1, err := term.ReadPassword(0)
if err != nil {
return nil, err
}
if !confirm {
return pw1, nil
}
fmt.Fprint(os.Stderr, "Enter again: ")
pw2, err := term.ReadPassword(0)
fmt.Fprintln(os.Stderr)
if err != nil {
return nil, err
}

if string(pw1) != string(pw2) {
return nil, errors.New("passwords do not match")
}
return pw1, nil
}
4 changes: 2 additions & 2 deletions cmd/cosign/cli/generate_key_pair_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ import (
func TestReadPasswordFn_env(t *testing.T) {
os.Setenv("COSIGN_PASSWORD", "foo")
defer os.Unsetenv("COSIGN_PASSWORD")
b, err := readPasswordFn()()
b, err := readPasswordFn(true)()
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
Expand All @@ -37,7 +37,7 @@ func TestReadPasswordFn_env(t *testing.T) {
func TestReadPasswordFn_envEmptyVal(t *testing.T) {
os.Setenv("COSIGN_PASSWORD", "")
defer os.Unsetenv("COSIGN_PASSWORD")
b, err := readPasswordFn()()
b, err := readPasswordFn(true)()
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
Expand Down

0 comments on commit 6eac142

Please sign in to comment.