File: client_side_phishing_model_unittest.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (709 lines) | stat: -rw-r--r-- 28,094 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
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
// 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/390223051): Remove C-library calls to fix the errors.
#pragma allow_unsafe_libc_calls
#endif

#include "components/safe_browsing/content/browser/client_side_phishing_model.h"

#include <string>
#include <utility>

#include "base/containers/span.h"
#include "base/files/file.h"
#include "base/files/file_util.h"
#include "base/files/scoped_temp_dir.h"
#include "base/functional/bind.h"
#include "base/logging.h"
#include "base/memory/read_only_shared_memory_region.h"
#include "base/memory/scoped_refptr.h"
#include "base/memory/shared_memory_mapping.h"
#include "base/path_service.h"
#include "base/run_loop.h"
#include "base/task/sequenced_task_runner.h"
#include "base/task/task_traits.h"
#include "base/task/thread_pool.h"
#include "base/test/gtest_util.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/scoped_command_line.h"
#include "base/test/scoped_feature_list.h"
#include "build/build_config.h"
#include "components/optimization_guide/core/delivery/model_util.h"
#include "components/optimization_guide/core/delivery/test_model_info_builder.h"
#include "components/optimization_guide/core/delivery/test_optimization_guide_model_provider.h"
#include "components/optimization_guide/core/optimization_guide_proto_util.h"
#include "components/optimization_guide/proto/client_side_phishing_model_metadata.pb.h"
#include "components/optimization_guide/proto/models.pb.h"
#include "components/safe_browsing/core/common/fbs/client_model_generated.h"
#include "components/safe_browsing/core/common/features.h"
#include "components/safe_browsing/core/common/proto/client_model.pb.h"
#include "content/public/test/browser_task_environment.h"
#include "content/public/test/test_renderer_host.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace safe_browsing {

namespace {

using ::optimization_guide::AnyWrapProto;

}

class ClientSidePhishingModelObserverTracker
    : public optimization_guide::TestOptimizationGuideModelProvider {
 public:
  void AddObserverForOptimizationTargetModel(
      optimization_guide::proto::OptimizationTarget optimization_target,
      const std::optional<optimization_guide::proto::Any>& model_metadata,
      optimization_guide::OptimizationTargetModelObserver* observer) override {
    if (optimization_target ==
        optimization_guide::proto::OPTIMIZATION_TARGET_CLIENT_SIDE_PHISHING) {
      EXPECT_FALSE(model_observer_);
      model_observer_ = observer;
    }
  }

  void RemoveObserverForOptimizationTargetModel(
      optimization_guide::proto::OptimizationTarget optimization_target,
      optimization_guide::OptimizationTargetModelObserver* observer) override {
    if (optimization_target ==
        optimization_guide::proto::OPTIMIZATION_TARGET_CLIENT_SIDE_PHISHING) {
      EXPECT_EQ(observer, model_observer_);
      model_observer_ = nullptr;
    }
  }

  // Notifies the model validation observer about the model file update.
  void NotifyModelFileUpdate(
      optimization_guide::proto::OptimizationTarget optimization_target,
      const base::FilePath& model_file_path,
      const base::flat_set<base::FilePath>& additional_files_path) {
    if (optimization_target ==
        optimization_guide::proto::OPTIMIZATION_TARGET_CLIENT_SIDE_PHISHING) {
      optimization_guide::proto::ClientSidePhishingModelMetadata
          trigger_model_metadata;
      trigger_model_metadata.set_image_embedding_model_version(1);
      auto model_metadata =
          optimization_guide::TestModelInfoBuilder()
              .SetModelFilePath(model_file_path)
              .SetAdditionalFiles(additional_files_path)
              .SetModelMetadata(AnyWrapProto(trigger_model_metadata))
              .Build();
      model_observer_->OnModelUpdated(optimization_target, *model_metadata);
    } else if (optimization_target ==
               optimization_guide::proto::
                   OPTIMIZATION_TARGET_CLIENT_SIDE_PHISHING_IMAGE_EMBEDDER) {
      optimization_guide::proto::ClientSidePhishingModelMetadata
          image_embedding_model_metadata;
      image_embedding_model_metadata.set_image_embedding_model_version(1);
      auto model_metadata =
          optimization_guide::TestModelInfoBuilder()
              .SetModelFilePath(model_file_path)
              .SetModelMetadata(AnyWrapProto(image_embedding_model_metadata))
              .Build();
      model_observer_->OnModelUpdated(optimization_target, *model_metadata);
    }
  }

  void SendEmptyModelInfoUpdate(
      optimization_guide::proto::OptimizationTarget optimization_target) {
    model_observer_->OnModelUpdated(optimization_target, std::nullopt);
  }

 private:
  // The observer that is registered to receive model validation optimzation
  // target events.
  raw_ptr<optimization_guide::OptimizationTargetModelObserver> model_observer_;
};

