File: gcp_fakes.h

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 (781 lines) | stat: -rw-r--r-- 27,928 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
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
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
// Copyright 2018 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef CHROME_CREDENTIAL_PROVIDER_TEST_GCP_FAKES_H_
#define CHROME_CREDENTIAL_PROVIDER_TEST_GCP_FAKES_H_

#include <deque>
#include <list>
#include <map>
#include <memory>
#include <string>
#include <thread>
#include <unordered_map>
#include <vector>

#include "base/memory/raw_ptr.h"
#include "base/memory/raw_ref.h"
#include "base/synchronization/waitable_event.h"
#include "base/task/single_thread_task_runner.h"
#include "base/test/test_reg_util_win.h"
#include "base/win/scoped_handle.h"
#include "chrome/credential_provider/extension/extension_utils.h"
#include "chrome/credential_provider/extension/os_service_manager.h"
#include "chrome/credential_provider/extension/task_manager.h"
#include "chrome/credential_provider/gaiacp/associated_user_validator.h"
#include "chrome/credential_provider/gaiacp/chrome_availability_checker.h"
#include "chrome/credential_provider/gaiacp/device_policies_manager.h"
#include "chrome/credential_provider/gaiacp/event_logging_api_manager.h"
#include "chrome/credential_provider/gaiacp/event_logs_upload_manager.h"
#include "chrome/credential_provider/gaiacp/gem_device_details_manager.h"
#include "chrome/credential_provider/gaiacp/internet_availability_checker.h"
#include "chrome/credential_provider/gaiacp/os_process_manager.h"
#include "chrome/credential_provider/gaiacp/os_user_manager.h"
#include "chrome/credential_provider/gaiacp/password_recovery_manager.h"
#include "chrome/credential_provider/gaiacp/scoped_lsa_policy.h"
#include "chrome/credential_provider/gaiacp/scoped_user_profile.h"
#include "chrome/credential_provider/gaiacp/token_generator.h"
#include "chrome/credential_provider/gaiacp/user_policies_manager.h"
#include "chrome/credential_provider/gaiacp/win_http_url_fetcher.h"
#include "chrome/credential_provider/setup/gcpw_files.h"

class GaiaId;

namespace base {
class WaitableEvent;
}

namespace credential_provider {

enum class FAILEDOPERATIONS {
  ADD_USER,
  CHANGE_PASSWORD,
  GET_USER_FULLNAME,
  SET_USER_FULLNAME
};

void InitializeRegistryOverrideForTesting(
    registry_util::RegistryOverrideManager* registry_override);

///////////////////////////////////////////////////////////////////////////////

class FakeOSProcessManager : public OSProcessManager {
 public:
  FakeOSProcessManager();
  ~FakeOSProcessManager() override;

  // OSProcessManager
  HRESULT GetTokenLogonSID(const base::win::ScopedHandle& token,
                           PSID* sid) override;
  HRESULT SetupPermissionsForLogonSid(PSID sid) override;
  HRESULT CreateProcessWithToken(
      const base::win::ScopedHandle& logon_token,
      const base::CommandLine& command_line,
      _STARTUPINFOW* startupinfo,
      base::win::ScopedProcessInformation* procinfo) override;

 private:
  raw_ptr<OSProcessManager> original_manager_;
  DWORD next_rid_ = 0;
};

///////////////////////////////////////////////////////////////////////////////

class FakeOSUserManager : public OSUserManager {
 public:
  FakeOSUserManager();
  ~FakeOSUserManager() override;

