summaryrefslogtreecommitdiff
path: root/qa/evil-tests/src/test/java/org/elasticsearch/common/cli/CheckFileCommandTests.java
blob: 95d0789fbf8b88fa9e2e039e255a9373351f9399 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
/*
 * Licensed to Elasticsearch under one or more contributor
 * license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright
 * ownership. Elasticsearch licenses this file to you 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 org.elasticsearch.common.cli;

import com.google.common.jimfs.Configuration;
import com.google.common.jimfs.Jimfs;

import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.util.set.Sets;
import org.elasticsearch.env.Environment;
import org.elasticsearch.test.ESTestCase;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileSystem;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.GroupPrincipal;
import java.nio.file.attribute.PosixFileAttributeView;
import java.nio.file.attribute.PosixFileAttributes;
import java.nio.file.attribute.PosixFilePermission;
import java.nio.file.attribute.UserPrincipal;
import java.util.Set;

import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;

/**
 *
 */
public class CheckFileCommandTests extends ESTestCase {

    private CliToolTestCase.CaptureOutputTerminal captureOutputTerminal = new CliToolTestCase.CaptureOutputTerminal();

    private Configuration jimFsConfiguration = Configuration.unix().toBuilder().setAttributeViews("basic", "owner", "posix", "unix").build();
    private Configuration jimFsConfigurationWithoutPermissions = randomBoolean() ? Configuration.unix().toBuilder().setAttributeViews("basic").build() : Configuration.windows();

    private enum Mode {
        CHANGE, KEEP, DISABLED
    }

    public void testThatCommandLogsErrorMessageOnFail() throws Exception {
        executeCommand(jimFsConfiguration, new PermissionCheckFileCommand(createTempDir(), captureOutputTerminal, Mode.CHANGE));
        assertThat(captureOutputTerminal.getTerminalOutput(), hasItem(containsString("Please ensure that the user account running Elasticsearch has read access to this file")));
    }

    public void testThatCommandLogsNothingWhenPermissionRemains() throws Exception {
        executeCommand(jimFsConfiguration, new PermissionCheckFileCommand(createTempDir(), captureOutputTerminal, Mode.KEEP));
        assertThat(captureOutputTerminal.getTerminalOutput(), hasSize(0));
    }

    public void testThatCommandLogsNothingWhenDisabled() throws Exception {
        executeCommand(jimFsConfiguration, new PermissionCheckFileCommand(createTempDir(), captureOutputTerminal, Mode.DISABLED));
        assertThat(captureOutputTerminal.getTerminalOutput(), hasSize(0));
    }

    public void testThatCommandLogsNothingIfFilesystemDoesNotSupportPermissions() throws Exception {
        executeCommand(jimFsConfigurationWithoutPermissions, new PermissionCheckFileCommand(createTempDir(), captureOutputTerminal, Mode.DISABLED));
        assertThat(captureOutputTerminal.getTerminalOutput(), hasSize(0));
    }

    public void testThatCommandLogsOwnerChange() throws Exception {
        executeCommand(jimFsConfiguration, new OwnerCheckFileCommand(createTempDir(), captureOutputTerminal, Mode.CHANGE));
        assertThat(captureOutputTerminal.getTerminalOutput(), hasItem(allOf(containsString("Owner of file ["), containsString("] used to be ["), containsString("], but now is ["))));
    }

    public void testThatCommandLogsNothingIfOwnerRemainsSame() throws Exception {
        executeCommand(jimFsConfiguration, new OwnerCheckFileCommand(createTempDir(), captureOutputTerminal, Mode.KEEP));
        assertThat(captureOutputTerminal.getTerminalOutput(), hasSize(0));
    }

    public void testThatCommandLogsNothingIfOwnerIsDisabled() throws Exception {
        executeCommand(jimFsConfiguration, new OwnerCheckFileCommand(createTempDir(), captureOutputTerminal, Mode.DISABLED));
        assertThat(captureOutputTerminal.getTerminalOutput(), hasSize(0));
    }

    public void testThatCommandLogsNothingIfFileSystemDoesNotSupportOwners() throws Exception {
        executeCommand(jimFsConfigurationWithoutPermissions, new OwnerCheckFileCommand(createTempDir(), captureOutputTerminal, Mode.DISABLED));
        assertThat(captureOutputTerminal.getTerminalOutput(), hasSize(0));
    }

    public void testThatCommandLogsIfGroupChanges() throws Exception {
        executeCommand(jimFsConfiguration, new GroupCheckFileCommand(createTempDir(), captureOutputTerminal, Mode.CHANGE));
        assertThat(captureOutputTerminal.getTerminalOutput(), hasItem(allOf(containsString("Group of file ["), containsString("] used to be ["), containsString("], but now is ["))));
    }