class ClientSidePhishingModelTest : public content::RenderViewHostTestHarness {
 public:
  ClientSidePhishingModelTest() = default;

  void SetUp() override {
    content::RenderViewHostTestHarness::SetUp();

    model_observer_tracker_ =
        std::make_unique<ClientSidePhishingModelObserverTracker>();
    client_side_phishing_model_ = std::make_unique<ClientSidePhishingModel>(
        model_observer_tracker_.get());
  }

  void TearDown() override {
    content::RenderViewHostTestHarness::TearDown();
    client_side_phishing_model_.reset();
    model_observer_tracker_.reset();
  }

  void SendEmptyModelInfoUpdate(
      optimization_guide::proto::OptimizationTarget optimization_target) {
    model_observer_tracker_->SendEmptyModelInfoUpdate(optimization_target);
    task_environment()->RunUntilIdle();
  }

  void ValidateModel(
      const base::FilePath& model_file_path,
      const base::flat_set<base::FilePath>& additional_file_path) {
    model_observer_tracker_->NotifyModelFileUpdate(
        optimization_guide::proto::OPTIMIZATION_TARGET_CLIENT_SIDE_PHISHING,
        model_file_path, additional_file_path);
    task_environment()->RunUntilIdle();
  }

  void ValidateImageEmbeddingModel(
      const base::FilePath& image_embedding_model_file_path) {
    model_observer_tracker_->NotifyModelFileUpdate(
        optimization_guide::proto::
            OPTIMIZATION_TARGET_CLIENT_SIDE_PHISHING_IMAGE_EMBEDDER,
        image_embedding_model_file_path, {});
    task_environment()->RunUntilIdle();
  }

  ClientSidePhishingModel* service() {
    return client_side_phishing_model_.get();
  }

  base::HistogramTester& histogram_tester() { return histogram_tester_; }

 private:
  base::HistogramTester histogram_tester_;

  std::unique_ptr<ClientSidePhishingModelObserverTracker>
      model_observer_tracker_;
  std::unique_ptr<ClientSidePhishingModel> client_side_phishing_model_;
};

namespace {

std::string CreateFlatBufferString() {
  flatbuffers::FlatBufferBuilder builder(1024);
  flat::ClientSideModelBuilder csd_model_builder(builder);
  builder.Finish(csd_model_builder.Finish());
  return std::string(reinterpret_cast<char*>(builder.GetBufferPointer()),
                     builder.GetSize());
}

void GetFlatBufferStringFromMappedMemory(
    base::ReadOnlySharedMemoryRegion region,
    std::string* output) {
  ASSERT_TRUE(region.IsValid());
  base::ReadOnlySharedMemoryMapping mapping = region.Map();
  ASSERT_TRUE(mapping.IsValid());
  *output = std::string(reinterpret_cast<const char*>(mapping.memory()),
                        mapping.size());
}

}  // namespace

