1 // Copyright 2018 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #ifndef CHROME_CREDENTIAL_PROVIDER_TEST_GCP_FAKES_H_
6 #define CHROME_CREDENTIAL_PROVIDER_TEST_GCP_FAKES_H_
7 
8 #include <deque>
9 #include <list>
10 #include <map>
11 #include <memory>
12 #include <string>
13 #include <thread>
14 #include <vector>
15 
16 #include "base/strings/string16.h"
17 #include "base/synchronization/waitable_event.h"
18 #include "base/test/test_reg_util_win.h"
19 #include "base/win/scoped_handle.h"
20 #include "chrome/credential_provider/extension/os_service_manager.h"
21 #include "chrome/credential_provider/extension/task_manager.h"
22 #include "chrome/credential_provider/gaiacp/associated_user_validator.h"
23 #include "chrome/credential_provider/gaiacp/chrome_availability_checker.h"
24 #include "chrome/credential_provider/gaiacp/device_policies_manager.h"
25 #include "chrome/credential_provider/gaiacp/event_logging_api_manager.h"
26 #include "chrome/credential_provider/gaiacp/event_logs_upload_manager.h"
27 #include "chrome/credential_provider/gaiacp/gem_device_details_manager.h"
28 #include "chrome/credential_provider/gaiacp/internet_availability_checker.h"
29 #include "chrome/credential_provider/gaiacp/os_process_manager.h"
30 #include "chrome/credential_provider/gaiacp/os_user_manager.h"
31 #include "chrome/credential_provider/gaiacp/password_recovery_manager.h"
32 #include "chrome/credential_provider/gaiacp/scoped_lsa_policy.h"
33 #include "chrome/credential_provider/gaiacp/scoped_user_profile.h"
34 #include "chrome/credential_provider/gaiacp/token_generator.h"
35 #include "chrome/credential_provider/gaiacp/user_policies_manager.h"
36 #include "chrome/credential_provider/gaiacp/win_http_url_fetcher.h"
37 #include "chrome/credential_provider/setup/gcpw_files.h"
38 
39 namespace base {
40 class WaitableEvent;
41 }
42 
43 namespace credential_provider {
44 
45 enum class FAILEDOPERATIONS {
46   ADD_USER,
47   CHANGE_PASSWORD,
48   GET_USER_FULLNAME,
49   SET_USER_FULLNAME
50 };
51 
52 void InitializeRegistryOverrideForTesting(
53     registry_util::RegistryOverrideManager* registry_override);
54 
55 ///////////////////////////////////////////////////////////////////////////////
56 
57 class FakeOSProcessManager : public OSProcessManager {
58  public:
59   FakeOSProcessManager();
60   ~FakeOSProcessManager() override;
61 
62   // OSProcessManager
63   HRESULT GetTokenLogonSID(const base::win::ScopedHandle& token,
64                            PSID* sid) override;
65   HRESULT SetupPermissionsForLogonSid(PSID sid) override;
66   HRESULT CreateProcessWithToken(
67       const base::win::ScopedHandle& logon_token,
68       const base::CommandLine& command_line,
69       _STARTUPINFOW* startupinfo,
70       base::win::ScopedProcessInformation* procinfo) override;
71 
72  private:
73   OSProcessManager* original_manager_;
74   DWORD next_rid_ = 0;
75 };
76 
77 ///////////////////////////////////////////////////////////////////////////////
78 
79 class FakeOSUserManager : public OSUserManager {
80  public:
81   FakeOSUserManager();
82   ~FakeOSUserManager() override;
83 
84   // OSUserManager
85   HRESULT GenerateRandomPassword(wchar_t* password, int length) override;
86   HRESULT AddUser(const wchar_t* username,
87                   const wchar_t* password,
88                   const wchar_t* fullname,
89                   const wchar_t* comment,
90                   bool add_to_users_group,
91                   BSTR* sid,
92                   DWORD* error) override;
93   // Add a user to the OS with domain associated with it.
94   HRESULT AddUser(const wchar_t* username,
95                   const wchar_t* password,
96                   const wchar_t* fullname,
97                   const wchar_t* comment,
98                   bool add_to_users_group,
99                   const wchar_t* domain,
100                   BSTR* sid,
101                   DWORD* error);
102   HRESULT ChangeUserPassword(const wchar_t* domain,
103                              const wchar_t* username,
104                              const wchar_t* password,
105                              const wchar_t* old_password) override;
106   HRESULT SetUserPassword(const wchar_t* domain,
107                           const wchar_t* username,
108                           const wchar_t* password) override;
109   HRESULT SetUserFullname(const wchar_t* domain,
110                           const wchar_t* username,
111                           const wchar_t* full_name) override;
112   HRESULT IsWindowsPasswordValid(const wchar_t* domain,
113                                  const wchar_t* username,
114                                  const wchar_t* password) override;
115 
116   HRESULT CreateLogonToken(const wchar_t* domain,
117                            const wchar_t* username,
118                            const wchar_t* password,
119                            bool interactive,
120                            base::win::ScopedHandle* token) override;
121   HRESULT GetUserSID(const wchar_t* domain,
122                      const wchar_t* username,
123                      PSID* sid) override;
124   HRESULT FindUserBySID(const wchar_t* sid,
125                         wchar_t* username,
126                         DWORD username_size,
127                         wchar_t* domain,
128                         DWORD domain_size) override;
129   HRESULT RemoveUser(const wchar_t* username, const wchar_t* password) override;
130 
131   HRESULT GetUserFullname(const wchar_t* domain,
132                           const wchar_t* username,
133                           base::string16* fullname) override;
134 
135   HRESULT ModifyUserAccessWithLogonHours(const wchar_t* domain,
136                                          const wchar_t* username,
137                                          bool allow) override;
138 
139   HRESULT SetDefaultPasswordChangePolicies(const wchar_t* domain,
140                                            const wchar_t* username) override;
141 
142   bool IsDeviceDomainJoined() override;
143 
SetIsDeviceDomainJoined(bool is_device_domain_joined)144   void SetIsDeviceDomainJoined(bool is_device_domain_joined) {
145     is_device_domain_joined_ = is_device_domain_joined;
146   }
147 
148   struct UserInfo {
149     UserInfo(const wchar_t* domain,
150              const wchar_t* password,
151              const wchar_t* fullname,
152              const wchar_t* comment,
153              const wchar_t* sid);
154     UserInfo();
155     UserInfo(const UserInfo& other);
156     ~UserInfo();
157 
158     bool operator==(const UserInfo& other) const;
159 
160     base::string16 domain;
161     base::string16 password;
162     base::string16 fullname;
163     base::string16 comment;
164     base::string16 sid;
165   };
166   const UserInfo GetUserInfo(const wchar_t* username);
167 
168   // Creates a new unique sid.  Free returned sid with FreeSid().
169   HRESULT CreateNewSID(PSID* sid);
170 
171   // Creates a fake user with the given |username|, |password|, |fullname|,
172   // |comment|. If |gaia_id| is non-empty, also associates the user with
173   // the given gaia id. If |email| is non-empty, sets the email to use for
174   // reauth to be this one.
175   // |sid| is allocated and filled with the SID of the new user.
176   HRESULT CreateTestOSUser(const base::string16& username,
177                            const base::string16& password,
178                            const base::string16& fullname,
179                            const base::string16& comment,
180                            const base::string16& gaia_id,
181                            const base::string16& email,
182                            BSTR* sid);
183 
184   // Creates a fake user with the given |username|, |password|, |fullname|,
185   // |comment| and |domain|. If |gaia_id| is non-empty, also associates the
186   // user with the given gaia id. If |email| is non-empty, sets the email to
187   // use for reauth to be this one.
188   // |sid| is allocated and filled with the SID of the new user.
189   HRESULT CreateTestOSUser(const base::string16& username,
190                            const base::string16& password,
191                            const base::string16& fullname,
192                            const base::string16& comment,
193                            const base::string16& gaia_id,
194                            const base::string16& email,
195                            const base::string16& domain,
196                            BSTR* sid);
197 
GetUserCount()198   size_t GetUserCount() const { return username_to_info_.size(); }
199   std::vector<std::pair<base::string16, base::string16>> GetUsers() const;
200 
SetFailureReason(FAILEDOPERATIONS failed_operaetion,HRESULT failure_reason)201   void SetFailureReason(FAILEDOPERATIONS failed_operaetion,
202                         HRESULT failure_reason) {
203     failure_reasons_[failed_operaetion] = failure_reason;
204   }
205 
DoesOperationFail(FAILEDOPERATIONS op)206   bool DoesOperationFail(FAILEDOPERATIONS op) {
207     return failure_reasons_.find(op) != failure_reasons_.end();
208   }
209 
RestoreOperation(FAILEDOPERATIONS op)210   void RestoreOperation(FAILEDOPERATIONS op) { failure_reasons_.erase(op); }
211 
212  private:
213   OSUserManager* original_manager_;
214   DWORD next_rid_ = 0;
215   std::map<base::string16, UserInfo> username_to_info_;
216   bool is_device_domain_joined_ = false;
217   std::map<FAILEDOPERATIONS, HRESULT> failure_reasons_;
218 };
219 
220 ///////////////////////////////////////////////////////////////////////////////
221 
222 class FakeScopedLsaPolicyFactory {
223  public:
224   FakeScopedLsaPolicyFactory();
225   virtual ~FakeScopedLsaPolicyFactory();
226 
227   ScopedLsaPolicy::CreatorCallback GetCreatorCallback();
228 
229   // PrivateDataMap is a string-to-string key/value store that maps private
230   // names to their corresponding data strings.  The term "private" here is
231   // used to reflect the name of the underlying OS calls.  This data is meant
232   // to be shared by all ScopedLsaPolicy instances created by this factory.
233   using PrivateDataMap = std::map<base::string16, base::string16>;
private_data()234   PrivateDataMap& private_data() { return private_data_; }
235 
236  private:
237   std::unique_ptr<ScopedLsaPolicy> Create(ACCESS_MASK mask);
238 
239   ScopedLsaPolicy::CreatorCallback original_creator_;
240   PrivateDataMap private_data_;
241 };
242 
243 class FakeScopedLsaPolicy : public ScopedLsaPolicy {
244  public:
245   ~FakeScopedLsaPolicy() override;
246 
247   // ScopedLsaPolicy
248   HRESULT StorePrivateData(const wchar_t* key, const wchar_t* value) override;
249   HRESULT RemovePrivateData(const wchar_t* key) override;
250   HRESULT RetrievePrivateData(const wchar_t* key,
251                               wchar_t* value,
252                               size_t length) override;
253   bool PrivateDataExists(const wchar_t* key) override;
254   HRESULT AddAccountRights(PSID sid,
255                            const std::vector<base::string16>& rights) override;
256   HRESULT RemoveAccountRights(
257       PSID sid,
258       const std::vector<base::string16>& rights) override;
259   HRESULT RemoveAccount(PSID sid) override;
260 
261  private:
262   friend class FakeScopedLsaPolicyFactory;
263 
264   explicit FakeScopedLsaPolicy(FakeScopedLsaPolicyFactory* factory);
265 
private_data()266   FakeScopedLsaPolicyFactory::PrivateDataMap& private_data() {
267     return factory_->private_data();
268   }
269 
270   FakeScopedLsaPolicyFactory* factory_;
271 };
272 
273 ///////////////////////////////////////////////////////////////////////////////
274 
275 // A scoped FakeScopedUserProfile factory.  Installs itself when constructed
276 // and removes itself when deleted.
277 class FakeScopedUserProfileFactory {
278  public:
279   FakeScopedUserProfileFactory();
280   virtual ~FakeScopedUserProfileFactory();
281 
282  private:
283   std::unique_ptr<ScopedUserProfile> Create(const base::string16& sid,
284                                             const base::string16& domain,
285                                             const base::string16& username,
286                                             const base::string16& password);
287 
288   ScopedUserProfile::CreatorCallback original_creator_;
289 };
290 
291 class FakeScopedUserProfile : public ScopedUserProfile {
292  public:
293   HRESULT SaveAccountInfo(const base::Value& properties) override;
294 
295  private:
296   friend class FakeScopedUserProfileFactory;
297 
298   FakeScopedUserProfile(const base::string16& sid,
299                         const base::string16& domain,
300                         const base::string16& username,
301                         const base::string16& password);
302   ~FakeScopedUserProfile() override;
303 
304   bool is_valid_ = false;
305 };
306 
307 ///////////////////////////////////////////////////////////////////////////////
308 
309 // A scoped FakeWinHttpUrlFetcher factory.  Installs itself when constructed
310 // and removes itself when deleted.
311 class FakeWinHttpUrlFetcherFactory {
312  public:
313   FakeWinHttpUrlFetcherFactory();
314   ~FakeWinHttpUrlFetcherFactory();
315 
316   // Returns the fetcher callback function being used. This can be used to
317   // install the same fake explicitly in all the components being used. Those
318   // components would otherwise have different fakes created automatically when
319   // they get initialized.
320   WinHttpUrlFetcher::CreatorCallback GetCreatorCallback();
321 
322   // Sets the given |response| for any number of HTTP requests made for |url|.
323   void SetFakeResponse(
324       const GURL& url,
325       const WinHttpUrlFetcher::Headers& headers,
326       const std::string& response,
327       HANDLE send_response_event_handle = INVALID_HANDLE_VALUE);
328 
329   // Queues the given |response| for the specified |num_requests| number of HTTP
330   // requests made for |url|. Different responses for the URL can be set by
331   // calling this function multiple times with different responses.
332   void SetFakeResponseForSpecifiedNumRequests(
333       const GURL& url,
334       const WinHttpUrlFetcher::Headers& headers,
335       const std::string& response,
336       unsigned int num_requests,
337       HANDLE send_response_event_handle = INVALID_HANDLE_VALUE);
338 
339   // Sets the response as a failed http attempt. The return result
340   // from http_url_fetcher.Fetch() would be set as the input HRESULT
341   // to this method.
342   void SetFakeFailedResponse(const GURL& url, HRESULT failed_hr);
343 
344   // Sets the option to collect request data for each URL fetcher created.
SetCollectRequestData(bool value)345   void SetCollectRequestData(bool value) { collect_request_data_ = value; }
346 
347   // Data used to make each HTTP request by the fetcher.
348   struct RequestData {
349     RequestData();
350     RequestData(const RequestData& rhs);
351     ~RequestData();
352     WinHttpUrlFetcher::Headers headers;
353     std::string body;
354     int timeout_in_millis;
355   };
356 
357   // Returns the request data for the request identified by |request_index|.
358   RequestData GetRequestData(size_t request_index) const;
359 
360   // Returns the number of requests created.
requests_created()361   size_t requests_created() const { return requests_created_; }
362 
363  private:
364   std::unique_ptr<WinHttpUrlFetcher> Create(const GURL& url);
365 
366   WinHttpUrlFetcher::CreatorCallback original_creator_;
367   WinHttpUrlFetcher::CreatorCallback fake_creator_;
368 
369   struct Response {
370     Response();
371     Response(const Response& rhs);
372     Response(const WinHttpUrlFetcher::Headers& new_headers,
373              const std::string& new_response,
374              HANDLE new_send_response_event_handle);
375     ~Response();
376     WinHttpUrlFetcher::Headers headers;
377     std::string response;
378     HANDLE send_response_event_handle;
379   };
380 
381   std::map<GURL, std::deque<Response>> fake_responses_;
382   std::map<GURL, HRESULT> failed_http_fetch_hr_;
383   size_t requests_created_ = 0;
384   bool collect_request_data_ = false;
385   bool remove_fake_response_when_created_ = false;
386   std::vector<RequestData> requests_data_;
387 };
388 
389 class FakeWinHttpUrlFetcher : public WinHttpUrlFetcher {
390  public:
391   explicit FakeWinHttpUrlFetcher(const GURL& url);
392   ~FakeWinHttpUrlFetcher() override;
393 
394   using WinHttpUrlFetcher::Headers;
395 
response_headers()396   const Headers& response_headers() const { return response_headers_; }
397 
398   // WinHttpUrlFetcher
399   bool IsValid() const override;
400   HRESULT SetRequestHeader(const char* name, const char* value) override;
401   HRESULT SetRequestBody(const char* body) override;
402   HRESULT SetHttpRequestTimeout(const int timeout_in_millis) override;
403   HRESULT Fetch(std::vector<char>* response) override;
404   HRESULT Close() override;
405 
406  private:
407   friend FakeWinHttpUrlFetcherFactory;
408   typedef FakeWinHttpUrlFetcherFactory::RequestData RequestData;
409 
410   Headers response_headers_;
411   std::string response_;
412   HANDLE send_response_event_handle_;
413   HRESULT response_hr_ = S_OK;
414   RequestData* request_data_ = nullptr;
415 };
416 
417 ///////////////////////////////////////////////////////////////////////////////
418 
419 class FakeAssociatedUserValidator : public AssociatedUserValidator {
420  public:
421   FakeAssociatedUserValidator();
422   explicit FakeAssociatedUserValidator(base::TimeDelta validation_timeout);
423   ~FakeAssociatedUserValidator() override;
424 
425   using AssociatedUserValidator::ForceRefreshTokenHandlesForTesting;
426   using AssociatedUserValidator::IsUserAccessBlockedForTesting;
427 
428  private:
429   AssociatedUserValidator* original_validator_ = nullptr;
430 };
431 
432 ///////////////////////////////////////////////////////////////////////////////
433 
434 class FakeChromeAvailabilityChecker : public ChromeAvailabilityChecker {
435  public:
436   enum HasSupportedChromeCheckType {
437     kChromeForceYes,
438     kChromeForceNo,
439     kChromeDontForce  // Uses the original checker to get result.
440   };
441 
442   FakeChromeAvailabilityChecker(
443       HasSupportedChromeCheckType has_supported_chrome = kChromeForceYes);
444   ~FakeChromeAvailabilityChecker() override;
445 
446   bool HasSupportedChromeVersion() override;
447   void SetHasSupportedChrome(HasSupportedChromeCheckType has_supported_chrome);
448 
449  private:
450   ChromeAvailabilityChecker* original_checker_ = nullptr;
451 
452   // Used during tests to force the credential provider to believe if a
453   // supported Chrome version is installed or not. In production a real
454   // check is performed at runtime.
455   HasSupportedChromeCheckType has_supported_chrome_ = kChromeForceYes;
456 };
457 
458 ///////////////////////////////////////////////////////////////////////////////
459 
460 class FakeInternetAvailabilityChecker : public InternetAvailabilityChecker {
461  public:
462   enum HasInternetConnectionCheckType { kHicForceYes, kHicForceNo };
463 
464   FakeInternetAvailabilityChecker(
465       HasInternetConnectionCheckType has_internet_connection = kHicForceYes);
466   ~FakeInternetAvailabilityChecker() override;
467 
468   bool HasInternetConnection() override;
469   void SetHasInternetConnection(
470       HasInternetConnectionCheckType has_internet_connection);
471 
472  private:
473   InternetAvailabilityChecker* original_checker_ = nullptr;
474 
475   // Used during tests to force the credential provider to believe if an
476   // internet connection is possible or not.  In production the value is
477   // always set to HIC_CHECK_ALWAYS to perform a real check at runtime.
478   HasInternetConnectionCheckType has_internet_connection_ = kHicForceYes;
479 };
480 
481 ///////////////////////////////////////////////////////////////////////////////
482 
483 class FakePasswordRecoveryManager : public PasswordRecoveryManager {
484  public:
485   FakePasswordRecoveryManager();
486   explicit FakePasswordRecoveryManager(
487       base::TimeDelta encryption_key_request_timeout,
488       base::TimeDelta decryption_key_request_timeout);
489   ~FakePasswordRecoveryManager() override;
490 
491   using PasswordRecoveryManager::MakeGenerateKeyPairResponseForTesting;
492   using PasswordRecoveryManager::MakeGetPrivateKeyResponseForTesting;
493   using PasswordRecoveryManager::SetRequestTimeoutForTesting;
494 
495  private:
496   PasswordRecoveryManager* original_validator_ = nullptr;
497 };
498 
499 ///////////////////////////////////////////////////////////////////////////////
500 
501 class FakeGemDeviceDetailsManager : public GemDeviceDetailsManager {
502  public:
503   FakeGemDeviceDetailsManager();
504   explicit FakeGemDeviceDetailsManager(
505       base::TimeDelta upload_device_details_request_timeout);
506   ~FakeGemDeviceDetailsManager() override;
507 
508   using GemDeviceDetailsManager::GetRequestDictForTesting;
509   using GemDeviceDetailsManager::GetUploadStatusForTesting;
510   using GemDeviceDetailsManager::SetRequestTimeoutForTesting;
511 
512  private:
513   GemDeviceDetailsManager* original_manager_ = nullptr;
514 };
515 
516 ///////////////////////////////////////////////////////////////////////////////
517 
518 class FakeEventLoggingApiManager : public EventLoggingApiManager {
519  public:
520   typedef EventLogsUploadManager::EventLogEntry EventLogEntry;
521 
522   EVT_HANDLE EvtQuery(EVT_HANDLE session,
523                       LPCWSTR path,
524                       LPCWSTR query,
525                       DWORD flags) override;
526 
527   EVT_HANDLE EvtOpenPublisherMetadata(EVT_HANDLE session,
528                                       LPCWSTR publisher_id,
529                                       LPCWSTR log_file_path,
530                                       LCID locale,
531                                       DWORD flags) override;
532 
533   EVT_HANDLE EvtCreateRenderContext(DWORD value_paths_count,
534                                     LPCWSTR* value_paths,
535                                     DWORD flags) override;
536 
537   BOOL EvtNext(EVT_HANDLE result_set,
538                DWORD events_size,
539                PEVT_HANDLE events,
540                DWORD timeout,
541                DWORD flags,
542                PDWORD num_returned) override;
543 
544   BOOL EvtGetQueryInfo(EVT_HANDLE query,
545                        EVT_QUERY_PROPERTY_ID property_id,
546                        DWORD value_buffer_size,
547                        PEVT_VARIANT value_buffer,
548                        PDWORD value_buffer_used) override;
549 
550   BOOL EvtRender(EVT_HANDLE context,
551                  EVT_HANDLE evt_handle,
552                  DWORD flags,
553                  DWORD buffer_size,
554                  PVOID buffer,
555                  PDWORD buffer_used,
556                  PDWORD property_count) override;
557 
558   BOOL EvtFormatMessage(EVT_HANDLE publisher_metadata,
559                         EVT_HANDLE event,
560                         DWORD message_id,
561                         DWORD value_count,
562                         PEVT_VARIANT values,
563                         DWORD flags,
564                         DWORD buffer_size,
565                         LPWSTR buffer,
566                         PDWORD buffer_used) override;
567 
568   BOOL EvtClose(EVT_HANDLE handle) override;
569 
570   DWORD GetLastError() override;
571 
572   explicit FakeEventLoggingApiManager(const std::vector<EventLogEntry>& logs);
573 
574   ~FakeEventLoggingApiManager() override;
575 
576  private:
577   EventLoggingApiManager* original_manager_ = nullptr;
578 
579   const std::vector<EventLogEntry>& logs_;
580   EVT_HANDLE query_handle_, publisher_metadata_, render_context_;
581   DWORD last_error_;
582   size_t next_event_idx_;
583   std::vector<EVT_HANDLE> event_handles_;
584   std::unordered_map<EVT_HANDLE, size_t> handle_to_index_map_;
585 };
586 
587 class FakeEventLogsUploadManager : public EventLogsUploadManager {
588  public:
589   typedef EventLogsUploadManager::EventLogEntry EventLogEntry;
590 
591   // Construct with the logs that should be present in the fake event log.
592   explicit FakeEventLogsUploadManager(const std::vector<EventLogEntry>& logs);
593   ~FakeEventLogsUploadManager() override;
594 
595   // Get the last upload status of the call to UploadEventViewerLogs.
596   HRESULT GetUploadStatus();
597 
598   // Get the number of successfully uploaded event logs.
599   uint64_t GetNumLogsUploaded();
600 
601  private:
602   EventLogsUploadManager* original_manager_ = nullptr;
603   FakeEventLoggingApiManager api_manager_;
604 };
605 
606 ///////////////////////////////////////////////////////////////////////////////
607 
608 class FakeUserPoliciesManager : public UserPoliciesManager {
609  public:
610   FakeUserPoliciesManager();
611   explicit FakeUserPoliciesManager(bool cloud_policies_enabled);
612   ~FakeUserPoliciesManager() override;
613 
614   HRESULT FetchAndStoreCloudUserPolicies(
615       const base::string16& sid,
616       const std::string& access_token) override;
617 
618   // Specify the policy to use for a user.
619   void SetUserPolicies(const base::string16& sid, const UserPolicies& policies);
620 
621   bool GetUserPolicies(const base::string16& sid,
622                        UserPolicies* policies) const override;
623 
624   // Specify whether user policy is valid for a user.
625   void SetUserPolicyStaleOrMissing(const base::string16& sid, bool status);
626 
627   bool IsUserPolicyStaleOrMissing(const base::string16& sid) const override;
628 
629   // Returns the number of times FetchAndStoreCloudUserPolicies method was
630   // called.
631   int GetNumTimesFetchAndStoreCalled() const;
632 
633  private:
634   UserPoliciesManager* original_manager_ = nullptr;
635   std::map<base::string16, UserPolicies> user_policies_;
636   int num_times_fetch_called_ = 0;
637   std::map<base::string16, bool> user_policies_stale_;
638 };
639 
640 ///////////////////////////////////////////////////////////////////////////////
641 
642 class FakeDevicePoliciesManager : public DevicePoliciesManager {
643  public:
644   explicit FakeDevicePoliciesManager(bool cloud_policies_enabled);
645   ~FakeDevicePoliciesManager() override;
646 
647   // Specify the policy to use for the device.
648   void SetDevicePolicies(const DevicePolicies& policies);
649 
650   void GetDevicePolicies(DevicePolicies* device_policies) override;
651 
652  private:
653   DevicePoliciesManager* original_manager_ = nullptr;
654   DevicePolicies device_policies_;
655 };
656 
657 ///////////////////////////////////////////////////////////////////////////////
658 
659 class FakeGCPWFiles : public GCPWFiles {
660  public:
661   FakeGCPWFiles();
662   ~FakeGCPWFiles() override;
663 
664   std::vector<base::FilePath::StringType> GetEffectiveInstallFiles() override;
665 
666  private:
667   GCPWFiles* original_files = nullptr;
668 };
669 
670 ///////////////////////////////////////////////////////////////////////////////
671 
672 class FakeOSServiceManager : public extension::OSServiceManager {
673  public:
674   FakeOSServiceManager();
675   ~FakeOSServiceManager() override;
676 
677   DWORD GetServiceStatus(SERVICE_STATUS* service_status) override;
678 
679   DWORD InstallService(const base::FilePath& service_binary_path,
680                        extension::ScopedScHandle* sc_handle) override;
681 
682   DWORD StartServiceCtrlDispatcher(
683       LPSERVICE_MAIN_FUNCTION service_main) override;
684 
685   DWORD RegisterCtrlHandler(
686       LPHANDLER_FUNCTION handler_proc,
687       SERVICE_STATUS_HANDLE* service_status_handle) override;
688 
689   DWORD SetServiceStatus(SERVICE_STATUS_HANDLE service_status_handle,
690                          SERVICE_STATUS service) override;
691 
SendControlRequestForTesting(DWORD control_request)692   void SendControlRequestForTesting(DWORD control_request) {
693     std::unique_lock<std::mutex> lock(m);
694     queue.push_back(control_request);
695     cv.notify_one();
696   }
697 
698   DWORD DeleteService() override;
699 
700   DWORD ChangeServiceConfig(DWORD dwServiceType,
701                             DWORD dwStartType,
702                             DWORD dwErrorControl) override;
703 
704  private:
GetControlRequestForTesting()705   DWORD GetControlRequestForTesting() {
706     std::unique_lock<std::mutex> lock(m);
707     cv.wait(lock, [&]() { return !queue.empty(); });
708     DWORD result = queue.front();
709     queue.pop_front();
710     return result;
711   }
712 
713   struct ServiceInfo {
714     LPHANDLER_FUNCTION control_handler_cb_;
715     SERVICE_STATUS service_status_;
716   };
717 
718   // Primitives that are used to synchronize with the thread running service
719   // main and the thread testing the code.
720   std::list<DWORD> queue;
721   std::mutex m;
722   std::condition_variable cv;
723 
724   // Original instance of OSServiceManager.
725   extension::OSServiceManager* os_service_manager_ = nullptr;
726   std::map<base::string16, ServiceInfo> service_lookup_from_name_;
727 };
728 
729 ///////////////////////////////////////////////////////////////////////////////
730 
731 class FakeTaskManager : public extension::TaskManager {
732  public:
733   FakeTaskManager();
734   ~FakeTaskManager() override;
735 
NumOfTimesExecuted()736   int NumOfTimesExecuted() { return num_of_times_executed_; }
737 
738  private:
739   void RunTasksInternal() override;
740 
741   // Original instance of TaskManager.
742   extension::TaskManager* task_manager_ = nullptr;
743 
744   int num_of_times_executed_;
745   base::Time start_time_;
746 };
747 
748 ///////////////////////////////////////////////////////////////////////////////
749 
750 class FakeTokenGenerator : public TokenGenerator {
751  public:
752   FakeTokenGenerator();
753   ~FakeTokenGenerator() override;
754 
755   std::string GenerateToken() override;
756 
757   void SetTokensForTesting(const std::vector<std::string>& test_tokens);
758 
759  private:
760   TokenGenerator* token_generator_ = nullptr;
761   std::vector<std::string> test_tokens_;
762 };
763 
764 ///////////////////////////////////////////////////////////////////////////////
765 
766 }  // namespace credential_provider
767 
768 #endif  // CHROME_CREDENTIAL_PROVIDER_TEST_GCP_FAKES_H_
769