File: share_operation_unittest.cc

package info (click to toggle)
chromium 138.0.7204.157-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 6,071,864 kB
  • sloc: cpp: 34,936,859; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,953; asm: 946,768; xml: 739,967; 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 (465 lines) | stat: -rw-r--r-- 19,086 bytes parent folder | download | duplicates (3)
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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifdef UNSAFE_BUFFERS_BUILD
// TODO(crbug.com/40285824): Remove this and convert code to safer constructs.
#pragma allow_unsafe_buffers
#endif

#include "chrome/browser/webshare/win/share_operation.h"

#include "base/files/file_path.h"
#include "base/memory/raw_ptr.h"
#include "base/run_loop.h"
#include "base/synchronization/waitable_event.h"
#include "base/test/bind.h"
#include "base/uuid.h"
#include "base/win/core_winrt_util.h"
#include "base/win/post_async_results.h"
#include "chrome/browser/webshare/share_service_impl.h"
#include "chrome/browser/webshare/win/fake_buffer.h"
#include "chrome/browser/webshare/win/fake_data_transfer_manager.h"
#include "chrome/browser/webshare/win/fake_data_transfer_manager_interop.h"
#include "chrome/browser/webshare/win/scoped_share_operation_fake_components.h"
#include "chrome/test/base/chrome_render_view_host_test_harness.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/web_contents.h"
#include "storage/browser/blob/blob_data_builder.h"
#include "storage/browser/blob/blob_impl.h"
#include "storage/browser/blob/blob_storage_context.h"
#include "ui/views/win/hwnd_util.h"
#include "url/gurl.h"

#include <wrl/event.h>

using ABI::Windows::ApplicationModel::DataTransfer::IDataPackage;
using ABI::Windows::ApplicationModel::DataTransfer::IDataPackagePropertySet;
using ABI::Windows::ApplicationModel::DataTransfer::IDataRequest;
using ABI::Windows::ApplicationModel::DataTransfer::IDataRequestedEventArgs;
using ABI::Windows::Foundation::IAsyncOperation;
using ABI::Windows::Foundation::IAsyncOperationCompletedHandler;
using ABI::Windows::Foundation::IAsyncOperationWithProgress;
using ABI::Windows::Foundation::IAsyncOperationWithProgressCompletedHandler;
using ABI::Windows::Foundation::IClosable;
using ABI::Windows::Storage::FileAccessMode;
using ABI::Windows::Storage::IStorageFile;
using ABI::Windows::Storage::Streams::IBuffer;
using ABI::Windows::Storage::Streams::IDataReader;
using ABI::Windows::Storage::Streams::IDataReaderFactory;
using ABI::Windows::Storage::Streams::IInputStream;
using ABI::Windows::Storage::Streams::InputStreamOptions;
using ABI::Windows::Storage::Streams::IRandomAccessStream;
using Microsoft::WRL::Callback;
using Microsoft::WRL::ComPtr;
using Microsoft::WRL::Make;

namespace webshare {
namespace {
constexpr uint64_t kMaxSharedFileBytesForTest = 1024 * 100;
}  // namespace

class ShareOperationUnitTest : public ChromeRenderViewHostTestHarness {
 public:
  ~ShareOperationUnitTest() override = default;

  void SetUp() override {
    ChromeRenderViewHostTestHarness::SetUp();

    ASSERT_NO_FATAL_FAILURE(scoped_fake_components_.SetUp());
    ShareOperation::SetMaxFileBytesForTesting(kMaxSharedFileBytesForTest);
  }

  void TearDown() override {
    ChromeRenderViewHostTestHarness::TearDown();
    ShareOperation::SetMaxFileBytesForTesting(kMaxSharedFileBytes);
  }

