Skip to content

Commit

Permalink
Handle empty input in AddStringKeyStoreCommand (#39490)
Browse files Browse the repository at this point in the history
This change ensures that we do not make assumptions about the length
of the input that we can read from the stdin. It still consumes only
one line, as the previous implementation

Co-authored-by: Ioannis Kakavas <[email protected]>
  • Loading branch information
dnhatn and jkakavas authored Aug 11, 2020
1 parent 9505212 commit 7a15d2a
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
package org.elasticsearch.common.settings;

import java.io.BufferedReader;
import java.io.CharArrayWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
Expand Down Expand Up @@ -83,8 +84,17 @@ protected void execute(Terminal terminal, OptionSet options, Environment env) th

final char[] value;
if (options.has(stdinOption)) {
BufferedReader stdinReader = new BufferedReader(new InputStreamReader(getStdin(), StandardCharsets.UTF_8));
value = stdinReader.readLine().toCharArray();
try (BufferedReader stdinReader = new BufferedReader(new InputStreamReader(getStdin(), StandardCharsets.UTF_8));
CharArrayWriter writer = new CharArrayWriter()) {
int charInt;
while ((charInt = stdinReader.read()) != -1) {
if ((char) charInt == '\r' || (char) charInt == '\n') {
break;
}
writer.write((char) charInt);
}
value = writer.toCharArray();
}
} else {
value = terminal.readSecret("Enter value for " + setting + ": ");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,27 @@ public void testStdinLong() throws Exception {
assertSecureString("foo", "secret value 2");
}

public void testStdinNoInput() throws Exception {
KeyStoreWrapper.create().save(env.configFile(), new char[0]);
setInput("");
execute("-x", "foo");
assertSecureString("foo", "");
}

public void testStdinInputWithLineBreaks() throws Exception {
KeyStoreWrapper.create().save(env.configFile(), new char[0]);
setInput("Typedthisandhitenter\n");
execute("-x", "foo");
assertSecureString("foo", "Typedthisandhitenter");
}

public void testStdinInputWithCarriageReturn() throws Exception {
KeyStoreWrapper.create().save(env.configFile(), new char[0]);
setInput("Typedthisandhitenter\r");
execute("-x", "foo");
assertSecureString("foo", "Typedthisandhitenter");
}

public void testMissingSettingName() throws Exception {
createKeystore("");
terminal.addTextInput("");
Expand Down

0 comments on commit 7a15d2a

Please sign in to comment.