Skip to content

Commit

Permalink
mfa: strip trailing newline when reading TOTP codes (#6948)
Browse files Browse the repository at this point in the history
The newline should not be interpreted as part of the code (or any
`prompt.Input` result).
  • Loading branch information
Andrew Lytvynov committed May 19, 2021
1 parent 93814d7 commit 9d4b4cf
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 1 deletion.
2 changes: 1 addition & 1 deletion lib/utils/prompt/confirmation.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,5 +77,5 @@ func Input(ctx context.Context, out io.Writer, in *ContextReader, question strin
if err != nil {
return "", trace.WrapWithMessage(err, "failed reading prompt response")
}
return string(answer), nil
return strings.TrimSpace(string(answer)), nil
}
61 changes: 61 additions & 0 deletions lib/utils/prompt/confirmation_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
/*
Copyright 2021 Gravitational, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package prompt

import (
"context"
"io"
"io/ioutil"
"testing"

"github.com/stretchr/testify/require"
)

func TestInput(t *testing.T) {
t.Parallel()

out, in := io.Pipe()
t.Cleanup(func() { out.Close() })
write := func(t *testing.T, s string) {
_, err := in.Write([]byte(s))
require.NoError(t, err)
}

r := NewContextReader(out)
ctx := context.Background()

t.Run("no whitespace", func(t *testing.T) {
go write(t, "hi")
got, err := Input(ctx, ioutil.Discard, r, "")
require.NoError(t, err)
require.Equal(t, got, "hi")
})

t.Run("with whitespace", func(t *testing.T) {
go write(t, "hey\n")
got, err := Input(ctx, ioutil.Discard, r, "")
require.NoError(t, err)
require.Equal(t, got, "hey")
})

t.Run("closed input", func(t *testing.T) {
require.NoError(t, in.Close())
got, err := Input(ctx, ioutil.Discard, r, "")
require.ErrorIs(t, err, io.EOF)
require.Empty(t, got)
})
}

0 comments on commit 9d4b4cf

Please sign in to comment.