 protected:
  void ReadFile(IStorageFile* file, std::string& result) {
    ComPtr<IRandomAccessStream> stream;
    {
      base::RunLoop run_loop;
      ComPtr<IAsyncOperation<IRandomAccessStream*>> open_operation;
      ASSERT_HRESULT_SUCCEEDED(file->OpenAsync(
          FileAccessMode::FileAccessMode_Read, &open_operation));
      ASSERT_HRESULT_SUCCEEDED(open_operation->put_Completed(
          Callback<IAsyncOperationCompletedHandler<IRandomAccessStream*>>(
              [&run_loop, &stream](
                  IAsyncOperation<IRandomAccessStream*>* async_operation,
                  AsyncStatus async_status) {
                EXPECT_EQ(async_status, AsyncStatus::Completed);
                EXPECT_HRESULT_SUCCEEDED(async_operation->GetResults(&stream));
                run_loop.Quit();
                return S_OK;
              })
              .Get()));
      run_loop.Run();
    }

    UINT64 size;
    ASSERT_HRESULT_SUCCEEDED(stream->get_Size(&size));

    ComPtr<IInputStream> input_stream;
    ASSERT_HRESULT_SUCCEEDED(stream->GetInputStreamAt(0, &input_stream));
    ComPtr<IClosable> closable_stream;
    ASSERT_HRESULT_SUCCEEDED(stream.As(&closable_stream));
    ASSERT_HRESULT_SUCCEEDED(closable_stream->Close());

    auto buffer = Make<FakeBuffer>(size);
    {
      base::RunLoop run_loop;
      ComPtr<IAsyncOperationWithProgress<IBuffer*, UINT32>> read_operation;
      ASSERT_HRESULT_SUCCEEDED(input_stream->ReadAsync(
          buffer.Get(), size, InputStreamOptions::InputStreamOptions_None,
          &read_operation));
      ASSERT_HRESULT_SUCCEEDED(read_operation->put_Completed(
          Callback<
              IAsyncOperationWithProgressCompletedHandler<IBuffer*, UINT32>>(
              [&run_loop](IAsyncOperationWithProgress<IBuffer*, UINT32>*
                              async_operation,
                          AsyncStatus async_status) {
                EXPECT_EQ(async_status, AsyncStatus::Completed);
                run_loop.Quit();
                return S_OK;
              })
              .Get()));
      run_loop.Run();
    }

    UINT32 bytes_loaded;
    ASSERT_HRESULT_SUCCEEDED(buffer->get_Length(&bytes_loaded));
    ASSERT_EQ(size, bytes_loaded);

    BYTE* raw_buffer;
    ASSERT_HRESULT_SUCCEEDED(buffer->Buffer(&raw_buffer));

    std::vector<unsigned char> bytes(bytes_loaded);
    for (UINT32 i = 0; i < bytes_loaded; i++) {
      bytes[i] = raw_buffer[i];
    }
    result = std::string(bytes.begin(), bytes.end());

    // Cleanup
    ComPtr<IClosable> closable_input_stream;
    ASSERT_HRESULT_SUCCEEDED(input_stream.As(&closable_input_stream));
    ASSERT_HRESULT_SUCCEEDED(closable_input_stream->Close());
  }

  blink::mojom::SharedFilePtr CreateSharedFile(
      base::FilePath::StringViewType name,
      const std::string& content_type,
      const std::string& contents) {
    auto blob = blink::mojom::SerializedBlob::New();
    const std::string uuid = base::Uuid::GenerateRandomV4().AsLowercaseString();
    blob->uuid = uuid;
    blob->content_type = content_type;
    blob->size = contents.size();

    base::RunLoop run_loop;
    auto blob_context_getter = browser_context()->GetBlobStorageContext();
    content::GetIOThreadTaskRunner({})->PostTaskAndReply(
        FROM_HERE,
        base::BindLambdaForTesting([&blob_context_getter, &blob, &uuid,
                                    &content_type, &contents]() {
          auto builder = std::make_unique<storage::BlobDataBuilder>(uuid);
          builder->set_content_type(content_type);
          builder->AppendData(contents);
          storage::BlobImpl::Create(
              blob_context_getter.Run()->AddFinishedBlob(std::move(builder)),
              blob->blob.InitWithNewPipeAndPassReceiver());
        }),
        base::BindLambdaForTesting([&run_loop]() { run_loop.Quit(); }));
    run_loop.Run();
    return blink::mojom::SharedFile::New(*base::SafeBaseName::Create(name),
                                         std::move(blob));
  }

  // Fetches the FakeDataTransferManager associated with the current context.
  // Returns a non-ref-counted pointer, as the lifetime is already maintained by
  // the scoped_fake_components_.
  FakeDataTransferManager* fake_data_transfer_manager() {
    if (!fake_data_transfer_manager_) {
      HWND hwnd =
          views::HWNDForNativeWindow(web_contents()->GetTopLevelNativeWindow());
      ComPtr<FakeDataTransferManager> fake_data_transfer_manager;
      EXPECT_HRESULT_SUCCEEDED(
          scoped_fake_components_.fake_data_transfer_manager_interop()
              .GetForWindow(hwnd, IID_PPV_ARGS(&fake_data_transfer_manager)));
      fake_data_transfer_manager_ = fake_data_transfer_manager.Get();
    }
    return fake_data_transfer_manager_;
  }

