summaryrefslogtreecommitdiff
path: root/chromium/components/policy/core/common/cloud/cloud_policy_client.h
blob: e29d81120a2dec14e046c415403b96defa54b287 (plain)
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
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef COMPONENTS_POLICY_CORE_COMMON_CLOUD_CLOUD_POLICY_CLIENT_H_
#define COMPONENTS_POLICY_CORE_COMMON_CLOUD_CLOUD_POLICY_CLIENT_H_

#include <stdint.h>

#include <map>
#include <memory>
#include <set>
#include <string>
#include <utility>
#include <vector>

#include "base/callback.h"
#include "base/memory/raw_ptr.h"
#include "base/observer_list.h"
#include "base/sequence_checker.h"
#include "base/time/time.h"
#include "base/values.h"
#include "components/policy/core/common/cloud/cloud_policy_constants.h"
#include "components/policy/core/common/cloud/cloud_policy_validator.h"
#include "components/policy/core/common/cloud/device_management_service.h"
#include "components/policy/core/common/cloud/dm_auth.h"
#include "components/policy/core/common/remote_commands/remote_command_job.h"
#include "components/policy/policy_export.h"
#include "components/policy/proto/device_management_backend.pb.h"
#include "third_party/abseil-cpp/absl/types/optional.h"

namespace content {
class BrowserContext;
}

namespace network {
class SharedURLLoaderFactory;
}

namespace policy {

class ClientDataDelegate;
class DMServerJobConfiguration;
class RegistrationJobConfiguration;
class SigningService;

// Implements the core logic required to talk to the device management service.
// Also keeps track of the current state of the association with the service,
// such as whether there is a valid registration (DMToken is present in that
// case) and whether and what errors occurred in the latest request.
//
// Note that CloudPolicyClient doesn't do any validation of policy responses
// such as signature and time stamp checks. These happen once the policy gets
// installed in the cloud policy cache.
class POLICY_EXPORT CloudPolicyClient {
 public:
  // Maps a (policy type, settings entity ID) pair to its corresponding
  // PolicyFetchResponse.
  using ResponseMap = std::map<std::pair<std::string, std::string>,
                               enterprise_management::PolicyFetchResponse>;

  // A callback which receives boolean status of an operation.  If the operation
  // succeeded, |status| is true.
  using StatusCallback = base::OnceCallback<void(bool status)>;

  // A callback which receives fetched remote commands.
  using RemoteCommandCallback = base::OnceCallback<void(
      DeviceManagementStatus,
      const std::vector<enterprise_management::SignedData>&)>;

  // A callback for fetching device robot OAuth2 authorization tokens.
  // Only occurs during enrollment, after the device is registered.
  using RobotAuthCodeCallback =
      base::OnceCallback<void(DeviceManagementStatus, const std::string&)>;

  // A callback which fetches device dm_token based on user affiliation.
  // Should be called once per registration.
  using DeviceDMTokenCallback = base::RepeatingCallback<std::string(
      const std::vector<std::string>& user_affiliation_ids)>;

  // Callback that processes response value received from the server,
  // or nullopt, if there was a failure.
  using ResponseCallback =
      base::OnceCallback<void(absl::optional<base::Value::Dict>)>;

  using ClientCertProvisioningStartCsrCallback = base::OnceCallback<void(
      DeviceManagementStatus,
      absl::optional<
          enterprise_management::ClientCertificateProvisioningResponse::Error>,
      absl::optional<int64_t> try_later,
      const std::string& invalidation_topic,
      const std::string& va_challenge,
      enterprise_management::HashingAlgorithm hash_algorithm,
      const std::string& data_to_sign)>;

  using ClientCertProvisioningFinishCsrCallback = base::OnceCallback<void(
      DeviceManagementStatus,
      absl::optional<
          enterprise_management::ClientCertificateProvisioningResponse::Error>,
      absl::optional<int64_t> try_later)>;

  using ClientCertProvisioningDownloadCertCallback = base::OnceCallback<void(
      DeviceManagementStatus,
      absl::optional<
          enterprise_management::ClientCertificateProvisioningResponse::Error>,
      absl::optional<int64_t> try_later,
      const std::string& pem_encoded_certificate)>;

  // Observer interface for state and policy changes.
  class POLICY_EXPORT Observer {
   public:
    virtual ~Observer();