TEST_F(ClientSidePhishingModelTest, ValidModel) {
  base::FilePath model_file_path;
  base::PathService::Get(base::DIR_SRC_TEST_DATA_ROOT, &model_file_path);
  model_file_path = model_file_path.AppendASCII("components")
                        .AppendASCII("test")
                        .AppendASCII("data")
                        .AppendASCII("safe_browsing")
                        .AppendASCII("client_model.pb");

  base::FilePath additional_files_path;
  base::PathService::Get(base::DIR_SRC_TEST_DATA_ROOT, &additional_files_path);
  additional_files_path = additional_files_path.AppendASCII("components")
                              .AppendASCII("test")
                              .AppendASCII("data")
                              .AppendASCII("safe_browsing")

#if BUILDFLAG(IS_ANDROID)
                              .AppendASCII("visual_model_android.tflite");
#else
                              .AppendASCII("visual_model_desktop.tflite");
#endif
  service()->SetModelTypeForTesting(CSDModelType::kFlatbuffer);
  ValidateModel(model_file_path, {additional_files_path});

  histogram_tester().ExpectUniqueSample(
      "SBClientPhishing.ModelDynamicUpdateSuccess", true, 1);
  EXPECT_TRUE(service()->IsEnabled());

  // Image embedding model has not been loaded yet, so the versions are not
  // matching.
  EXPECT_FALSE(service()->IsModelMetadataImageEmbeddingVersionMatching());

  base::FilePath image_embedding_model_file_path;
  base::PathService::Get(base::DIR_SRC_TEST_DATA_ROOT,
                         &image_embedding_model_file_path);
  image_embedding_model_file_path =
      image_embedding_model_file_path.AppendASCII("components")
          .AppendASCII("test")
          .AppendASCII("data")
          .AppendASCII("safe_browsing")
          .AppendASCII("image_embedding.tflite");
  ValidateImageEmbeddingModel(image_embedding_model_file_path);
  histogram_tester().ExpectUniqueSample(
      "SBClientPhishing.ModelDynamicUpdateSuccess.ImageEmbedding", true, 1);

  EXPECT_TRUE(service()->HasImageEmbeddingModel());
  // The above must be true in order for below to be true.
  const base::File& image_embedding_file = service()->GetImageEmbeddingModel();
  EXPECT_TRUE(image_embedding_file.IsValid());
  EXPECT_TRUE(service()->IsModelMetadataImageEmbeddingVersionMatching());

  // We are going to load it another time to see that it works with a model
  // loaded already.
  ValidateImageEmbeddingModel(image_embedding_model_file_path);
  // Since we loaded the model twice, we expect this to be 2 now.
  histogram_tester().ExpectUniqueSample(
      "SBClientPhishing.ModelDynamicUpdateSuccess.ImageEmbedding", true, 2);

  EXPECT_TRUE(service()->HasImageEmbeddingModel());
  const base::File& image_embedding_file_2 =
      service()->GetImageEmbeddingModel();
  EXPECT_TRUE(image_embedding_file_2.IsValid());
  EXPECT_TRUE(service()->IsModelMetadataImageEmbeddingVersionMatching());

  // Now we're going to get rid of the image embedding model in file by sending
  // an empty model info.
  SendEmptyModelInfoUpdate(
      optimization_guide::proto::
          OPTIMIZATION_TARGET_CLIENT_SIDE_PHISHING_IMAGE_EMBEDDER);
  // Service should still be enabled because it can live without the image
  // embedding model.
  EXPECT_TRUE(service()->IsEnabled());
  EXPECT_FALSE(service()->HasImageEmbeddingModel());
  EXPECT_FALSE(service()->IsModelMetadataImageEmbeddingVersionMatching());
}

TEST_F(ClientSidePhishingModelTest, InvalidModelDueToInvalidPath) {
  base::ScopedTempDir model_dir;
  EXPECT_TRUE(model_dir.CreateUniqueTempDir());
  base::FilePath model_file_path =
      model_dir.GetPath().AppendASCII("non_existent_client_model.pb");
  base::WriteFile(model_file_path, "INVALID MODEL DATA");

  base::FilePath additional_files_path;
  base::PathService::Get(base::DIR_SRC_TEST_DATA_ROOT, &additional_files_path);
  additional_files_path = additional_files_path.AppendASCII("components")
                              .AppendASCII("test")
                              .AppendASCII("data")
                              .AppendASCII("safe_browsing")

#if BUILDFLAG(IS_ANDROID)
                              .AppendASCII("visual_model_android.tflite");
#else
                              .AppendASCII("visual_model_desktop.tflite");
#endif

  ValidateModel(model_file_path, {additional_files_path});

  histogram_tester().ExpectUniqueSample(
      "SBClientPhishing.ModelDynamicUpdateSuccess", false, 1);
  EXPECT_FALSE(service()->IsEnabled());
}