  FakeDataTransferManagerInterop& fake_data_transfer_manager_interop() {
    return scoped_fake_components_.fake_data_transfer_manager_interop();
  }

 private:
  raw_ptr<FakeDataTransferManager, DanglingUntriaged>
      fake_data_transfer_manager_ = nullptr;
  ScopedShareOperationFakeComponents scoped_fake_components_;
};

TEST_F(ShareOperationUnitTest, WithoutTitle) {
  bool post_data_requested_callback_invoked = false;
  fake_data_transfer_manager()->SetPostDataRequestedCallback(
      base::BindLambdaForTesting(
          [&post_data_requested_callback_invoked](
              const FakeDataTransferManager::DataRequestedContent&
                  data_requested_content) {
            ASSERT_FALSE(post_data_requested_callback_invoked);
            post_data_requested_callback_invoked = true;
            ASSERT_EQ(data_requested_content.title, " ");
            ASSERT_EQ(data_requested_content.text, "shared Text");
          }));

  base::RunLoop run_loop;
  ShareOperation operation{"", "shared Text", GURL(), web_contents()};
  operation.Run(
      std::vector<blink::mojom::SharedFilePtr>(),
      base::BindLambdaForTesting([&run_loop](blink::mojom::ShareError error) {
        ASSERT_EQ(error, blink::mojom::ShareError::OK);
        run_loop.Quit();
      }));
  run_loop.Run();

  ASSERT_TRUE(post_data_requested_callback_invoked);
}

TEST_F(ShareOperationUnitTest, BasicFields) {
  bool post_data_requested_callback_invoked = false;
  fake_data_transfer_manager()->SetPostDataRequestedCallback(
      base::BindLambdaForTesting(
          [&post_data_requested_callback_invoked](
              const FakeDataTransferManager::DataRequestedContent&
                  data_requested_content) {
            ASSERT_FALSE(post_data_requested_callback_invoked);
            post_data_requested_callback_invoked = true;
            ASSERT_EQ(data_requested_content.title, "shared title");
            ASSERT_EQ(data_requested_content.text, "shared text");
            ASSERT_EQ(GURL(data_requested_content.uri),
                      GURL("https://www.contoso.com"));
          }));

  base::RunLoop run_loop;
  ShareOperation operation{"shared title", "shared text",
                           GURL("https://www.contoso.com"), web_contents()};
  operation.Run(
      std::vector<blink::mojom::SharedFilePtr>(),
      base::BindLambdaForTesting([&run_loop](blink::mojom::ShareError error) {
        ASSERT_EQ(error, blink::mojom::ShareError::OK);
        run_loop.Quit();
      }));
  run_loop.Run();

  ASSERT_TRUE(post_data_requested_callback_invoked);
}

TEST_F(ShareOperationUnitTest, ShowShareUIForWindowFailure) {
  fake_data_transfer_manager_interop().SetShowShareUIForWindowBehavior(
      FakeDataTransferManagerInterop::ShowShareUIForWindowBehavior::
          FailImmediately);

  base::RunLoop run_loop;
  ShareOperation operation{"shared title", "shared text",
                           GURL("https://www.contoso.com"), web_contents()};
  operation.Run(
      std::vector<blink::mojom::SharedFilePtr>(),
      base::BindLambdaForTesting([&run_loop](blink::mojom::ShareError error) {
        ASSERT_EQ(error, blink::mojom::ShareError::INTERNAL_ERROR);
        run_loop.Quit();
      }));
  run_loop.Run();
}

TEST_F(ShareOperationUnitTest, BasicFile) {
  bool post_data_requested_callback_invoked = false;
  ComPtr<IStorageFile> shared_file;
  fake_data_transfer_manager()->SetPostDataRequestedCallback(
      base::BindLambdaForTesting(
          [&](const FakeDataTransferManager::DataRequestedContent&
                  data_requested_content) {
            ASSERT_FALSE(post_data_requested_callback_invoked);
            post_data_requested_callback_invoked = true;
            ASSERT_EQ(data_requested_content.title, "shared title");
            ASSERT_EQ(data_requested_content.files.size(), 1ull);
            ASSERT_EQ(data_requested_content.files[0].name, "MyFile.txt");
            shared_file = data_requested_content.files[0].file;
          }));

  base::RunLoop run_loop;
  std::vector<blink::mojom::SharedFilePtr> files;
  files.push_back(CreateSharedFile(FILE_PATH_LITERAL("MyFile.txt"),
                                   "text/plain", "Contents of the file"));
  ShareOperation operation{"shared title", "", GURL(), web_contents()};
  operation.Run(
      std::move(files),
      base::BindLambdaForTesting([&run_loop](blink::mojom::ShareError error) {
        ASSERT_EQ(error, blink::mojom::ShareError::OK);
        run_loop.Quit();
      }));
  run_loop.Run();

  ASSERT_TRUE(post_data_requested_callback_invoked);
  ASSERT_TRUE(shared_file);
  std::string file_contents;
  ASSERT_NO_FATAL_FAILURE(ReadFile(shared_file.Get(), file_contents));
  ASSERT_EQ(file_contents, "Contents of the file");
}

TEST_F(ShareOperationUnitTest, SingleFileAtSizeLimit) {
  bool post_data_requested_callback_invoked = false;
  ComPtr<IStorageFile> shared_file;
  fake_data_transfer_manager()->SetPostDataRequestedCallback(
      base::BindLambdaForTesting(
          [&](const FakeDataTransferManager::DataRequestedContent&
                  data_requested_content) {
            ASSERT_FALSE(post_data_requested_callback_invoked);
            post_data_requested_callback_invoked = true;
            ASSERT_EQ(data_requested_content.files.size(), 1ull);
            shared_file = data_requested_content.files[0].file;
          }));

  base::RunLoop run_loop;
  std::vector<blink::mojom::SharedFilePtr> files;
  files.push_back(
      CreateSharedFile(FILE_PATH_LITERAL("MyFile.txt"), "text/plain",
                       std::string(kMaxSharedFileBytesForTest, '*')));
  ShareOperation operation{"", "", GURL(), web_contents()};
  operation.Run(
      std::move(files),
      base::BindLambdaForTesting([&run_loop](blink::mojom::ShareError error) {
        ASSERT_EQ(error, blink::mojom::ShareError::OK);
        run_loop.Quit();
      }));
  run_loop.Run();

  ASSERT_TRUE(post_data_requested_callback_invoked);
  ASSERT_TRUE(shared_file);
  std::string file_contents;
  ASSERT_NO_FATAL_FAILURE(ReadFile(shared_file.Get(), file_contents));
  ASSERT_EQ(file_contents.length(), kMaxSharedFileBytesForTest);
}

TEST_F(ShareOperationUnitTest, SingleFileLargerThanSizeLimit) {
  bool post_data_requested_callback_invoked = false;
  ComPtr<IStorageFile> shared_file;
  fake_data_transfer_manager()->SetPostDataRequestedCallback(
      base::BindLambdaForTesting(
          [&](const FakeDataTransferManager::DataRequestedContent&
                  data_requested_content) {
            ASSERT_FALSE(post_data_requested_callback_invoked);
            post_data_requested_callback_invoked = true;
            ASSERT_EQ(data_requested_content.files.size(), 1ull);
            shared_file = data_requested_content.files[0].file;
          }));

  base::RunLoop run_loop;
  std::vector<blink::mojom::SharedFilePtr> files;
  files.push_back(
      CreateSharedFile(FILE_PATH_LITERAL("MyFile.txt"), "text/plain",
                       std::string(kMaxSharedFileBytesForTest + 1, '*')));
  ShareOperation operation{"", "", GURL(), web_contents()};
  operation.Run(
      std::move(files),
      base::BindLambdaForTesting([&run_loop](blink::mojom::ShareError error) {
        ASSERT_EQ(error, blink::mojom::ShareError::OK);
        run_loop.Quit();
      }));
  run_loop.Run();

  ASSERT_TRUE(post_data_requested_callback_invoked);
  ASSERT_TRUE(shared_file);
  std::string file_contents;
  ASSERT_NO_FATAL_FAILURE(ReadFile(shared_file.Get(), file_contents));
  ASSERT_LT(file_contents.length(), kMaxSharedFileBytesForTest + 1);
}

TEST_F(ShareOperationUnitTest, FilesTotallingSizeLimit) {
  bool post_data_requested_callback_invoked = false;
  ComPtr<IStorageFile> shared_file_1;
  ComPtr<IStorageFile> shared_file_2;
  fake_data_transfer_manager()->SetPostDataRequestedCallback(
      base::BindLambdaForTesting(
          [&](const FakeDataTransferManager::DataRequestedContent&
                  data_requested_content) {
            ASSERT_FALSE(post_data_requested_callback_invoked);
            post_data_requested_callback_invoked = true;
            ASSERT_EQ(data_requested_content.files.size(), 2ull);
            shared_file_1 = data_requested_content.files[0].file;
            shared_file_2 = data_requested_content.files[1].file;
          }));

  base::RunLoop run_loop;
  std::vector<blink::mojom::SharedFilePtr> files;
  files.push_back(
      CreateSharedFile(FILE_PATH_LITERAL("File1.txt"), "text/plain",
                       std::string(kMaxSharedFileBytesForTest / 2, '*')));
  files.push_back(
      CreateSharedFile(FILE_PATH_LITERAL("File2.txt"), "text/plain",
                       std::string(kMaxSharedFileBytesForTest / 2, '*')));
  ShareOperation operation{"", "", GURL(), web_contents()};
  operation.Run(
      std::move(files),
      base::BindLambdaForTesting([&run_loop](blink::mojom::ShareError error) {
        ASSERT_EQ(error, blink::mojom::ShareError::OK);
        run_loop.Quit();
      }));
  run_loop.Run();

  ASSERT_TRUE(post_data_requested_callback_invoked);
  ASSERT_TRUE(shared_file_1);
  ASSERT_TRUE(shared_file_2);
  std::string file1_contents;
  ASSERT_NO_FATAL_FAILURE(ReadFile(shared_file_1.Get(), file1_contents));
  std::string file2_contents;
  ASSERT_NO_FATAL_FAILURE(ReadFile(shared_file_2.Get(), file2_contents));
  ASSERT_EQ(file1_contents.length() + file2_contents.length(),
            kMaxSharedFileBytesForTest);
}

TEST_F(ShareOperationUnitTest, FilesTotallingLargerThanSizeLimit) {
  bool post_data_requested_callback_invoked = false;
  ComPtr<IStorageFile> shared_file_1;
  ComPtr<IStorageFile> shared_file_2;
  fake_data_transfer_manager()->SetPostDataRequestedCallback(
      base::BindLambdaForTesting(
          [&](const FakeDataTransferManager::DataRequestedContent&
                  data_requested_content) {
            ASSERT_FALSE(post_data_requested_callback_invoked);
            post_data_requested_callback_invoked = true;
            ASSERT_EQ(data_requested_content.files.size(), 2ull);
            shared_file_1 = data_requested_content.files[0].file;
            shared_file_2 = data_requested_content.files[1].file;
          }));

  base::RunLoop run_loop;
  std::vector<blink::mojom::SharedFilePtr> files;
  files.push_back(
      CreateSharedFile(FILE_PATH_LITERAL("File1.txt"), "text/plain",
                       std::string(kMaxSharedFileBytesForTest / 2, '*')));
  files.push_back(
      CreateSharedFile(FILE_PATH_LITERAL("File2.txt"), "text/plain",
                       std::string((kMaxSharedFileBytesForTest / 2) + 1, '*')));
  ShareOperation operation{"", "", GURL(), web_contents()};
  operation.Run(
      std::move(files),
      base::BindLambdaForTesting([&run_loop](blink::mojom::ShareError error) {
        ASSERT_EQ(error, blink::mojom::ShareError::OK);
        run_loop.Quit();
      }));
  run_loop.Run();

  ASSERT_TRUE(post_data_requested_callback_invoked);
  ASSERT_TRUE(shared_file_1);
  ASSERT_TRUE(shared_file_2);
  std::string file1_contents;
  ASSERT_NO_FATAL_FAILURE(ReadFile(shared_file_1.Get(), file1_contents));
  std::string file2_contents;
  ASSERT_NO_FATAL_FAILURE(ReadFile(shared_file_2.Get(), file2_contents));
  ASSERT_LT(file1_contents.length() + file2_contents.length(),
            kMaxSharedFileBytesForTest + 1);
}

}  // namespace webshare