  // OSUserManager
  HRESULT GenerateRandomPassword(wchar_t* password, int length) override;
  HRESULT AddUser(const wchar_t* username,
                  const wchar_t* password,
                  const wchar_t* fullname,
                  const wchar_t* comment,
                  bool add_to_users_group,
                  BSTR* sid,
                  DWORD* error) override;
  // Add a user to the OS with domain associated with it.
  HRESULT AddUser(const wchar_t* username,
                  const wchar_t* password,
                  const wchar_t* fullname,
                  const wchar_t* comment,
                  bool add_to_users_group,
                  const wchar_t* domain,
                  BSTR* sid,
                  DWORD* error);
  HRESULT ChangeUserPassword(const wchar_t* domain,
                             const wchar_t* username,
                             const wchar_t* password,
                             const wchar_t* old_password) override;
  HRESULT SetUserPassword(const wchar_t* domain,
                          const wchar_t* username,
                          const wchar_t* password) override;
  HRESULT SetUserFullname(const wchar_t* domain,
                          const wchar_t* username,
                          const wchar_t* full_name) override;
  HRESULT IsWindowsPasswordValid(const wchar_t* domain,
                                 const wchar_t* username,
                                 const wchar_t* password) override;

  HRESULT CreateLogonToken(const wchar_t* domain,
                           const wchar_t* username,
                           const wchar_t* password,
                           bool interactive,
                           base::win::ScopedHandle* token) override;

  HRESULT GetUserSID(const wchar_t* domain,
                     const wchar_t* username,
                     PSID* sid) override;

  HRESULT FindUserBySID(const wchar_t* sid,
                        wchar_t* username,
                        DWORD username_size,
                        wchar_t* domain,
                        DWORD domain_size) override;
  HRESULT RemoveUser(const wchar_t* username, const wchar_t* password) override;

  HRESULT GetUserFullname(const wchar_t* domain,
                          const wchar_t* username,
                          std::wstring* fullname) override;

  HRESULT ModifyUserAccessWithLogonHours(const wchar_t* domain,
                                         const wchar_t* username,
                                         bool allow) override;

  HRESULT SetDefaultPasswordChangePolicies(const wchar_t* domain,
                                           const wchar_t* username) override;

  bool IsDeviceDomainJoined() override;

  void SetIsDeviceDomainJoined(bool is_device_domain_joined) {
    is_device_domain_joined_ = is_device_domain_joined;
  }

  void FailFindUserBySID(const wchar_t* sid, int number_of_failures);

  struct UserInfo {
    UserInfo(const wchar_t* domain,
             const wchar_t* password,
             const wchar_t* fullname,
             const wchar_t* comment,
             const wchar_t* sid);
    UserInfo();
    UserInfo(const UserInfo& other);
    ~UserInfo();

    bool operator==(const UserInfo& other) const;

    std::wstring domain;
    std::wstring password;
    std::wstring fullname;
    std::wstring comment;
    std::wstring sid;
  };
  const UserInfo GetUserInfo(const wchar_t* username);

  // Creates a new unique sid.  Free returned sid with FreeSid().
  HRESULT CreateNewSID(PSID* sid);

  // Creates a fake user with the given |username|, |password|, |fullname|,
  // |comment|. If |gaia_id| is non-empty, also associates the user with
  // the given gaia id. If |email| is non-empty, sets the email to use for
  // reauth to be this one.
  // |sid| is allocated and filled with the SID of the new user.
  HRESULT CreateTestOSUser(const std::wstring& username,
                           const std::wstring& password,
                           const std::wstring& fullname,
                           const std::wstring& comment,
                           const GaiaId& gaia_id,
                           const std::wstring& email,
                           BSTR* sid);

  // Creates a fake user with the given |username|, |password|, |fullname|,
  // |comment| and |domain|. If |gaia_id| is non-empty, also associates the
  // user with the given gaia id. If |email| is non-empty, sets the email to
  // use for reauth to be this one.
  // |sid| is allocated and filled with the SID of the new user.
  HRESULT CreateTestOSUser(const std::wstring& username,
                           const std::wstring& password,
                           const std::wstring& fullname,
                           const std::wstring& comment,
                           const GaiaId& gaia_id,
                           const std::wstring& email,
                           const std::wstring& domain,
                           BSTR* sid);

  size_t GetUserCount() const { return username_to_info_.size(); }
  std::vector<std::pair<std::wstring, std::wstring>> GetUsers() const;

  void SetFailureReason(FAILEDOPERATIONS failed_operaetion,
                        HRESULT failure_reason) {
    failure_reasons_[failed_operaetion] = failure_reason;
  }