TEST_F(ClientSidePhishingModelTest, InvalidModelDueToNonexistentPath) {
  base::ScopedTempDir model_dir;
  EXPECT_TRUE(model_dir.CreateUniqueTempDir());
  base::FilePath weird_model_file_path =
      model_dir.GetPath().AppendASCII("non_existent_directory/");

  base::FilePath additional_files_path;
  base::PathService::Get(base::DIR_SRC_TEST_DATA_ROOT, &additional_files_path);
  additional_files_path = additional_files_path.AppendASCII("components")
                              .AppendASCII("test")
                              .AppendASCII("data")
                              .AppendASCII("safe_browsing")
#if BUILDFLAG(IS_ANDROID)
                              .AppendASCII("visual_model_android.tflite");
#else
                              .AppendASCII("visual_model_desktop.tflite");
#endif

  ValidateModel(weird_model_file_path, {additional_files_path});

  histogram_tester().ExpectUniqueSample(
      "SBClientPhishing.ModelDynamicUpdateSuccess", false, 1);
  EXPECT_FALSE(service()->IsEnabled());
}

TEST_F(ClientSidePhishingModelTest,
       InvalidModelDueToValidPathButMultipleAdditionalFilesPath) {
  base::ScopedTempDir model_dir;
  EXPECT_TRUE(model_dir.CreateUniqueTempDir());
  base::FilePath model_file_path;
  base::PathService::Get(base::DIR_SRC_TEST_DATA_ROOT, &model_file_path);
  model_file_path = model_file_path.AppendASCII("components")
                        .AppendASCII("test")
                        .AppendASCII("data")
                        .AppendASCII("safe_browsing")
                        .AppendASCII("client_model.pb");

  base::FilePath additional_files_path;
  base::PathService::Get(base::DIR_SRC_TEST_DATA_ROOT, &additional_files_path);
  additional_files_path = additional_files_path.AppendASCII("components")
                              .AppendASCII("test")
                              .AppendASCII("data")
                              .AppendASCII("safe_browsing")
#if BUILDFLAG(IS_ANDROID)
                              .AppendASCII("visual_model_android.tflite");
#else
                              .AppendASCII("visual_model_desktop.tflite");
#endif

  // It has to be different file name at the end for the set to count them
  // differently.
  base::FilePath additional_files_path2;
  base::PathService::Get(base::DIR_SRC_TEST_DATA_ROOT, &additional_files_path2);
  additional_files_path2 = additional_files_path2.AppendASCII("components2")
                               .AppendASCII("test2")
                               .AppendASCII("data2")
                               .AppendASCII("safe_browsing2")

#if BUILDFLAG(IS_ANDROID)
                               .AppendASCII("visual_model_android2.tflite");
#else
                               .AppendASCII("visual_model_desktop2.tflite");
#endif

  ValidateModel(model_file_path,
                {additional_files_path, additional_files_path2});

  histogram_tester().ExpectUniqueSample(
      "SBClientPhishing.ModelDynamicUpdateSuccess", false, 1);
  EXPECT_FALSE(service()->IsEnabled());
}

TEST_F(ClientSidePhishingModelTest,
       InvalidImageEmbeddingModelDueToNonexistentPath) {
  base::ScopedTempDir model_dir;
  EXPECT_TRUE(model_dir.CreateUniqueTempDir());
  base::FilePath image_embedding_model_file_path =
      model_dir.GetPath().AppendASCII("non_existent_directory_2/");

  ValidateImageEmbeddingModel(image_embedding_model_file_path);

  histogram_tester().ExpectUniqueSample(
      "SBClientPhishing.ModelDynamicUpdateSuccess.ImageEmbedding", false, 1);
}

