Skip to content

Commit

Permalink
Merge pull request #83 from hashicorp/jasonpilz/HCPCP-1620-respect-in…
Browse files Browse the repository at this point in the history
…terrupt-readsecret

HCPCP-1620: ReadSecret: Respect Ctrl-C Interrupt
  • Loading branch information
jasonpilz authored May 20, 2024
2 parents ad523bc + 0eae269 commit ce3d8e5
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 2 deletions.
41 changes: 40 additions & 1 deletion internal/pkg/iostreams/io.go
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,46 @@ func (s *system) ReadSecret() ([]byte, error) {
return nil, fmt.Errorf("prompting is disabled")
}

return term.ReadPassword(int(s.in.Fd()))
fd := int(s.in.Fd())

// Store and restore the terminal status on interruptions to
// avoid that the terminal remains in the password state
// This is necessary as for https://github.com/golang/go/issues/31180
oldState, err := term.GetState(fd)
if err != nil {
return nil, err
}

type Buffer struct {
Buffer []byte
Error error
}
errorChannel := make(chan Buffer, 1)
doneChannel := make(chan struct{})
defer close(doneChannel)

// Cancelled context restores the terminal, otherwise the no-echo mode would remain intact
go func() {
select {
case <-doneChannel:
return
case <-s.ctx.Done():
}

if oldState != nil {
_ = term.Restore(fd, oldState)
}
errorChannel <- Buffer{Buffer: make([]byte, 0), Error: context.Cause(s.ctx)}
}()

go func() {
buf, err := term.ReadPassword(fd)
errorChannel <- Buffer{Buffer: buf, Error: err}
}()

buf := <-errorChannel

return buf.Buffer, buf.Error
}

func (s *system) PromptConfirm(prompt string) (confirmed bool, err error) {
Expand Down
2 changes: 1 addition & 1 deletion main.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ func main() {
func realMain() int {
args := os.Args[1:]

// Listen for interupts
// Listen for interrupts
shutdownCtx, shutdown := context.WithCancelCause(context.Background())
defer shutdown(nil)
go func() {
Expand Down

0 comments on commit ce3d8e5

Please sign in to comment.