  bool DoesOperationFail(FAILEDOPERATIONS op) {
    return failure_reasons_.find(op) != failure_reasons_.end();
  }

  void RestoreOperation(FAILEDOPERATIONS op) { failure_reasons_.erase(op); }

 private:
  raw_ptr<OSUserManager> original_manager_;
  DWORD next_rid_ = 0;
  std::map<std::wstring, UserInfo> username_to_info_;
  bool is_device_domain_joined_ = false;
  std::map<FAILEDOPERATIONS, HRESULT> failure_reasons_;
  std::map<std::wstring, int> to_be_failed_find_user_sids_;
};

///////////////////////////////////////////////////////////////////////////////

class FakeScopedLsaPolicyFactory {
 public:
  FakeScopedLsaPolicyFactory();
  virtual ~FakeScopedLsaPolicyFactory();

  ScopedLsaPolicy::CreatorCallback GetCreatorCallback();

  // PrivateDataMap is a string-to-string key/value store that maps private
  // names to their corresponding data strings.  The term "private" here is
  // used to reflect the name of the underlying OS calls.  This data is meant
  // to be shared by all ScopedLsaPolicy instances created by this factory.
  using PrivateDataMap = std::map<std::wstring, std::wstring>;
  PrivateDataMap& private_data() { return private_data_; }

 private:
  std::unique_ptr<ScopedLsaPolicy> Create(ACCESS_MASK mask);

  ScopedLsaPolicy::CreatorCallback original_creator_;
  PrivateDataMap private_data_;
};

class FakeScopedLsaPolicy : public ScopedLsaPolicy {
 public:
  ~FakeScopedLsaPolicy() override;

  // ScopedLsaPolicy
  HRESULT StorePrivateData(const wchar_t* key, const wchar_t* value) override;
  HRESULT RemovePrivateData(const wchar_t* key) override;
  HRESULT RetrievePrivateData(const wchar_t* key,
                              wchar_t* value,
                              size_t length) override;
  bool PrivateDataExists(const wchar_t* key) override;
  HRESULT AddAccountRights(PSID sid,
                           const std::vector<std::wstring>& rights) override;
  HRESULT RemoveAccountRights(PSID sid,
                              const std::vector<std::wstring>& rights) override;
  HRESULT RemoveAccount(PSID sid) override;

 private:
  friend class FakeScopedLsaPolicyFactory;

  explicit FakeScopedLsaPolicy(FakeScopedLsaPolicyFactory* factory);

  FakeScopedLsaPolicyFactory::PrivateDataMap& private_data() {
    return factory_->private_data();
  }

  raw_ptr<FakeScopedLsaPolicyFactory> factory_;
};

///////////////////////////////////////////////////////////////////////////////

// A scoped FakeScopedUserProfile factory.  Installs itself when constructed
// and removes itself when deleted.
class FakeScopedUserProfileFactory {
 public:
  FakeScopedUserProfileFactory();
  virtual ~FakeScopedUserProfileFactory();

 private:
  std::unique_ptr<ScopedUserProfile> Create(const std::wstring& sid,
                                            const std::wstring& domain,
                                            const std::wstring& username,
                                            const std::wstring& password);

  ScopedUserProfile::CreatorCallback original_creator_;
};

class FakeScopedUserProfile : public ScopedUserProfile {
 public:
  HRESULT SaveAccountInfo(const base::Value::Dict& properties) override;

 private:
  friend class FakeScopedUserProfileFactory;

  FakeScopedUserProfile(const std::wstring& sid,
                        const std::wstring& domain,
                        const std::wstring& username,
                        const std::wstring& password);
  ~FakeScopedUserProfile() override;

  bool is_valid_ = false;
};

///////////////////////////////////////////////////////////////////////////////

// A scoped FakeWinHttpUrlFetcher factory.  Installs itself when constructed
// and removes itself when deleted.
class FakeWinHttpUrlFetcherFactory {
 public:
  FakeWinHttpUrlFetcherFactory();
  ~FakeWinHttpUrlFetcherFactory();