TEST_F(ClientSidePhishingModelTest,
       EmptyOptimizationGuideModelInfoDisablesService) {
  base::FilePath model_file_path;
  base::PathService::Get(base::DIR_SRC_TEST_DATA_ROOT, &model_file_path);
  model_file_path = model_file_path.AppendASCII("components")
                        .AppendASCII("test")
                        .AppendASCII("data")
                        .AppendASCII("safe_browsing")
                        .AppendASCII("client_model.pb");

  base::FilePath additional_files_path;
  base::PathService::Get(base::DIR_SRC_TEST_DATA_ROOT, &additional_files_path);
  additional_files_path = additional_files_path.AppendASCII("components")
                              .AppendASCII("test")
                              .AppendASCII("data")
                              .AppendASCII("safe_browsing")

#if BUILDFLAG(IS_ANDROID)
                              .AppendASCII("visual_model_android.tflite");
#else
                              .AppendASCII("visual_model_desktop.tflite");
#endif
  service()->SetModelTypeForTesting(CSDModelType::kFlatbuffer);
  ValidateModel(model_file_path, {additional_files_path});

  histogram_tester().ExpectUniqueSample(
      "SBClientPhishing.ModelDynamicUpdateSuccess", true, 1);
  EXPECT_TRUE(service()->IsEnabled());

  // It is enabled now, but we will send an empty model info update to the model
  // class, which should remove the model from the class, and notifying the
  // service class will make it disabled.
  SendEmptyModelInfoUpdate(
      optimization_guide::proto::OPTIMIZATION_TARGET_CLIENT_SIDE_PHISHING);

  EXPECT_FALSE(service()->IsEnabled());
}

TEST_F(ClientSidePhishingModelTest, RejectsInvalidFlatbuffer) {
  service()->SetVisualTfLiteModelForTesting(base::File());
  service()->ClearMappedRegionForTesting();
  service()->SetModelTypeForTesting(CSDModelType::kNone);
  service()->SetModelStringForTesting("bad flatbuffer", base::File());
  EXPECT_FALSE(service()->IsEnabled());
}

TEST_F(ClientSidePhishingModelTest, NotifiesForFile) {
  service()->SetVisualTfLiteModelForTesting(base::File());
  service()->ClearMappedRegionForTesting();
  service()->SetModelTypeForTesting(CSDModelType::kNone);

  base::RunLoop run_loop;
  bool called = false;
  base::CallbackListSubscription subscription =
      service()->RegisterCallback(base::BindRepeating(
          [](base::RepeatingClosure quit_closure, bool* called) {
            *called = true;
            std::move(quit_closure).Run();
          },
          run_loop.QuitClosure(), &called));

  base::ScopedTempDir temp_dir;
  ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
  const base::FilePath file_path =
      temp_dir.GetPath().AppendASCII("visual_model.tflite");
  base::File file(file_path, base::File::FLAG_OPEN_ALWAYS |
                                 base::File::FLAG_READ |
                                 base::File::FLAG_WRITE);
  const std::string_view file_contents = "visual model file";
  file.WriteAtCurrentPos(base::as_byte_span(file_contents));

  const std::string model_str = CreateFlatBufferString();
  service()->SetModelStringForTesting(model_str, std::move(file));

  run_loop.Run();

  EXPECT_TRUE(called);
  EXPECT_TRUE(service()->IsEnabled());
}

TEST_F(ClientSidePhishingModelTest, DoesNotNotifyOnBadInitialUpdate) {
  service()->SetVisualTfLiteModelForTesting(base::File());
  service()->ClearMappedRegionForTesting();
  service()->SetModelTypeForTesting(CSDModelType::kNone);

  base::RunLoop run_loop;
  bool called = false;
  base::CallbackListSubscription subscription =
      service()->RegisterCallback(base::BindRepeating(
          [](base::RepeatingClosure quit_closure, bool* called) {
            *called = true;
            std::move(quit_closure).Run();
          },
          run_loop.QuitClosure(), &called));

  service()->SetModelStringForTesting("", base::File());

  run_loop.RunUntilIdle();

  EXPECT_FALSE(called);
  EXPECT_FALSE(service()->IsEnabled());
}

TEST_F(ClientSidePhishingModelTest, DoesNotNotifyOnBadFollowingUpdate) {
  service()->SetVisualTfLiteModelForTesting(base::File());
  service()->ClearMappedRegionForTesting();
  service()->SetModelTypeForTesting(CSDModelType::kNone);

  base::RunLoop run_loop;

  // Perform a valid update.
  base::ScopedTempDir temp_dir;
  ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
  const base::FilePath file_path =
      temp_dir.GetPath().AppendASCII("visual_model.tflite");
  base::File file(file_path, base::File::FLAG_OPEN_ALWAYS |
                                 base::File::FLAG_READ |
                                 base::File::FLAG_WRITE);
  const std::string_view file_contents = "visual model file";
  file.WriteAtCurrentPos(base::as_byte_span(file_contents));

  const std::string model_str = CreateFlatBufferString();
  service()->SetModelStringForTesting(model_str, std::move(file));

  run_loop.RunUntilIdle();

  // Perform an invalid update.
  bool called = false;
  base::CallbackListSubscription subscription =
      service()->RegisterCallback(base::BindRepeating(
          [](base::RepeatingClosure quit_closure, bool* called) {
            *called = true;
            std::move(quit_closure).Run();
          },
          run_loop.QuitClosure(), &called));

  service()->SetModelStringForTesting("", base::File());

  run_loop.RunUntilIdle();

  EXPECT_FALSE(called);
  EXPECT_TRUE(service()->IsEnabled());
}