    // Called when a policy fetch completes successfully. If a policy fetch
    // triggers an error, OnClientError() will fire.
    virtual void OnPolicyFetched(CloudPolicyClient* client) = 0;

    // Called upon registration state changes. This callback is invoked for
    // successful completion of registration and unregistration requests.
    virtual void OnRegistrationStateChanged(CloudPolicyClient* client) = 0;

    // Indicates there's been an error in a previously-issued request.
    virtual void OnClientError(CloudPolicyClient* client) = 0;

    // Called when the Service Account Identity is set on a policy data object
    // after a policy fetch. |service_account_email()| will return the new
    // account's email.
    virtual void OnServiceAccountSet(CloudPolicyClient* client,
                                     const std::string& account_email) {}
  };

  struct POLICY_EXPORT RegistrationParameters {
   public:
    RegistrationParameters(
        enterprise_management::DeviceRegisterRequest::Type registration_type,
        enterprise_management::DeviceRegisterRequest::Flavor flavor);
    ~RegistrationParameters();

    // A setter for |psm_execution_result| field.
    void SetPsmExecutionResult(
        absl::optional<
            enterprise_management::DeviceRegisterRequest::PsmExecutionResult>
            new_psm_result);

    // A setter for |psm_determination_timestamp| field.
    void SetPsmDeterminationTimestamp(
        absl::optional<int64_t> new_psm_timestamp);

    void SetLicenseType(
        enterprise_management::LicenseType_LicenseTypeEnum license_type);

    enterprise_management::DeviceRegisterRequest::Type registration_type;
    enterprise_management::DeviceRegisterRequest::Flavor flavor;

    absl::optional<enterprise_management::LicenseType_LicenseTypeEnum>
        license_type_;

    // Lifetime of registration. Used for easier clean up of ephemeral session
    // registrations.
    enterprise_management::DeviceRegisterRequest::Lifetime lifetime =
        enterprise_management::DeviceRegisterRequest::LIFETIME_INDEFINITE;

    // Device requisition.
    std::string requisition;

    // Server-backed state keys (used for forced enrollment check).
    std::string current_state_key;

    // The following field is relevant only to Chrome OS.
    // PSM protocol execution result. Its value will exist if the device
    // undergoes enrollment and a PSM server-backed state determination was
    // performed before (on Chrome OS, as encoded in the
    // `prefs::kEnrollmentPsmResult` pref).
    absl::optional<
        enterprise_management::DeviceRegisterRequest::PsmExecutionResult>
        psm_execution_result;

    // The following field is relevant only to Chrome OS.
    // PSM protocol determination timestamp. Its value will exist if the device
    // undergoes enrollment and PSM got executed successfully (on ChromeOS, as
    // encoded in `prefs::kEnrollmentPsmDeterminationTime` pref).
    absl::optional<int64_t> psm_determination_timestamp;
  };

  // If non-empty, |machine_id|, |machine_model|, |brand_code|,
  // |attested_device_id|, |ethernet_mac_address|, |dock_mac_address| and
  // |manufacture_date| are passed to the server verbatim. As these reveal
  // machine identity, they must only be used where this is appropriate (i.e.
  // device policy, but not user policy). |service| is weak pointer and it's
  // the caller's responsibility to keep it valid for the lifetime of
  // CloudPolicyClient. |device_dm_token_callback| is used to retrieve device
  // DMToken for affiliated users. Could be null if it's not possible to use
  // device DMToken for user policy fetches.
  CloudPolicyClient(
      const std::string& machine_id,
      const std::string& machine_model,
      const std::string& brand_code,
      const std::string& attested_device_id,
      const std::string& ethernet_mac_address,
      const std::string& dock_mac_address,
      const std::string& manufacture_date,
      DeviceManagementService* service,
      scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory,
      DeviceDMTokenCallback device_dm_token_callback);
  // A simpler constructor for those that do not need any of the identification
  // strings of the full constructor.
  CloudPolicyClient(
      DeviceManagementService* service,
      scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory,
      DeviceDMTokenCallback device_dm_token_callback);
  CloudPolicyClient(const CloudPolicyClient&) = delete;
  CloudPolicyClient& operator=(const CloudPolicyClient&) = delete;

  virtual ~CloudPolicyClient();

