Skip to content

Commit 7a15d2a

Browse files
dnhatnjkakavas
andauthored
Handle empty input in AddStringKeyStoreCommand (#39490)
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]>
1 parent 9505212 commit 7a15d2a

File tree

2 files changed

+33
-2
lines changed

2 files changed

+33
-2
lines changed

server/src/main/java/org/elasticsearch/common/settings/AddStringKeyStoreCommand.java

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
package org.elasticsearch.common.settings;
2121

2222
import java.io.BufferedReader;
23+
import java.io.CharArrayWriter;
2324
import java.io.InputStream;
2425
import java.io.InputStreamReader;
2526
import java.nio.charset.StandardCharsets;
@@ -83,8 +84,17 @@ protected void execute(Terminal terminal, OptionSet options, Environment env) th
8384

8485
final char[] value;
8586
if (options.has(stdinOption)) {
86-
BufferedReader stdinReader = new BufferedReader(new InputStreamReader(getStdin(), StandardCharsets.UTF_8));
87-
value = stdinReader.readLine().toCharArray();
87+
try (BufferedReader stdinReader = new BufferedReader(new InputStreamReader(getStdin(), StandardCharsets.UTF_8));
88+
CharArrayWriter writer = new CharArrayWriter()) {
89+
int charInt;
90+
while ((charInt = stdinReader.read()) != -1) {
91+
if ((char) charInt == '\r' || (char) charInt == '\n') {
92+
break;
93+
}
94+
writer.write((char) charInt);
95+
}
96+
value = writer.toCharArray();
97+
}
8898
} else {
8999
value = terminal.readSecret("Enter value for " + setting + ": ");
90100
}

server/src/test/java/org/elasticsearch/common/settings/AddStringKeyStoreCommandTests.java

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,27 @@ public void testStdinLong() throws Exception {
134134
assertSecureString("foo", "secret value 2");
135135
}
136136

137+
public void testStdinNoInput() throws Exception {
138+
KeyStoreWrapper.create().save(env.configFile(), new char[0]);
139+
setInput("");
140+
execute("-x", "foo");
141+
assertSecureString("foo", "");
142+
}
143+
144+
public void testStdinInputWithLineBreaks() throws Exception {
145+
KeyStoreWrapper.create().save(env.configFile(), new char[0]);
146+
setInput("Typedthisandhitenter\n");
147+
execute("-x", "foo");
148+
assertSecureString("foo", "Typedthisandhitenter");
149+
}
150+
151+
public void testStdinInputWithCarriageReturn() throws Exception {
152+
KeyStoreWrapper.create().save(env.configFile(), new char[0]);
153+
setInput("Typedthisandhitenter\r");
154+
execute("-x", "foo");
155+
assertSecureString("foo", "Typedthisandhitenter");
156+
}
157+
137158
public void testMissingSettingName() throws Exception {
138159
createKeystore("");
139160
terminal.addTextInput("");

0 commit comments

Comments
 (0)