  // Returns the fetcher callback function being used. This can be used to
  // install the same fake explicitly in all the components being used. Those
  // components would otherwise have different fakes created automatically when
  // they get initialized.
  WinHttpUrlFetcher::CreatorCallback GetCreatorCallback();

  // Sets the given |response| for any number of HTTP requests made for |url|.
  void SetFakeResponse(
      const GURL& url,
      const WinHttpUrlFetcher::Headers& headers,
      const std::string& response,
      HANDLE send_response_event_handle = INVALID_HANDLE_VALUE);

  // Queues the given |response| for the specified |num_requests| number of HTTP
  // requests made for |url|. Different responses for the URL can be set by
  // calling this function multiple times with different responses.
  void SetFakeResponseForSpecifiedNumRequests(
      const GURL& url,
      const WinHttpUrlFetcher::Headers& headers,
      const std::string& response,
      unsigned int num_requests,
      HANDLE send_response_event_handle = INVALID_HANDLE_VALUE);

  // Sets the response as a failed http attempt. The return result
  // from http_url_fetcher.Fetch() would be set as the input HRESULT
  // to this method.
  void SetFakeFailedResponse(const GURL& url, HRESULT failed_hr);

  // Sets the option to collect request data for each URL fetcher created.
  void SetCollectRequestData(bool value) { collect_request_data_ = value; }

  // Data used to make each HTTP request by the fetcher.
  struct RequestData {
    RequestData();
    RequestData(const RequestData& rhs);
    ~RequestData();
    WinHttpUrlFetcher::Headers headers;
    std::string body;
    int timeout_in_millis;
  };

  // Returns the request data for the request identified by |request_index|.
  RequestData GetRequestData(size_t request_index) const;

  // Returns the number of requests created.
  size_t requests_created() const { return requests_created_; }

 private:
  std::unique_ptr<WinHttpUrlFetcher> Create(const GURL& url);

  WinHttpUrlFetcher::CreatorCallback original_creator_;
  WinHttpUrlFetcher::CreatorCallback fake_creator_;

  struct Response {
    Response();
    Response(const Response& rhs);
    Response(const WinHttpUrlFetcher::Headers& new_headers,
             const std::string& new_response,
             HANDLE new_send_response_event_handle);
    ~Response();
    WinHttpUrlFetcher::Headers headers;
    std::string response;
    HANDLE send_response_event_handle;
  };

  std::map<GURL, std::deque<Response>> fake_responses_;
  std::map<GURL, HRESULT> failed_http_fetch_hr_;
  size_t requests_created_ = 0;
  bool collect_request_data_ = false;
  bool remove_fake_response_when_created_ = false;
  std::vector<RequestData> requests_data_;
};

class FakeWinHttpUrlFetcher : public WinHttpUrlFetcher {
 public:
  explicit FakeWinHttpUrlFetcher(const GURL& url);
  ~FakeWinHttpUrlFetcher() override;

  using WinHttpUrlFetcher::Headers;

  const Headers& response_headers() const { return response_headers_; }

  // WinHttpUrlFetcher
  bool IsValid() const override;
  HRESULT SetRequestHeader(const char* name, const char* value) override;
  HRESULT SetRequestBody(const char* body) override;
  HRESULT SetHttpRequestTimeout(const int timeout_in_millis) override;
  HRESULT Fetch(std::vector<char>* response) override;
  HRESULT Close() override;

 private:
  friend FakeWinHttpUrlFetcherFactory;
  typedef FakeWinHttpUrlFetcherFactory::RequestData RequestData;

  Headers response_headers_;
  std::string response_;
  HANDLE send_response_event_handle_;
  HRESULT response_hr_ = S_OK;
  raw_ptr<RequestData> request_data_ = nullptr;
};

///////////////////////////////////////////////////////////////////////////////

class FakeAssociatedUserValidator : public AssociatedUserValidator {
 public:
  FakeAssociatedUserValidator();
  explicit FakeAssociatedUserValidator(base::TimeDelta validation_timeout);
  ~FakeAssociatedUserValidator() override;