  // Sets the DMToken, thereby establishing a registration with the server. A
  // policy fetch is not automatically issued but can be requested by calling
  // FetchPolicy().
  // |user_affiliation_ids| are used to get device DMToken if relevant.
  virtual void SetupRegistration(
      const std::string& dm_token,
      const std::string& client_id,
      const std::vector<std::string>& user_affiliation_ids);

  // Attempts to register with the device management service. Results in a
  // registration change or error notification.
  virtual void Register(const RegistrationParameters& parameters,
                        const std::string& client_id,
                        const std::string& oauth_token);

  // Attempts to register with the device management service using a
  // registration certificate. Results in a registration change or
  // error notification. The |signing_service| is used to sign the request and
  // is expected to be available until caller receives
  // |OnRegistrationStateChanged| or |OnClientError|.
  // TODO(crbug.com/1236148): Remove SigningService from CloudPolicyClient and
  // make callees sign their data themselves.
  virtual void RegisterWithCertificate(const RegistrationParameters& parameters,
                                       const std::string& client_id,
                                       const std::string& pem_certificate_chain,
                                       const std::string& sub_organization,
                                       SigningService* signing_service);

  // Attempts to enroll with the device management service using an enrollment
  // token. Results in a registration change or error notification.
  // This method is used to register browser (e.g. for machine-level policies).
  // Device registration with enrollment token should be performed using
  // RegisterWithCertificate method.
  virtual void RegisterWithToken(
      const std::string& token,
      const std::string& client_id,
      const ClientDataDelegate& client_data_delegate);

  // Sets information about a policy invalidation. Subsequent fetch operations
  // will use the given info, and callers can use fetched_invalidation_version
  // to determine which version of policy was fetched.
  void SetInvalidationInfo(int64_t version, const std::string& payload);

  // Sets OAuth token to be used as an additional authentication in requests to
  // DMServer. It is used for child user. This class does not track validity of
  // the |oauth_token|. It should be provided with a fresh token when the
  // previous token expires. If OAuth token is set for the client, it will be
  // automatically included in the folllowing requests:
  //  * policy fetch
  //  * status report upload
  virtual void SetOAuthTokenAsAdditionalAuth(const std::string& oauth_token);

  // Requests a policy fetch. The client being registered is a prerequisite to
  // this operation and this call will CHECK if the client is not in registered
  // state. FetchPolicy() triggers a policy fetch from the cloud. A policy
  // change notification is reported to the observers and the new policy blob
  // can be retrieved once the policy fetch operation completes. In case of
  // multiple requests to fetch policy, new requests will cancel any pending
  // requests and the latest request will eventually trigger notifications.
  virtual void FetchPolicy();

  // Upload a policy validation report to the server. Like FetchPolicy, this
  // method requires that the client is in a registered state. This method
  // should only be called if the policy was rejected (e.g. validation or
  // serialization error).
  virtual void UploadPolicyValidationReport(
      CloudPolicyValidatorBase::Status status,
      const std::vector<ValueValidationIssue>& value_validation_issues,
      const std::string& policy_type,
      const std::string& policy_token);

  // Requests OAuth2 auth codes for the device robot account. The client being
  // registered is a prerequisite to this operation and this call will CHECK if
  // the client is not in registered state. |oauth_scopes| is the scopes for
  // which the robot auth codes will be valid, and |device_type| should match
  // the type of the robot account associated with this request.
  // The |callback| will be called when the operation completes.
  virtual void FetchRobotAuthCodes(
      DMAuth auth,
      enterprise_management::DeviceServiceApiAccessRequest::DeviceType
          device_type,
      const std::set<std::string>& oauth_scopes,
      RobotAuthCodeCallback callback);

  // Sends an unregistration request to the server.
  virtual void Unregister();

  // Upload a machine certificate to the server.  Like FetchPolicy, this method
  // requires that the client is in a registered state.  |certificate_data| must
  // hold the X.509 certificate data to be sent to the server.  The |callback|
  // will be called when the operation completes.
  virtual void UploadEnterpriseMachineCertificate(
      const std::string& certificate_data,
      StatusCallback callback);

  // Upload an enrollment certificate to the server.  Like FetchPolicy, this
  // method requires that the client is in a registered state.
  // |certificate_data| must hold the X.509 certificate data to be sent to the
  // server.  The |callback| will be called when the operation completes.
  virtual void UploadEnterpriseEnrollmentCertificate(
      const std::string& certificate_data,
      StatusCallback callback);

