File: trash_service_unittest.cc

package info (click to toggle)
chromium 138.0.7204.183-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 6,071,908 kB
  • sloc: cpp: 34,937,088; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,953; asm: 946,768; xml: 739,971; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,806; php: 13,980; tcl: 13,166; yacc: 8,925; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (301 lines) | stat: -rw-r--r-- 11,208 bytes parent folder | download | duplicates (6)
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
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chromeos/ash/components/trash_service/public/cpp/trash_service.h"

#include <limits.h>

#include <memory>
#include <string_view>
#include <utility>
#include <vector>

#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/files/scoped_temp_dir.h"
#include "base/rand_util.h"
#include "base/run_loop.h"
#include "base/strings/strcat.h"
#include "base/strings/string_split.h"
#include "base/test/gmock_callback_support.h"
#include "base/test/mock_callback.h"
#include "base/test/task_environment.h"
#include "base/time/time.h"
#include "chromeos/ash/components/trash_service/public/mojom/trash_service.mojom.h"
#include "chromeos/ash/components/trash_service/trash_service_impl.h"
#include "mojo/public/cpp/bindings/remote.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace ash::trash_service {

using ::base::test::RunClosure;
using ::testing::_;

namespace {

// A struct with default data used by tests to enable testing invalid fields
// with all remaining data being valid.
struct TrashInfoContents {
  std::string header = "[Trash Info]";
  std::string path_line = "Path=/foo/bar.txt";
  std::string date_line = "DeletionDate=2022-07-18T10:13:00.000Z";

  base::FilePath restore_path{"/foo/bar.txt"};

  std::string ToString() const {
    return base::StrCat({header, "\n", path_line, "\n", date_line});
  }

  base::Time GetDeletionDate() const {
    std::vector<std::string_view> key_value =
        base::SplitStringPiece(std::string_view(date_line), "=",
                               base::WhitespaceHandling::TRIM_WHITESPACE,
                               base::SplitResult::SPLIT_WANT_ALL);
    EXPECT_EQ(2UL, key_value.size());
    base::Time time;
    EXPECT_TRUE(base::Time::FromUTCString(key_value[1].data(), &time));
    return time;
  }
};

}  // namespace

class TrashServiceTest : public ::testing::Test {
 public:
  void SetUp() override {
    ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
    test_dir_ = temp_dir_.GetPath();

    trash_impl_ = std::make_unique<TrashServiceImpl>(
        trash_service_remote_.BindNewPipeAndPassReceiver());
  }

  void ExpectParsingFailedForFileContents(const std::string& file_contents) {
    const base::FilePath file_path = test_dir_.Append("foo.txt.trashinfo");
    ASSERT_TRUE(base::WriteFile(file_path, file_contents));
    base::File trash_info_file(file_path,
                               base::File::FLAG_OPEN | base::File::FLAG_READ);

    base::MockCallback<ParseTrashInfoCallback> complete_callback;
    base::RunLoop run_loop;
    EXPECT_CALL(complete_callback, Run(base::File::FILE_ERROR_FAILED,
                                       base::FilePath(), base::Time()))
        .WillOnce(RunClosure(run_loop.QuitClosure()));

    trash_impl_->ParseTrashInfoFile(std::move(trash_info_file),
                                    complete_callback.Get());
    run_loop.Run();
  }

  void ExpectParsingSucceedsForFileContents(
      const TrashInfoContents& file_contents) {
    const base::FilePath file_path = test_dir_.Append("foo.txt.trashinfo");
    ASSERT_TRUE(base::WriteFile(file_path, file_contents.ToString()));
    base::File trash_info_file(file_path,
                               base::File::FLAG_OPEN | base::File::FLAG_READ);

    base::MockCallback<ParseTrashInfoCallback> complete_callback;
    base::RunLoop run_loop;
    EXPECT_CALL(complete_callback,
                Run(base::File::FILE_OK, file_contents.restore_path,
                    file_contents.GetDeletionDate()))
        .WillOnce(RunClosure(run_loop.QuitClosure()));

    trash_impl_->ParseTrashInfoFile(std::move(trash_info_file),
                                    complete_callback.Get());
    run_loop.Run();
  }