  using AssociatedUserValidator::ForceRefreshTokenHandlesForTesting;
  using AssociatedUserValidator::IsUserAccessBlockedForTesting;

 private:
  raw_ptr<AssociatedUserValidator> original_validator_ = nullptr;
};

///////////////////////////////////////////////////////////////////////////////

class FakeChromeAvailabilityChecker : public ChromeAvailabilityChecker {
 public:
  enum HasSupportedChromeCheckType {
    kChromeForceYes,
    kChromeForceNo,
    kChromeDontForce  // Uses the original checker to get result.
  };

  FakeChromeAvailabilityChecker(
      HasSupportedChromeCheckType has_supported_chrome = kChromeForceYes);
  ~FakeChromeAvailabilityChecker() override;

  bool HasSupportedChromeVersion() override;
  void SetHasSupportedChrome(HasSupportedChromeCheckType has_supported_chrome);

 private:
  raw_ptr<ChromeAvailabilityChecker> original_checker_ = nullptr;

  // Used during tests to force the credential provider to believe if a
  // supported Chrome version is installed or not. In production a real
  // check is performed at runtime.
  HasSupportedChromeCheckType has_supported_chrome_ = kChromeForceYes;
};

///////////////////////////////////////////////////////////////////////////////

class FakeInternetAvailabilityChecker : public InternetAvailabilityChecker {
 public:
  enum HasInternetConnectionCheckType { kHicForceYes, kHicForceNo };

  FakeInternetAvailabilityChecker(
      HasInternetConnectionCheckType has_internet_connection = kHicForceYes);
  ~FakeInternetAvailabilityChecker() override;

  bool HasInternetConnection() override;
  void SetHasInternetConnection(
      HasInternetConnectionCheckType has_internet_connection);

 private:
  raw_ptr<InternetAvailabilityChecker> original_checker_ = nullptr;

  // Used during tests to force the credential provider to believe if an
  // internet connection is possible or not.  In production the value is
  // always set to HIC_CHECK_ALWAYS to perform a real check at runtime.
  HasInternetConnectionCheckType has_internet_connection_ = kHicForceYes;
};

///////////////////////////////////////////////////////////////////////////////

class FakePasswordRecoveryManager : public PasswordRecoveryManager {
 public:
  FakePasswordRecoveryManager();
  explicit FakePasswordRecoveryManager(
      base::TimeDelta encryption_key_request_timeout,
      base::TimeDelta decryption_key_request_timeout);
  ~FakePasswordRecoveryManager() override;

  using PasswordRecoveryManager::MakeGenerateKeyPairResponseForTesting;
  using PasswordRecoveryManager::MakeGetPrivateKeyResponseForTesting;
  using PasswordRecoveryManager::SetRequestTimeoutForTesting;

 private:
  raw_ptr<PasswordRecoveryManager> original_validator_ = nullptr;
};

///////////////////////////////////////////////////////////////////////////////

class FakeGemDeviceDetailsManager : public GemDeviceDetailsManager {
 public:
  FakeGemDeviceDetailsManager();
  explicit FakeGemDeviceDetailsManager(
      base::TimeDelta upload_device_details_request_timeout);
  ~FakeGemDeviceDetailsManager() override;

  using GemDeviceDetailsManager::GetRequestDictForTesting;
  using GemDeviceDetailsManager::GetUploadStatusForTesting;
  using GemDeviceDetailsManager::SetRequestTimeoutForTesting;

 private:
  raw_ptr<GemDeviceDetailsManager> original_manager_ = nullptr;
};

///////////////////////////////////////////////////////////////////////////////

class FakeEventLoggingApiManager : public EventLoggingApiManager {
 public:
  typedef EventLogsUploadManager::EventLogEntry EventLogEntry;

  EVT_HANDLE EvtQuery(EVT_HANDLE session,
                      LPCWSTR path,
                      LPCWSTR query,
                      DWORD flags) override;

  EVT_HANDLE EvtOpenPublisherMetadata(EVT_HANDLE session,
                                      LPCWSTR publisher_id,
                                      LPCWSTR log_file_path,
                                      LCID locale,
                                      DWORD flags) override;