  // Upload an enrollment identifier to the server. Like FetchPolicy, this
  // method requires that the client is in a registered state.
  // |enrollment_id| must hold an enrollment identifier. The |callback| will be
  // called when the operation completes.
  virtual void UploadEnterpriseEnrollmentId(const std::string& enrollment_id,
                                            StatusCallback callback);

  // Uploads status to the server. The client must be in a registered state.
  // Only non-null statuses will be included in the upload status request. The
  // |callback| will be called when the operation completes.
  virtual void UploadDeviceStatus(
      const enterprise_management::DeviceStatusReportRequest* device_status,
      const enterprise_management::SessionStatusReportRequest* session_status,
      const enterprise_management::ChildStatusReportRequest* child_status,
      StatusCallback callback);

  // Uploads Chrome Desktop report to the server. As above, the client must be
  // in a registered state. |chrome_desktop_report| will be included in the
  // upload request. The |callback| will be called when the operation completes.
  virtual void UploadChromeDesktopReport(
      std::unique_ptr<enterprise_management::ChromeDesktopReportRequest>
          chrome_desktop_report,
      StatusCallback callback);

  // Uploads Chrome OS User report to the server. The user's DM token must be
  // set. |chrome_os_user_report| will be included in the upload request. The
  // |callback| will be called when the operation completes.
  virtual void UploadChromeOsUserReport(
      std::unique_ptr<enterprise_management::ChromeOsUserReportRequest>
          chrome_os_user_report,
      StatusCallback callback);

  // Uploads Chrome profile report to the server. The user's DM token must be
  // set. |chrome_profile_report| will be included in the upload request. The
  // |callback| will be called when the operation completes.
  virtual void UploadChromeProfileReport(
      std::unique_ptr<enterprise_management::ChromeProfileReportRequest>
          chrome_profile_report,
      StatusCallback callback);

  // Uploads a report containing enterprise connectors real-time security
  // events for |context|. As above, the client must be in a registered state.
  // If |include_device_info| is true, information specific to the device such
  // as the device name, user, id and OS will be included in the report. The
  // |callback| will be called when the operation completes.
  virtual void UploadSecurityEventReport(content::BrowserContext* context,
                                         bool include_device_info,
                                         base::Value::Dict report,
                                         StatusCallback callback);

  // Uploads a report containing |merging_payload| (merged into the default
  // payload of the job). The client must be in a registered state. The
  // |callback| will be called when the operation completes.
  virtual void UploadEncryptedReport(base::Value::Dict merging_payload,
                                     absl::optional<base::Value::Dict> context,
                                     ResponseCallback callback);

  // Uploads a report on the status of app push-installs. The client must be in
  // a registered state. The |callback| will be called when the operation
  // completes.
  // Only one outstanding app push-install report upload is allowed.
  // In case the new push-installs report upload is started, the previous one
  // will be canceled.
  virtual void UploadAppInstallReport(base::Value::Dict report,
                                      StatusCallback callback);

  // Cancels the pending app push-install status report upload, if exists.
  virtual void CancelAppInstallReportUpload();

  // Uploads a report on the status of extension installs. The client must be in
  // a registered state. The |callback| will be called when the operation
  // completes.
  // Only one outstanding extension install report upload is allowed.
  // In case the new installs report upload is started, the previous one
  // will be canceled.
  virtual void UploadExtensionInstallReport(base::Value::Dict report,
                                            StatusCallback callback);

  // Cancels the pending extension install status report upload, if exists.
  virtual void CancelExtensionInstallReportUpload();

  // Attempts to fetch remote commands, with |last_command_id| being the ID of
  // the last command that finished execution and |command_results| being
  // results for previous commands which have not been reported yet. The
  // |callback| will be called when the operation completes.
  // Note that sending |last_command_id| will acknowledge this command and any
  // previous commands. A nullptr indicates that no commands have finished
  // execution.
  virtual void FetchRemoteCommands(
      std::unique_ptr<RemoteCommandJob::UniqueIDType> last_command_id,
      const std::vector<enterprise_management::RemoteCommandResult>&
          command_results,
      RemoteCommandCallback callback);

  // Sends a device attribute update permission request to the server, uses
  // |auth| to identify user who requests a permission to name a device, calls
  // a |callback| from the enrollment screen to indicate whether the device
  // naming prompt should be shown.
  void GetDeviceAttributeUpdatePermission(DMAuth auth, StatusCallback callback);