TEST_F(ClientSidePhishingModelTest, CanOverrideFlatBufferWithFlag) {
  service()->SetVisualTfLiteModelForTesting(base::File());
  service()->ClearMappedRegionForTesting();
  service()->SetModelTypeForTesting(CSDModelType::kNone);

  base::test::ScopedCommandLine command_line;
  base::ScopedTempDir temp_dir;
  ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
  const base::FilePath nonexistent_path =
      temp_dir.GetPath().AppendASCII("nonexistent");
  command_line.GetProcessCommandLine()->AppendSwitchPath(
      "csd-model-override-path", nonexistent_path);

  // Try overriding without setting anything in file path initially.
  service()->MaybeOverrideModel();
  EXPECT_EQ(service()->GetModelType(), CSDModelType::kNone);

  const base::FilePath empty_path;

  command_line.GetProcessCommandLine()->AppendSwitchPath(
      "csd-model-override-path", empty_path);

  // Try overriding now with just an empty file path.
  service()->MaybeOverrideModel();
  EXPECT_EQ(service()->GetModelType(), CSDModelType::kNone);

  const base::FilePath file_path = temp_dir.GetPath();
  command_line.GetProcessCommandLine()->AppendSwitchPath(
      "csd-model-override-path", file_path);

  // Try overriding now with just a valid file path, but no files.
  service()->MaybeOverrideModel();
  EXPECT_EQ(service()->GetModelType(), CSDModelType::kNone);

  base::File file(file_path.AppendASCII("client_model.pb"),
                  base::File::FLAG_OPEN_ALWAYS | base::File::FLAG_READ |
                      base::File::FLAG_WRITE);

  const std::string file_contents = CreateFlatBufferString();
  file.WriteAtCurrentPos(base::as_byte_span(file_contents));

  base::RunLoop run_loop;
  bool called = false;
  base::CallbackListSubscription subscription =
      service()->RegisterCallback(base::BindRepeating(
          [](base::RepeatingClosure quit_closure, bool* called) {
            *called = true;
            std::move(quit_closure).Run();
          },
          run_loop.QuitClosure(), &called));

  // We now have everything, so we can expect the subscription to properly run
  // and the model will be set.
  service()->MaybeOverrideModel();

  run_loop.Run();

  std::string model_str_from_shared_mem;
  ASSERT_NO_FATAL_FAILURE(GetFlatBufferStringFromMappedMemory(
      service()->GetModelSharedMemoryRegion(), &model_str_from_shared_mem));
  EXPECT_EQ(model_str_from_shared_mem, file_contents);
  EXPECT_EQ(service()->GetModelType(), CSDModelType::kFlatbuffer);
  EXPECT_TRUE(called);
}

TEST_F(ClientSidePhishingModelTest, AcceptsValidFlatbuffer) {
  service()->SetVisualTfLiteModelForTesting(base::File());
  service()->ClearMappedRegionForTesting();
  service()->SetModelTypeForTesting(CSDModelType::kNone);

  base::RunLoop run_loop;
  bool called = false;
  base::CallbackListSubscription subscription =
      service()->RegisterCallback(base::BindRepeating(
          [](base::RepeatingClosure quit_closure, bool* called) {
            *called = true;
            std::move(quit_closure).Run();
          },
          run_loop.QuitClosure(), &called));

  const std::string model_str = CreateFlatBufferString();
  base::ScopedTempDir temp_dir;
  ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
  const base::FilePath file_path =
      temp_dir.GetPath().AppendASCII("visual_model.tflite");
  base::File file(file_path, base::File::FLAG_OPEN_ALWAYS |
                                 base::File::FLAG_READ |
                                 base::File::FLAG_WRITE);
  const std::string_view file_contents = "visual model file";
  file.WriteAtCurrentPos(base::as_byte_span(file_contents));
  service()->SetModelStringForTesting(model_str, std::move(file));
  run_loop.Run();

  EXPECT_TRUE(service()->IsEnabled());

  std::string model_str_from_shared_mem;
  ASSERT_NO_FATAL_FAILURE(GetFlatBufferStringFromMappedMemory(
      service()->GetModelSharedMemoryRegion(), &model_str_from_shared_mem));
  EXPECT_EQ(model_str, model_str_from_shared_mem);
  EXPECT_EQ(service()->GetModelType(), CSDModelType::kFlatbuffer);

  EXPECT_TRUE(called);
}