    public void testThatCommandLogsNothingIfGroupRemainsSame() throws Exception {
        executeCommand(jimFsConfiguration, new GroupCheckFileCommand(createTempDir(), captureOutputTerminal, Mode.KEEP));
        assertThat(captureOutputTerminal.getTerminalOutput(), hasSize(0));
    }

    public void testThatCommandLogsNothingIfGroupIsDisabled() throws Exception {
        executeCommand(jimFsConfiguration, new GroupCheckFileCommand(createTempDir(), captureOutputTerminal, Mode.DISABLED));
        assertThat(captureOutputTerminal.getTerminalOutput(), hasSize(0));
    }

    public void testThatCommandLogsNothingIfFileSystemDoesNotSupportGroups() throws Exception {
        executeCommand(jimFsConfigurationWithoutPermissions, new GroupCheckFileCommand(createTempDir(), captureOutputTerminal, Mode.DISABLED));
        assertThat(captureOutputTerminal.getTerminalOutput(), hasSize(0));
    }

    public void testThatCommandDoesNotLogAnythingOnFileCreation() throws Exception {
        Configuration configuration = randomBoolean() ? jimFsConfiguration : jimFsConfigurationWithoutPermissions;

        try (FileSystem fs = Jimfs.newFileSystem(configuration)) {
            Path path = fs.getPath(randomAsciiOfLength(10));
            Settings settings = Settings.builder()
                    .put("path.home", createTempDir().toString())
                    .build();
            new CreateFileCommand(captureOutputTerminal, path).execute(settings, new Environment(settings));
            assertThat(Files.exists(path), is(true));
        }

        assertThat(captureOutputTerminal.getTerminalOutput(), hasSize(0));
    }

    public void testThatCommandWorksIfFileIsDeletedByCommand() throws Exception {
        Configuration configuration = randomBoolean() ? jimFsConfiguration : jimFsConfigurationWithoutPermissions;

        try (FileSystem fs = Jimfs.newFileSystem(configuration)) {
            Path path = fs.getPath(randomAsciiOfLength(10));
            Files.write(path, "anything".getBytes(StandardCharsets.UTF_8));

            Settings settings = Settings.builder()
                    .put("path.home", createTempDir().toString())
                    .build();
            new DeleteFileCommand(captureOutputTerminal, path).execute(settings, new Environment(settings));
            assertThat(Files.exists(path), is(false));
        }

        assertThat(captureOutputTerminal.getTerminalOutput(), hasSize(0));
    }

    private void executeCommand(Configuration configuration, AbstractTestCheckFileCommand command) throws Exception {
        try (FileSystem fs = Jimfs.newFileSystem(configuration)) {
            command.execute(fs);
        }
    }

    abstract class AbstractTestCheckFileCommand extends CheckFileCommand {

        protected final Mode mode;
        protected FileSystem fs;
        protected Path[] paths;
        final Path baseDir;

        public AbstractTestCheckFileCommand(Path baseDir, Terminal terminal, Mode mode) throws IOException {
            super(terminal);
            this.mode = mode;
            this.baseDir = baseDir;
        }

        public CliTool.ExitStatus execute(FileSystem fs) throws Exception {
            this.fs = fs;
            this.paths = new Path[] { writePath(fs, "p1", "anything"), writePath(fs, "p2", "anything"), writePath(fs, "p3", "anything") };
            Settings settings = Settings.settingsBuilder()
                    .put("path.home", baseDir.toString())
                    .build();
            return super.execute(Settings.EMPTY, new Environment(settings));
        }

        private Path writePath(FileSystem fs, String name, String content) throws IOException {
            Path path = fs.getPath(name);
            Files.write(path, content.getBytes(StandardCharsets.UTF_8));
            return path;
        }

        @Override
        protected Path[] pathsForPermissionsCheck(Settings settings, Environment env) {
            return paths;
        }
    }

    /**
     * command that changes permissions from a file if enabled
     */
    class PermissionCheckFileCommand extends AbstractTestCheckFileCommand {

        public PermissionCheckFileCommand(Path baseDir, Terminal terminal, Mode mode) throws IOException {
            super(baseDir, terminal, mode);
        }