  // Sends a device naming information (Asset Id and Location) to the
  // device management server, uses |auth| to identify user who names a device,
  // the |callback| will be called when the operation completes.
  void UpdateDeviceAttributes(DMAuth auth,
                              const std::string& asset_id,
                              const std::string& location,
                              StatusCallback callback);

  // Sends a GCM id update request to the DM server. The server will
  // associate the DM token in authorization header with |gcm_id|, and
  // |callback| will be called when the operation completes.
  virtual void UpdateGcmId(const std::string& gcm_id, StatusCallback callback);

  // Sends a request with EUICCs on device to the DM server.
  virtual void UploadEuiccInfo(
      std::unique_ptr<enterprise_management::UploadEuiccInfoRequest> request,
      StatusCallback callback);

  // Sends certificate provisioning start csr request. It is Step 1 in the
  // certificate provisioning flow. |cert_scope| defines if it is a user- or
  // device-level request, |cert_profile_id| defines for which profile from
  // policies the request applies, |public_key| is used to build the CSR.
  // |callback| will be called when the operation completes. It is expected to
  // receive the CSR and VA challenge.
  virtual void ClientCertProvisioningStartCsr(
      const std::string& cert_scope,
      const std::string& cert_profile_id,
      const std::string& cert_profile_version,
      const std::string& public_key,
      ClientCertProvisioningStartCsrCallback callback);

  // Sends certificate provisioning finish csr request. It is Step 2 in the
  // certificate provisioning flow. |cert_scope| defines if it is a user- or
  // device-level request, |cert_profile_id| and |public_key| define the
  // provisioning flow that should be continued. |va_challenge_response| is a
  // challenge response to the challenge from the previous step. |signature| is
  // cryptographic signature of the CSR from the previous step, the algorithm
  // for it is defined in a corresponding certificate profile. |callback| will
  // be called when the operation completes. It is expected to receive a
  // confirmation that the request is accepted.
  virtual void ClientCertProvisioningFinishCsr(
      const std::string& cert_scope,
      const std::string& cert_profile_id,
      const std::string& cert_profile_version,
      const std::string& public_key,
      const std::string& va_challenge_response,
      const std::string& signature,
      ClientCertProvisioningFinishCsrCallback callback);

  // Sends certificate provisioning download certificate request. It is Step 3
  // (final) in the certificate provisioning flow. |cert_scope|,
  // |cert_profile_id|, |public_key| are the same as for finish csr request.
  // |callback| will be called when the operation completes. It is expected to
  // receive a certificate that was issued according to the CSR that was
  // generated during previous steps.
  virtual void ClientCertProvisioningDownloadCert(
      const std::string& cert_scope,
      const std::string& cert_profile_id,
      const std::string& cert_profile_version,
      const std::string& public_key,
      ClientCertProvisioningDownloadCertCallback callback);

  // Used the update the current service account email associated with this
  // policy client and notify observers.
  void UpdateServiceAccount(const std::string& account_email);

  // Adds an observer to be called back upon policy and state changes.
  void AddObserver(Observer* observer);

  // Removes the specified observer.
  void RemoveObserver(Observer* observer);

  const std::string& machine_id() const {
    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
    return machine_id_;
  }
  const std::string& machine_model() const {
    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
    return machine_model_;
  }
  const std::string& brand_code() const {
    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
    return brand_code_;
  }
  const std::string& attested_device_id() const {
    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
    return attested_device_id_;
  }
  const std::string& ethernet_mac_address() const {
    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
    return ethernet_mac_address_;
  }
  const std::string& dock_mac_address() const {
    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
    return dock_mac_address_;
  }
  const std::string& manufacture_date() const {
    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
    return manufacture_date_;
  }

  void set_last_policy_timestamp(const base::Time& timestamp) {
    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
    last_policy_timestamp_ = timestamp;
  }

  const base::Time& last_policy_timestamp() {
    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
    return last_policy_timestamp_;
  }

  void set_public_key_version(int public_key_version) {
    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
    public_key_version_ = public_key_version;
    public_key_version_valid_ = true;
  }

  void clear_public_key_version() {
    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
    public_key_version_valid_ = false;
  }

  // FetchPolicy() calls will request this policy type.
  // If |settings_entity_id| is empty then it won't be set in the
  // PolicyFetchRequest.
  void AddPolicyTypeToFetch(const std::string& policy_type,
                            const std::string& settings_entity_id);