TEST_F(ClientSidePhishingModelTest, FlatbufferOnFollowingUpdate) {
  service()->SetVisualTfLiteModelForTesting(base::File());
  service()->ClearMappedRegionForTesting();
  service()->SetModelTypeForTesting(CSDModelType::kNone);

  base::RunLoop run_loop;

  const std::string model_str1 = CreateFlatBufferString();
  base::ScopedTempDir temp_dir;
  ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
  const base::FilePath file_path =
      temp_dir.GetPath().AppendASCII("visual_model.tflite");
  base::File file(file_path, base::File::FLAG_OPEN_ALWAYS |
                                 base::File::FLAG_READ |
                                 base::File::FLAG_WRITE);
  const std::string_view file_contents = "visual model file";
  file.WriteAtCurrentPos(base::as_byte_span(file_contents));
  service()->SetModelStringForTesting(model_str1, std::move(file));

  run_loop.RunUntilIdle();
  EXPECT_TRUE(service()->IsEnabled());

  std::string model_str_from_shared_mem1;

  ASSERT_NO_FATAL_FAILURE(GetFlatBufferStringFromMappedMemory(
      service()->GetModelSharedMemoryRegion(), &model_str_from_shared_mem1));
  EXPECT_EQ(model_str1, model_str_from_shared_mem1);
  EXPECT_EQ(service()->GetModelType(), CSDModelType::kFlatbuffer);
  // Should be able to write to memory with WritableSharedMemoryMapping field.
  void* memory_addr = service()->GetFlatBufferMemoryAddressForTesting();

  EXPECT_EQ(memset(memory_addr, 'G', 1), memory_addr);

  bool called = false;
  base::CallbackListSubscription subscription =
      service()->RegisterCallback(base::BindRepeating(
          [](base::RepeatingClosure quit_closure, bool* called) {
            *called = true;
            std::move(quit_closure).Run();
          },
          run_loop.QuitClosure(), &called));

  const std::string model_str2 = CreateFlatBufferString();
  base::ScopedTempDir temp_dir2;
  ASSERT_TRUE(temp_dir2.CreateUniqueTempDir());
  const base::FilePath file_path2 =
      temp_dir2.GetPath().AppendASCII("visual_model.tflite");
  base::File file2(file_path2, base::File::FLAG_OPEN_ALWAYS |
                                   base::File::FLAG_READ |
                                   base::File::FLAG_WRITE);
  const std::string_view file_contents2 = "visual model file";
  file2.WriteAtCurrentPos(base::as_byte_span(file_contents2));
  service()->SetModelStringForTesting(model_str2, std::move(file2));

  run_loop.RunUntilIdle();
  EXPECT_TRUE(called);
  EXPECT_TRUE(service()->IsEnabled());
  std::string model_str_from_shared_mem2;
  ASSERT_NO_FATAL_FAILURE(GetFlatBufferStringFromMappedMemory(
      service()->GetModelSharedMemoryRegion(), &model_str_from_shared_mem2));
  EXPECT_EQ(model_str2, model_str_from_shared_mem2);
  EXPECT_EQ(service()->GetModelType(), CSDModelType::kFlatbuffer);

  // Mapping should be undone automatically, even with a region copy lying
  // around.
  // Can remove this if flaky.
  // Windows ASAN flake: crbug.com/1234652
#if !(BUILDFLAG(IS_WIN) && defined(ADDRESS_SANITIZER))
  BASE_EXPECT_DEATH(memset(memory_addr, 'G', 1), "");
#endif
}

}  // namespace safe_browsing