 protected:
  base::test::TaskEnvironment task_environment_;

  base::ScopedTempDir temp_dir_;
  base::FilePath test_dir_;

  std::unique_ptr<TrashServiceImpl> trash_impl_;
  mojo::Remote<mojom::TrashService> trash_service_remote_;
};

TEST_F(TrashServiceTest, NonexistingFileShouldReturnNotFound) {
  const base::FilePath file_path_does_not_exist =
      test_dir_.Append("foo.txt.trashinfo");
  base::File trash_info_file(file_path_does_not_exist,
                             base::File::FLAG_OPEN | base::File::FLAG_READ);

  base::MockCallback<ParseTrashInfoCallback> complete_callback;
  base::RunLoop run_loop;
  EXPECT_CALL(complete_callback, Run(base::File::FILE_ERROR_NOT_FOUND, _, _))
      .WillOnce(RunClosure(run_loop.QuitClosure()));

  trash_impl_->ParseTrashInfoFile(std::move(trash_info_file),
                                  complete_callback.Get());
  run_loop.Run();
}

TEST_F(TrashServiceTest, PathExceedingMaxAllowableLengthShouldFail) {
  // Create a valid path that exceeds `PATH_MAX`.
  TrashInfoContents file_contents;
  file_contents.restore_path =
      base::FilePath("/foo").Append(std::string(PATH_MAX, 'f')).Append("foo");
  file_contents.path_line =
      base::StrCat({"Path=", file_contents.restore_path.value()});

  // Setup the test file as a well-formed file but with a path that will cause
  // the read buffer to go over.
  ExpectParsingFailedForFileContents(file_contents.ToString());
}

TEST_F(TrashServiceTest, ValidFileWithExtraDataIgnoresOverflow) {
  TrashInfoContents contents;
  const base::FilePath file_path = test_dir_.Append("foo.txt.trashinfo");

  // Append 1024 random bytes to the end of the trashinfo file, this data
  // should be ignored when parsing.
  ASSERT_TRUE(base::WriteFile(file_path,
                              base::StrCat({contents.ToString(), "\n",
                                            base::RandBytesAsString(1024)})));
  base::File trash_info_file(file_path,
                             base::File::FLAG_OPEN | base::File::FLAG_READ);

  base::MockCallback<ParseTrashInfoCallback> complete_callback;
  base::RunLoop run_loop;
  EXPECT_CALL(complete_callback, Run(base::File::FILE_OK, contents.restore_path,
                                     contents.GetDeletionDate()))
      .WillOnce(RunClosure(run_loop.QuitClosure()));

  trash_impl_->ParseTrashInfoFile(std::move(trash_info_file),
                                  complete_callback.Get());
  run_loop.Run();
}

TEST_F(TrashServiceTest, InvalidTrashInfoHeaderScenarios) {
  // Invalid header.
  {
    TrashInfoContents contents;
    contents.header = "invalid header";
    ExpectParsingFailedForFileContents(contents.ToString());
  }

  // Valid structure but misspelled.
  {
    TrashInfoContents contents;
    contents.header = "[Trash Imfo]";
    ExpectParsingFailedForFileContents(contents.ToString());
  }

  // First line is the "Path=" key value pair.
  {
    TrashInfoContents contents;
    std::string file_contents =
        base::StrCat({contents.path_line, "\n", contents.date_line});
    ExpectParsingFailedForFileContents(file_contents);
  }
}