  // FetchPolicy() calls won't request the given policy type and optional
  // |settings_entity_id| anymore.
  void RemovePolicyTypeToFetch(const std::string& policy_type,
                               const std::string& settings_entity_id);

  // Configures a set of device state keys to transfer to the server in the next
  // policy fetch. If the fetch is successful, the keys will be cleared so they
  // are only uploaded once.
  void SetStateKeysToUpload(const std::vector<std::string>& keys);

  // Whether the client is registered with the device management service.
  bool is_registered() const {
    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
    return !dm_token_.empty();
  }

  // Whether the client requires reregistration with the device management
  // service.
  bool requires_reregistration() const {
    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
    return !reregistration_dm_token_.empty();
  }

  DeviceManagementService* service() {
    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
    return service_;
  }
  const std::string& dm_token() const {
    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
    return dm_token_;
  }
  const std::string& client_id() const {
    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
    return client_id_;
  }
  const base::DictionaryValue* configuration_seed() const {
    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
    return configuration_seed_.get();
  }

  // The device mode as received in the registration request.
  DeviceMode device_mode() const {
    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
    return device_mode_;
  }

  // The policy responses as obtained by the last request to the cloud. These
  // policies haven't gone through verification, so their contents cannot be
  // trusted. Use CloudPolicyStore::policy() and CloudPolicyStore::policy_map()
  // instead for making policy decisions.
  const ResponseMap& responses() const {
    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
    return responses_;
  }

  // Returns the policy response for the (|policy_type|, |settings_entity_id|)
  // pair if found in |responses()|. Otherwise returns nullptr.
  const enterprise_management::PolicyFetchResponse* GetPolicyFor(
      const std::string& policy_type,
      const std::string& settings_entity_id) const;

  DeviceManagementStatus status() const {
    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
    return status_;
  }

  // Returns the invalidation version that was used for the last FetchPolicy.
  // Observers can call this method from their OnPolicyFetched method to
  // determine which at which invalidation version the policy was fetched.
  int64_t fetched_invalidation_version() const {
    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
    return fetched_invalidation_version_;
  }

  scoped_refptr<network::SharedURLLoaderFactory> GetURLLoaderFactory();

  void add_connector_url_params(bool value) {
    add_connector_url_params_ = value;
  }

  // Returns the number of active requests.
  int GetActiveRequestCountForTest() const;

  void SetURLLoaderFactoryForTesting(
      scoped_refptr<network::SharedURLLoaderFactory> factory);

 protected:
  // A set of (policy type, settings entity ID) pairs to fetch.
  typedef std::set<std::pair<std::string, std::string>> PolicyTypeSet;

  // Upload a certificate to the server.  Like FetchPolicy, this method
  // requires that the client is in a registered state.  |certificate_data| must
  // hold the X.509 certificate data to be sent to the server.  The |callback|
  // will be called when the operation completes.
  void UploadCertificate(
      const std::string& certificate_data,
      enterprise_management::DeviceCertUploadRequest::CertificateType
          certificate_type,
      StatusCallback callback);

  // This is called when a RegisterWithCertiifcate request has been signed.
  void OnRegisterWithCertificateRequestSigned(
      bool success,
      enterprise_management::SignedData signed_data);

  // Callback for registration requests.
  void OnRegisterCompleted(
      DeviceManagementService::Job* job,
      DeviceManagementStatus status,
      int net_error,
      const enterprise_management::DeviceManagementResponse& response);

  // Callback for policy fetch requests.
  void OnPolicyFetchCompleted(
      DeviceManagementService::Job* job,
      DeviceManagementStatus status,
      int net_error,
      const enterprise_management::DeviceManagementResponse& response);

  // Callback for robot account api authorization requests.
  void OnFetchRobotAuthCodesCompleted(
      RobotAuthCodeCallback callback,
      DeviceManagementService::Job* job,
      DeviceManagementStatus status,
      int net_error,
      const enterprise_management::DeviceManagementResponse& response);

  // Callback for unregistration requests.
  void OnUnregisterCompleted(
      DeviceManagementService::Job* job,
      DeviceManagementStatus status,
      int net_error,
      const enterprise_management::DeviceManagementResponse& response);