  EVT_HANDLE EvtCreateRenderContext(DWORD value_paths_count,
                                    LPCWSTR* value_paths,
                                    DWORD flags) override;

  BOOL EvtNext(EVT_HANDLE result_set,
               DWORD events_size,
               PEVT_HANDLE events,
               DWORD timeout,
               DWORD flags,
               PDWORD num_returned) override;

  BOOL EvtGetQueryInfo(EVT_HANDLE query,
                       EVT_QUERY_PROPERTY_ID property_id,
                       DWORD value_buffer_size,
                       PEVT_VARIANT value_buffer,
                       PDWORD value_buffer_used) override;

  BOOL EvtRender(EVT_HANDLE context,
                 EVT_HANDLE evt_handle,
                 DWORD flags,
                 DWORD buffer_size,
                 PVOID buffer,
                 PDWORD buffer_used,
                 PDWORD property_count) override;

  BOOL EvtFormatMessage(EVT_HANDLE publisher_metadata,
                        EVT_HANDLE event,
                        DWORD message_id,
                        DWORD value_count,
                        PEVT_VARIANT values,
                        DWORD flags,
                        DWORD buffer_size,
                        LPWSTR buffer,
                        PDWORD buffer_used) override;

  BOOL EvtClose(EVT_HANDLE handle) override;

  DWORD GetLastError() override;

  explicit FakeEventLoggingApiManager(const std::vector<EventLogEntry>& logs);

  ~FakeEventLoggingApiManager() override;

 private:
  raw_ptr<EventLoggingApiManager> original_manager_ = nullptr;

  const raw_ref<const std::vector<EventLogEntry>> logs_;
  EVT_HANDLE query_handle_, publisher_metadata_, render_context_;
  DWORD last_error_;
  size_t next_event_idx_;
  std::vector<EVT_HANDLE> event_handles_;
  std::unordered_map<EVT_HANDLE, size_t> handle_to_index_map_;
};

class FakeEventLogsUploadManager : public EventLogsUploadManager {
 public:
  typedef EventLogsUploadManager::EventLogEntry EventLogEntry;

  // Construct with the logs that should be present in the fake event log.
  explicit FakeEventLogsUploadManager(const std::vector<EventLogEntry>& logs);
  ~FakeEventLogsUploadManager() override;

  // Get the last upload status of the call to UploadEventViewerLogs.
  HRESULT GetUploadStatus();

  // Get the number of successfully uploaded event logs.
  uint64_t GetNumLogsUploaded();

 private:
  raw_ptr<EventLogsUploadManager> original_manager_ = nullptr;
  FakeEventLoggingApiManager api_manager_;
};

///////////////////////////////////////////////////////////////////////////////

class FakeUserPoliciesManager : public UserPoliciesManager {
 public:
  FakeUserPoliciesManager();
  explicit FakeUserPoliciesManager(bool cloud_policies_enabled);
  ~FakeUserPoliciesManager() override;

  HRESULT FetchAndStoreCloudUserPolicies(
      const std::wstring& sid,
      const std::string& access_token) override;

  // Specify the policy to use for a user.
  void SetUserPolicies(const std::wstring& sid, const UserPolicies& policies);

  bool GetUserPolicies(const std::wstring& sid,
                       UserPolicies* policies) const override;

  // Specify whether user policy is valid for a user.
  void SetUserPolicyStaleOrMissing(const std::wstring& sid, bool status);

  bool IsUserPolicyStaleOrMissing(const std::wstring& sid) const override;

  // Returns the number of times FetchAndStoreCloudUserPolicies method was
  // called.
  int GetNumTimesFetchAndStoreCalled() const;

 private:
  raw_ptr<UserPoliciesManager> original_manager_ = nullptr;
  std::map<std::wstring, UserPolicies> user_policies_;
  int num_times_fetch_called_ = 0;
  std::map<std::wstring, bool> user_policies_stale_;
};

///////////////////////////////////////////////////////////////////////////////

class FakeDevicePoliciesManager : public DevicePoliciesManager {
 public:
  explicit FakeDevicePoliciesManager(bool cloud_policies_enabled);
  ~FakeDevicePoliciesManager() override;