TEST_F(TrashServiceTest, InvalidPathKeyValueScenarios) {
  // No path key value pair.
  {
    TrashInfoContents contents;
    std::string file_contents =
        base::StrCat({contents.header, "\n", contents.date_line});
    ExpectParsingFailedForFileContents(file_contents);
  }

  // Create a too-long path where each component is valid.
  std::string long_path;
  for (int i = 0; long_path.size() < PATH_MAX; ++i) {
    long_path += '/';
    long_path.append(200, static_cast<char>('a' + i));
  }
  long_path.resize(PATH_MAX);

  const std::vector<std::string> lines = {{
      "/foo/bar",                // Missing "Path=" key.
      "Patn=/foo/bar",           // Misspelled "Path=" key.
      "Path=/foo/../bar",        // Path references parent.
      "Path=/foo/%2e%2E/bar",    // Path references parent in a sneaky way.
      "Path=/foo/./bar",         // Path references current dir.
      "Path=/foo/%2e/bar",       // Path references current dir in a sneaky way.
      "Path=relative/path.txt",  // Relative file path.
      "Path=",                   // Empty path.
      "Path=bar"                 // Relative folder path.
      "Path=foo/bar"             // Relative path.
      "Path=/",                  // Root path.
      "Path=%2f",                // Root path in a sneaky way.
      "Path=/////",              // Root path.
      "Path=//server/foo/bar",   // UNC-style path.
      "Path=/foo%00/bar",        // Embedded NUL byte.
      "Path=/foo%ff/bar",        // Non UTF-8.
      base::StrCat(
          {"Path=/", std::string(NAME_MAX + 1, 'x')}),  // Long component.
      base::StrCat({"Path=", long_path}),               // Long path.
  }};

  for (const std::string& line : lines) {
    TrashInfoContents contents;
    contents.path_line = line;
    ExpectParsingFailedForFileContents(contents.ToString());
  }
}

TEST_F(TrashServiceTest, InvalidDeletionDateKeyValueScenarios) {
  // No deletion date key value pair.
  {
    TrashInfoContents contents;
    std::string file_contents =
        base::StrCat({contents.header, "\n", contents.path_line});
    ExpectParsingFailedForFileContents(file_contents);
  }

  const std::vector<std::string> kInvalidDeletionDates = {{
      "2022-07-18T10:13:00.000Z",              // Missing "DeletionDate=" key.
      "DeletedDate=2022-07-18T10:13:00.000Z",  // Misspelled "DeletionDate="
                                               // key.
      "DeletionDate=2022-07-1810:13:00.000Z",  // Not the required size (missing
                                               // the T character for time).
      "DeletionDate=abcdefghijklmnopqrstuvw",  // Same ISO-8601 size but invalid
                                               // date.
  }};
  for (const auto& date : kInvalidDeletionDates) {
    TrashInfoContents contents;
    contents.date_line = date;
    ExpectParsingFailedForFileContents(contents.ToString());
  }
}

TEST_F(TrashServiceTest, ValidPathKeyValueScenarios) {
  TrashInfoContents contents;

  const std::vector<std::string> kValidPaths = {{
      "Path=/foo/bar.txt",      // Happy path.
      "   Path=/foo/bar.txt",   // Leading whitespace is ignored.
      "Path=/foo/bar.txt    ",  // Trailing whitespace is ignored.
  }};
  for (const auto& path : kValidPaths) {
    contents.path_line = path;
    ExpectParsingSucceedsForFileContents(contents);
  }

  contents.path_line = "Path=/%09new%0aline%25%20";
  contents.restore_path = base::FilePath("/\tnew\nline% ");
  ExpectParsingSucceedsForFileContents(contents);
}

TEST_F(TrashServiceTest, ValidDeletionDateKeyValueScenarios) {
  const std::vector<std::string> kValidDeletionDates = {{
      "DeletionDate=2022-07-18T10:13:00.000Z",      // Happy path.
      "   DeletionDate=2022-07-18T10:13:00.000Z",   // Leading whitespace is
                                                    // ignored.
      "DeletionDate=2022-07-18T10:13:00.000Z    ",  // Trailing whitespace is
                                                    // ignored.
  }};
  for (const auto& date : kValidDeletionDates) {
    TrashInfoContents contents;
    contents.date_line = date;
    ExpectParsingSucceedsForFileContents(contents);
  }
}

}  // namespace ash::trash_service