  // Callback for certificate upload requests.
  void OnCertificateUploadCompleted(
      StatusCallback callback,
      DeviceManagementService::Job* job,
      DeviceManagementStatus status,
      int net_error,
      const enterprise_management::DeviceManagementResponse& response);

  // Callback for several types of status/report upload requests.
  void OnReportUploadCompleted(
      StatusCallback callback,
      DeviceManagementService::Job* job,
      DeviceManagementStatus status,
      int net_error,
      const enterprise_management::DeviceManagementResponse& response);

  // Callback for realtime report upload requests.
  void OnRealtimeReportUploadCompleted(
      StatusCallback callback,
      DeviceManagementService::Job* job,
      DeviceManagementStatus status,
      int net_error,
      absl::optional<base::Value::Dict> response);

  // Callback for encrypted report upload requests.
  void OnEncryptedReportUploadCompleted(
      ResponseCallback callback,
      DeviceManagementService::Job* job,
      DeviceManagementStatus status,
      int net_error,
      absl::optional<base::Value::Dict> response);

  // Callback for remote command fetch requests.
  void OnRemoteCommandsFetched(
      RemoteCommandCallback callback,
      DeviceManagementService::Job* job,
      DeviceManagementStatus status,
      int net_error,
      const enterprise_management::DeviceManagementResponse& response);

  // Callback for device attribute update permission requests.
  void OnDeviceAttributeUpdatePermissionCompleted(
      StatusCallback callback,
      DeviceManagementService::Job* job,
      DeviceManagementStatus status,
      int net_error,
      const enterprise_management::DeviceManagementResponse& response);

  // Callback for device attribute update requests.
  void OnDeviceAttributeUpdated(
      StatusCallback callback,
      DeviceManagementService::Job* job,
      DeviceManagementStatus status,
      int net_error,
      const enterprise_management::DeviceManagementResponse& response);

  // Callback for gcm id update requests.
  void OnGcmIdUpdated(
      StatusCallback callback,
      DeviceManagementService::Job* job,
      DeviceManagementStatus status,
      int net_error,
      const enterprise_management::DeviceManagementResponse& response);

  // Callback for EUICC info upload requests.
  void OnEuiccInfoUploaded(
      StatusCallback callback,
      DeviceManagementService::Job* job,
      DeviceManagementStatus status,
      int net_error,
      const enterprise_management::DeviceManagementResponse& response);

  // Callback for certificate provisioning start csr requests.
  void OnClientCertProvisioningStartCsrResponse(
      ClientCertProvisioningStartCsrCallback callback,
      policy::DeviceManagementService::Job* job,
      policy::DeviceManagementStatus status,
      int net_error,
      const enterprise_management::DeviceManagementResponse& response);

  // Callback for certificate provisioning finish csr requests.
  void OnClientCertProvisioningFinishCsrResponse(
      ClientCertProvisioningFinishCsrCallback callback,
      policy::DeviceManagementService::Job* job,
      policy::DeviceManagementStatus status,
      int net_error,
      const enterprise_management::DeviceManagementResponse& response);

  // Callback for certificate provisioning download cert requests.
  void OnClientCertProvisioningDownloadCertResponse(
      ClientCertProvisioningDownloadCertCallback callback,
      policy::DeviceManagementService::Job* job,
      policy::DeviceManagementStatus status,
      int net_error,
      const enterprise_management::DeviceManagementResponse& response);

  // Helper to remove a job from request_jobs_.
  void RemoveJob(DeviceManagementService::Job* job);

  // Observer notification helpers.
  void NotifyPolicyFetched();
  void NotifyRegistrationStateChanged();
  void NotifyClientError();
  void NotifyServiceAccountSet(const std::string& account_email);

  // Assert non-concurrent usage in debug builds.
  SEQUENCE_CHECKER(sequence_checker_);

  // Data necessary for constructing policy requests.
  const std::string machine_id_;
  const std::string machine_model_;
  const std::string brand_code_;
  const std::string attested_device_id_;
  const std::string ethernet_mac_address_;
  const std::string dock_mac_address_;
  const std::string manufacture_date_;
  PolicyTypeSet types_to_fetch_;
  std::vector<std::string> state_keys_to_upload_;

  // OAuth token that if set is used as an additional form of authentication
  // (next to |dm_token_|) in policy fetch requests.
  std::string oauth_token_;