        @Override
        public CliTool.ExitStatus doExecute(Settings settings, Environment env) throws Exception {
            int randomInt = randomInt(paths.length - 1);
            Path randomPath = paths[randomInt];
            switch (mode) {
                case CHANGE:
                    Files.write(randomPath, randomAsciiOfLength(10).getBytes(StandardCharsets.UTF_8));
                    Files.setPosixFilePermissions(randomPath, Sets.newHashSet(PosixFilePermission.OWNER_EXECUTE, PosixFilePermission.OTHERS_EXECUTE, PosixFilePermission.GROUP_EXECUTE));
                    break;
                case KEEP:
                    Files.write(randomPath, randomAsciiOfLength(10).getBytes(StandardCharsets.UTF_8));
                    Set<PosixFilePermission> posixFilePermissions = Files.getPosixFilePermissions(randomPath);
                    Files.setPosixFilePermissions(randomPath, posixFilePermissions);
                    break;
            }
            return CliTool.ExitStatus.OK;
        }

    }

    /**
     * command that changes the owner of a file if enabled
     */
    class OwnerCheckFileCommand extends AbstractTestCheckFileCommand {

        public OwnerCheckFileCommand(Path baseDir, Terminal terminal, Mode mode) throws IOException {
            super(baseDir, terminal, mode);
        }

        @Override
        public CliTool.ExitStatus doExecute(Settings settings, Environment env) throws Exception {
            int randomInt = randomInt(paths.length - 1);
            Path randomPath = paths[randomInt];
            switch (mode) {
                case CHANGE:
                    Files.write(randomPath, randomAsciiOfLength(10).getBytes(StandardCharsets.UTF_8));
                    UserPrincipal randomOwner = fs.getUserPrincipalLookupService().lookupPrincipalByName(randomAsciiOfLength(10));
                    Files.setOwner(randomPath, randomOwner);
                    break;
                case KEEP:
                    Files.write(randomPath, randomAsciiOfLength(10).getBytes(StandardCharsets.UTF_8));
                    UserPrincipal originalOwner = Files.getOwner(randomPath);
                    Files.setOwner(randomPath, originalOwner);
                    break;
            }

            return CliTool.ExitStatus.OK;
        }
    }

    /**
     * command that changes the group of a file if enabled
     */
    class GroupCheckFileCommand extends AbstractTestCheckFileCommand {

        public GroupCheckFileCommand(Path baseDir, Terminal terminal, Mode mode) throws IOException {
            super(baseDir, terminal, mode);
        }

        @Override
        public CliTool.ExitStatus doExecute(Settings settings, Environment env) throws Exception {
            int randomInt = randomInt(paths.length - 1);
            Path randomPath = paths[randomInt];
            switch (mode) {
                case CHANGE:
                    Files.write(randomPath, randomAsciiOfLength(10).getBytes(StandardCharsets.UTF_8));
                    GroupPrincipal randomPrincipal = fs.getUserPrincipalLookupService().lookupPrincipalByGroupName(randomAsciiOfLength(10));
                    Files.getFileAttributeView(randomPath, PosixFileAttributeView.class).setGroup(randomPrincipal);
                    break;
                case KEEP:
                    Files.write(randomPath, randomAsciiOfLength(10).getBytes(StandardCharsets.UTF_8));
                    GroupPrincipal groupPrincipal = Files.readAttributes(randomPath, PosixFileAttributes.class).group();
                    Files.getFileAttributeView(randomPath, PosixFileAttributeView.class).setGroup(groupPrincipal);
                    break;
            }

            return CliTool.ExitStatus.OK;
        }
    }

    /**
     * A command that creates a non existing file
     */
    class CreateFileCommand extends CheckFileCommand {

        private final Path pathToCreate;

        public CreateFileCommand(Terminal terminal, Path pathToCreate) {
            super(terminal);
            this.pathToCreate = pathToCreate;
        }

        @Override
        public CliTool.ExitStatus doExecute(Settings settings, Environment env) throws Exception {
            Files.write(pathToCreate, "anything".getBytes(StandardCharsets.UTF_8));
            return CliTool.ExitStatus.OK;
        }

        @Override
        protected Path[] pathsForPermissionsCheck(Settings settings, Environment env) throws Exception {
            return new Path[] { pathToCreate };
        }
    }

    /**
     * A command that deletes an existing file
     */
    class DeleteFileCommand extends CheckFileCommand {

        private final Path pathToDelete;

        public DeleteFileCommand(Terminal terminal, Path pathToDelete) {
            super(terminal);
            this.pathToDelete = pathToDelete;
        }

        @Override
        public CliTool.ExitStatus doExecute(Settings settings, Environment env) throws Exception {
            Files.delete(pathToDelete);
            return CliTool.ExitStatus.OK;
        }

        @Override
        protected Path[] pathsForPermissionsCheck(Settings settings, Environment env) throws Exception {
            return new Path[] {pathToDelete};
        }
    }
}