Skip to content

Commit 55a8bcd

Browse files
author
Andrew Lytvynov
committed
mfa: strip trailing newline when reading TOTP codes
The newline should not be interpreted as part of the code (or any `prompt.Input` result).
1 parent 11c62e8 commit 55a8bcd

File tree

2 files changed

+61
-1
lines changed

2 files changed

+61
-1
lines changed

Diff for: lib/utils/prompt/confirmation.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -77,5 +77,5 @@ func Input(ctx context.Context, out io.Writer, in *ContextReader, question strin
7777
if err != nil {
7878
return "", trace.WrapWithMessage(err, "failed reading prompt response")
7979
}
80-
return string(answer), nil
80+
return strings.TrimSpace(string(answer)), nil
8181
}

Diff for: lib/utils/prompt/confirmation_test.go

+60
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
/*
2+
Copyright 2021 Gravitational, Inc.
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
*/
16+
17+
package prompt
18+
19+
import (
20+
"context"
21+
"io"
22+
"testing"
23+
24+
"github.com/stretchr/testify/require"
25+
)
26+
27+
func TestInput(t *testing.T) {
28+
t.Parallel()
29+
30+
out, in := io.Pipe()
31+
defer out.Close()
32+
write := func(t *testing.T, s string) {
33+
_, err := in.Write([]byte(s))
34+
require.NoError(t, err)
35+
}
36+
37+
r := NewContextReader(out)
38+
ctx := context.Background()
39+
40+
t.Run("no whitespace", func(t *testing.T) {
41+
go write(t, "hi")
42+
got, err := Input(ctx, io.Discard, r, "")
43+
require.NoError(t, err)
44+
require.Equal(t, got, "hi")
45+
})
46+
47+
t.Run("with whitespace", func(t *testing.T) {
48+
go write(t, "hey\n")
49+
got, err := Input(ctx, io.Discard, r, "")
50+
require.NoError(t, err)
51+
require.Equal(t, got, "hey")
52+
})
53+
54+
t.Run("closed input", func(t *testing.T) {
55+
require.NoError(t, in.Close())
56+
got, err := Input(ctx, io.Discard, r, "")
57+
require.ErrorIs(t, err, io.EOF)
58+
require.Empty(t, got)
59+
})
60+
}

0 commit comments

Comments
 (0)