  std::string dm_token_;
  std::unique_ptr<base::DictionaryValue> configuration_seed_;
  DeviceMode device_mode_ = DEVICE_MODE_NOT_SET;
  std::string client_id_;
  base::Time last_policy_timestamp_;
  int public_key_version_ = -1;
  bool public_key_version_valid_ = false;
  // Device DMToken for affiliated user policy requests.
  // Retrieved from |device_dm_token_callback_| on registration.
  std::string device_dm_token_;

  // Information for the latest policy invalidation received.
  int64_t invalidation_version_ = 0;
  std::string invalidation_payload_;

  // The invalidation version used for the most recent fetch operation.
  int64_t fetched_invalidation_version_ = 0;

  // Used for issuing requests to the cloud.
  raw_ptr<DeviceManagementService> service_ = nullptr;

  // Only one outstanding policy fetch or device/user registration request is
  // allowed. Using a separate job to track those requests. If multiple
  // requests have been started, only the last one will be kept.
  std::unique_ptr<DeviceManagementService::Job> unique_request_job_;

  // All of the outstanding non-policy-fetch request jobs. These jobs are
  // silently cancelled if Unregister() is called.
  std::vector<std::unique_ptr<DeviceManagementService::Job>> request_jobs_;

  // Only one outstanding app push-install report upload is allowed, and it must
  // be accessible so that it can be canceled.
  raw_ptr<DeviceManagementService::Job> app_install_report_request_job_ =
      nullptr;

  // Only one outstanding extension install report upload is allowed, and it
  // must be accessible so that it can be canceled.
  raw_ptr<DeviceManagementService::Job> extension_install_report_request_job_ =
      nullptr;

  // The policy responses returned by the last policy fetch operation.
  ResponseMap responses_;
  DeviceManagementStatus status_ = DM_STATUS_SUCCESS;

  DeviceDMTokenCallback device_dm_token_callback_;

  base::ObserverList<Observer, true>::Unchecked observers_;

  scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory_;

 private:
  // Creates a new real-time reporting job and appends it to |request_jobs_|.
  // The job will send its report to the |server_url| endpoint.  If
  // |include_device_info| is true, information specific to the device such as
  // the device name, user, id and OS will be included in the report. If
  // |add_connector_url_params| is true then URL paramaters specific to
  // enterprise connectors are added to the request uploading the report.
  // |callback| is invoked once the report is uploaded.
  DeviceManagementService::Job* CreateNewRealtimeReportingJob(
      base::Value::Dict report,
      const std::string& server_url,
      bool include_device_info,
      bool add_connector_url_params,
      StatusCallback callback);

  void SetClientId(const std::string& client_id);
  // Fills in the common fields of a DeviceRegisterRequest for |Register| and
  // |RegisterWithCertificate|.
  void CreateDeviceRegisterRequest(
      const RegistrationParameters& params,
      const std::string& client_id,
      enterprise_management::DeviceRegisterRequest* request);

  // Prepare the certificate upload request field for uploading a certificate.
  void PrepareCertUploadRequest(
      DMServerJobConfiguration* config,
      const std::string& certificate_data,
      enterprise_management::DeviceCertUploadRequest::CertificateType
          certificate_type);

  // Creates a job config to upload a certificate.
  std::unique_ptr<DMServerJobConfiguration> CreateCertUploadJobConfiguration(
      CloudPolicyClient::StatusCallback callback);

  // Executes a job to upload a certificate. Onwership of the job is
  // retained by this method.
  void ExecuteCertUploadJob(std::unique_ptr<DMServerJobConfiguration> config);

  // Sets `unique_request_job_` with a new job created with `config`.
  void CreateUniqueRequestJob(
      std::unique_ptr<RegistrationJobConfiguration> config);

  // Used to store a copy of the previously used |dm_token_|. This is used
  // during re-registration, which gets triggered by a failed policy fetch with
  // error |DM_STATUS_SERVICE_DEVICE_NOT_FOUND|.
  std::string reregistration_dm_token_;

  // Whether extra enterprise connectors URL parameters should be included
  // in real-time reports.  Only reports uploaded using UploadRealtimeReport()
  // are affected.
  bool add_connector_url_params_ = false;

  // Used to create tasks which run delayed on the UI thread.
  base::WeakPtrFactory<CloudPolicyClient> weak_ptr_factory_{this};
};

}  // namespace policy

#endif  // COMPONENTS_POLICY_CORE_COMMON_CLOUD_CLOUD_POLICY_CLIENT_H_