  // Specify the policy to use for the device.
  void SetDevicePolicies(const DevicePolicies& policies);

  void GetDevicePolicies(DevicePolicies* device_policies) override;

 private:
  raw_ptr<DevicePoliciesManager> original_manager_ = nullptr;
  DevicePolicies device_policies_;
};

///////////////////////////////////////////////////////////////////////////////

class FakeGCPWFiles : public GCPWFiles {
 public:
  FakeGCPWFiles();
  ~FakeGCPWFiles() override;

  std::vector<base::FilePath::StringType> GetEffectiveInstallFiles() override;

 private:
  raw_ptr<GCPWFiles> original_files = nullptr;
};

///////////////////////////////////////////////////////////////////////////////

class FakeOSServiceManager : public extension::OSServiceManager {
 public:
  FakeOSServiceManager();
  ~FakeOSServiceManager() override;

  DWORD GetServiceStatus(SERVICE_STATUS* service_status) override;

  DWORD InstallService(const base::FilePath& service_binary_path,
                       extension::ScopedScHandle* sc_handle) override;

  DWORD StartServiceCtrlDispatcher(
      LPSERVICE_MAIN_FUNCTION service_main) override;

  DWORD RegisterCtrlHandler(
      LPHANDLER_FUNCTION handler_proc,
      SERVICE_STATUS_HANDLE* service_status_handle) override;

  DWORD SetServiceStatus(SERVICE_STATUS_HANDLE service_status_handle,
                         SERVICE_STATUS service) override;

  void SendControlRequestForTesting(DWORD control_request) {
    std::unique_lock<std::mutex> lock(m);
    queue.push_back(control_request);
    cv.notify_one();
  }

  DWORD DeleteService() override;

  DWORD ChangeServiceConfig(DWORD dwServiceType,
                            DWORD dwStartType,
                            DWORD dwErrorControl) override;

 private:
  DWORD GetControlRequestForTesting() {
    std::unique_lock<std::mutex> lock(m);
    cv.wait(lock, [&]() { return !queue.empty(); });
    DWORD result = queue.front();
    queue.pop_front();
    return result;
  }

  struct ServiceInfo {
    LPHANDLER_FUNCTION control_handler_cb_;
    SERVICE_STATUS service_status_;
  };

  // Primitives that are used to synchronize with the thread running service
  // main and the thread testing the code.
  std::list<DWORD> queue;
  std::mutex m;
  std::condition_variable cv;

  // Original instance of OSServiceManager.
  raw_ptr<extension::OSServiceManager> os_service_manager_ = nullptr;
  std::map<std::wstring, ServiceInfo> service_lookup_from_name_;
};

///////////////////////////////////////////////////////////////////////////////

class FakeTaskManager : public extension::TaskManager {
 public:
  FakeTaskManager();
  ~FakeTaskManager() override;

  int NumOfTimesExecuted(const std::string& task_name) {
    return num_of_times_executed_[task_name];
  }

 private:
  void ExecuteTask(scoped_refptr<base::SingleThreadTaskRunner> task_runner,
                   const std::string& task_name) override;

  // Original instance of TaskManager.
  raw_ptr<extension::TaskManager> task_manager_ = nullptr;

  // Counts the number of execution per task.
  std::map<std::string, int> num_of_times_executed_;
};

///////////////////////////////////////////////////////////////////////////////

class FakeTokenGenerator : public TokenGenerator {
 public:
  FakeTokenGenerator();
  ~FakeTokenGenerator() override;

  std::string GenerateToken() override;

  void SetTokensForTesting(const std::vector<std::string>& test_tokens);

 private:
  raw_ptr<TokenGenerator> token_generator_ = nullptr;
  std::vector<std::string> test_tokens_;
};

///////////////////////////////////////////////////////////////////////////////

}  // namespace credential_provider

#endif  // CHROME_CREDENTIAL_PROVIDER_TEST_GCP_FAKES_H_