File: configuration_policy_handler_ash.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (721 lines) | stat: -rw-r--r-- 27,536 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/ash/policy/handlers/configuration_policy_handler_ash.h"

#include <stdint.h>

#include <memory>
#include <optional>
#include <string_view>
#include <utility>
#include <vector>

#include "ash/constants/ash_features.h"
#include "ash/constants/ash_pref_names.h"
#include "ash/constants/geolocation_access_level.h"
#include "ash/system/privacy_hub/privacy_hub_controller.h"
#include "base/check.h"
#include "base/containers/contains.h"
#include "base/functional/callback.h"
#include "base/json/json_reader.h"
#include "base/json/json_writer.h"
#include "base/notreached.h"
#include "base/strings/strcat.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/values.h"
#include "chrome/browser/apps/app_service/policy_util.h"
#include "chrome/browser/ash/accessibility/magnifier_type.h"
#include "chrome/browser/ui/ash/shelf/chrome_shelf_prefs.h"
#include "chrome/browser/web_applications/policy/app_service_web_app_policy.h"
#include "chrome/browser/web_applications/policy/web_app_policy_manager.h"
#include "chrome/browser/web_applications/web_app_utils.h"
#include "chrome/common/pref_names.h"
#include "chromeos/ash/experiences/arc/arc_prefs.h"
#include "chromeos/components/onc/onc_signature.h"
#include "chromeos/components/onc/onc_utils.h"
#include "chromeos/components/onc/onc_validator.h"
#include "chromeos/dbus/power/power_policy_controller.h"
#include "components/crx_file/id_util.h"
#include "components/onc/onc_constants.h"
#include "components/onc/onc_pref_names.h"
#include "components/policy/core/browser/configuration_policy_handler.h"
#include "components/policy/core/browser/policy_error_map.h"
#include "components/policy/core/common/external_data_fetcher.h"
#include "components/policy/core/common/schema.h"
#include "components/policy/policy_constants.h"
#include "components/prefs/pref_value_map.h"
#include "components/strings/grit/components_strings.h"
#include "crypto/sha2.h"
#include "url/gurl.h"

namespace policy {

namespace {

using ::ash::MagnifierType;

constexpr char kPolicyEntryPolicyIdKey[] = "policy_id";
constexpr char kPolicyEntryFileExtensionsKey[] = "file_extensions";

constexpr char kSubkeyURL[] = "url";
constexpr char kSubkeyHash[] = "hash";

std::optional<std::string> GetSubkeyString(const base::Value::Dict& dict,
                                           PolicyErrorMap* errors,
                                           const std::string& policy,
                                           const std::string& subkey) {
  const base::Value* policy_value = dict.Find(subkey);

  if (!policy_value) {
    errors->AddError(policy, IDS_POLICY_NOT_SPECIFIED_ERROR,
                     PolicyErrorPath{subkey});
    return std::nullopt;
  }
  if (!policy_value->is_string()) {
    errors->AddError(policy, IDS_POLICY_TYPE_ERROR,
                     base::Value::GetTypeName(base::Value::Type::STRING),
                     PolicyErrorPath{subkey});
    return std::nullopt;
  }
  if (policy_value->GetString().empty()) {
    errors->AddError(policy, IDS_POLICY_NOT_SPECIFIED_ERROR,
                     PolicyErrorPath{subkey});
    return std::nullopt;
  }
  return policy_value->GetString();
}

constexpr char kScreenDimDelayAC[] = "AC.Delays.ScreenDim";
constexpr char kScreenOffDelayAC[] = "AC.Delays.ScreenOff";
constexpr char kIdleWarningDelayAC[] = "AC.Delays.IdleWarning";
constexpr char kIdleDelayAC[] = "AC.Delays.Idle";
constexpr char kIdleActionAC[] = "AC.IdleAction";
constexpr char kScreenDimDelayBattery[] = "Battery.Delays.ScreenDim";
constexpr char kScreenOffDelayBattery[] = "Battery.Delays.ScreenOff";
constexpr char kIdleWarningDelayBattery[] = "Battery.Delays.IdleWarning";
constexpr char kIdleDelayBattery[] = "Battery.Delays.Idle";
constexpr char kIdleActionBattery[] = "Battery.IdleAction";

constexpr char kScreenLockDelayAC[] = "AC";
constexpr char kScreenLockDelayBattery[] = "Battery";

constexpr char kActionSuspend[] = "Suspend";
constexpr char kActionLogout[] = "Logout";
constexpr char kActionShutdown[] = "Shutdown";
constexpr char kActionDoNothing[] = "DoNothing";

constexpr char kScreenBrightnessPercentAC[] = "BrightnessAC";
constexpr char kScreenBrightnessPercentBattery[] = "BrightnessBattery";

// Converts the string held by |value| to an int Value holding the corresponding
// |chromeos::PowerPolicyController| enum value. Returns an empty value if
// |value| is nullptr, not a string or if |value| holds a string which does not
// represent a known action.
base::Value ConvertToActionEnumValue(const base::Value* value) {
  if (!value || !value->is_string()) {
    return base::Value();
  }
  if (value->GetString() == kActionSuspend) {
    return base::Value(chromeos::PowerPolicyController::ACTION_SUSPEND);
  }
  if (value->GetString() == kActionLogout) {
    return base::Value(chromeos::PowerPolicyController::ACTION_STOP_SESSION);
  }
  if (value->GetString() == kActionShutdown) {
    return base::Value(chromeos::PowerPolicyController::ACTION_SHUT_DOWN);
  }
  if (value->GetString() == kActionDoNothing) {
    return base::Value(chromeos::PowerPolicyController::ACTION_DO_NOTHING);
  }
  return base::Value();
}

void SetPrefValueIfNotNull(PrefValueMap* prefs,
                           const std::string& name,
                           const base::Value* value) {
  if (value) {
    prefs->SetValue(name, value->Clone());
  }
}

base::Value CalculateIdleActionValue(const base::Value* idle_action_value,
                                     const base::Value* idle_delay_value) {
  // From the PowerManagementIdleSettings policy description, zero value for
  // the idle delay should disable the idle action. But for prefs, setting
  // |kPowerAcIdleDelayMs| or |kPowerBatteryIdleDelayMs| to zero does not
  // disable the corresponding idle action. See b/202113291. To be consistent
  // with policy description, we set power idle action to |ACTION_DO_NOTHING|,
  // if the idle delay is zero.
  if (idle_delay_value && idle_delay_value->GetInt() == 0) {
    return base::Value(chromeos::PowerPolicyController::ACTION_DO_NOTHING);
  }
  return ConvertToActionEnumValue(idle_action_value);
}

bool IsSupportedAppTypePolicyId(std::string_view policy_id) {
  return web_app::WebAppPolicyManager::IsChromeAppPolicyId(policy_id) ||
         web_app::IsArcAppPolicyId(policy_id) ||
         web_app::IsSystemWebAppPolicyId(policy_id) ||
         web_app::WebAppPolicyManager::IsWebAppPolicyId(policy_id) ||
         web_app::WebAppPolicyManager::IsPreinstalledWebAppPolicyId(
             policy_id) ||
         web_app::WebAppPolicyManager::IsIsolatedWebAppPolicyId(policy_id);
}

}  // namespace

ExternalDataPolicyHandler::ExternalDataPolicyHandler(const char* policy_name)
    : TypeCheckingPolicyHandler(policy_name, base::Value::Type::DICT) {}

ExternalDataPolicyHandler::~ExternalDataPolicyHandler() = default;

bool ExternalDataPolicyHandler::CheckPolicySettings(const PolicyMap& policies,
                                                    PolicyErrorMap* errors) {
  const std::string policy = policy_name();
  if (!policies.IsPolicySet(policy)) {
    return true;
  }

  return CheckPolicySettings(policy.c_str(), policies.Get(policy), errors);
}

bool ExternalDataPolicyHandler::CheckPolicySettings(
    const char* policy,
    const PolicyMap::Entry* entry,
    PolicyErrorMap* errors) {
  if (!TypeCheckingPolicyHandler::CheckPolicySettings(
          policy, base::Value::Type::DICT, entry, errors)) {
    return false;
  }

  const base::Value* value = entry->value(base::Value::Type::DICT);
  DCHECK(value);
  const base::Value::Dict& dict = value->GetDict();
  std::optional<std::string> url_string =
      GetSubkeyString(dict, errors, policy, kSubkeyURL);
  std::optional<std::string> hash_string =
      GetSubkeyString(dict, errors, policy, kSubkeyHash);
  if (!url_string || !hash_string) {
    return false;
  }

  const GURL url(url_string.value());
  if (!url.is_valid()) {
    errors->AddError(policy, IDS_POLICY_INVALID_URL_ERROR,
                     PolicyErrorPath{kSubkeyURL});
    return false;
  }

  std::vector<uint8_t> hash;
  if (!base::HexStringToBytes(hash_string.value(), &hash) ||
      hash.size() != crypto::kSHA256Length) {
    errors->AddError(policy, IDS_POLICY_INVALID_HASH_ERROR,
                     PolicyErrorPath{kSubkeyHash});
    return false;
  }

  return true;
}

void ExternalDataPolicyHandler::ApplyPolicySettings(const PolicyMap& policies,
                                                    PrefValueMap* prefs) {}

// static
NetworkConfigurationPolicyHandler*
NetworkConfigurationPolicyHandler::CreateForUserPolicy() {
  return new NetworkConfigurationPolicyHandler(
      key::kOpenNetworkConfiguration, onc::ONC_SOURCE_USER_POLICY,
      onc::prefs::kOpenNetworkConfiguration);
}

// static
NetworkConfigurationPolicyHandler*
NetworkConfigurationPolicyHandler::CreateForDevicePolicy() {
  return new NetworkConfigurationPolicyHandler(
      key::kDeviceOpenNetworkConfiguration, onc::ONC_SOURCE_DEVICE_POLICY,
      onc::prefs::kDeviceOpenNetworkConfiguration);
}

NetworkConfigurationPolicyHandler::~NetworkConfigurationPolicyHandler() =
    default;

bool NetworkConfigurationPolicyHandler::CheckPolicySettings(
    const PolicyMap& policies,
    PolicyErrorMap* errors) {
  const base::Value* value;
  if (!CheckAndGetValue(policies, errors, &value)) {
    return false;
  }

  if (!value) {
    return true;
  }

  std::optional<base::Value::Dict> root_dict =
      chromeos::onc::ReadDictionaryFromJson(value->GetString());
  if (!root_dict.has_value()) {
    errors->AddError(policy_name(), IDS_POLICY_NETWORK_CONFIG_PARSE_FAILED);
    return false;
  }

  // Validate the ONC dictionary. We are liberal and ignore unknown field
  // names and ignore invalid field names in kRecommended arrays.
  chromeos::onc::Validator validator(
      /*error_on_unknown_field=*/false,
      /*error_on_wrong_recommended=*/false,
      /*error_on_missing_field=*/true,
      /*managed_onc=*/true,
      /*log_warnings=*/true);
  validator.SetOncSource(onc_source_);

  // ONC policies are always unencrypted.
  chromeos::onc::Validator::Result validation_result;
  validator.ValidateAndRepairObject(
      &chromeos::onc::kToplevelConfigurationSignature, root_dict.value(),
      &validation_result);

  // Pass error/warning message and non-localized debug_info to PolicyErrorMap.
  std::vector<std::string_view> messages;
  for (const chromeos::onc::Validator::ValidationIssue& issue :
       validator.validation_issues()) {
    messages.push_back(issue.message);
  }
  std::string debug_info = base::JoinString(messages, "\n");

  if (validation_result == chromeos::onc::Validator::VALID_WITH_WARNINGS) {
    errors->AddError(policy_name(), IDS_POLICY_NETWORK_CONFIG_IMPORT_PARTIAL,
                     debug_info);
  } else if (validation_result == chromeos::onc::Validator::INVALID) {
    errors->AddError(policy_name(), IDS_POLICY_NETWORK_CONFIG_IMPORT_FAILED,
                     debug_info);
  }

  // In any case, don't reject the policy as some networks or certificates could
  // still be applied.
  return true;
}

void NetworkConfigurationPolicyHandler::ApplyPolicySettings(
    const PolicyMap& policies,
    PrefValueMap* prefs) {
  const base::Value* value =
      policies.GetValue(policy_name(), base::Value::Type::STRING);
  if (!value) {
    return;
  }

  const std::string& onc_blob = value->GetString();

  base::Value::List network_configs;
  base::Value::List certificates;
  base::Value::Dict global_network_config;
  chromeos::onc::ParseAndValidateOncForImport(
      onc_blob, onc_source_, &network_configs, &global_network_config,
      &certificates);

  // Currently, only the per-network configuration is stored in a pref. Ignore
  // |global_network_config| and |certificates|.
  prefs->SetValue(pref_path_, base::Value(std::move(network_configs)));
}

void NetworkConfigurationPolicyHandler::PrepareForDisplaying(
    PolicyMap* policies) const {
  const PolicyMap::Entry* entry = policies->Get(policy_name());
  if (!entry) {
    return;
  }
  std::optional<base::Value> sanitized_config =
      SanitizeNetworkConfig(entry->value(base::Value::Type::STRING));

  if (!sanitized_config.has_value()) {
    sanitized_config = base::Value();
  }

  policies->Set(policy_name(), entry->level, entry->scope, entry->source,
                std::move(sanitized_config), nullptr);
}

NetworkConfigurationPolicyHandler::NetworkConfigurationPolicyHandler(
    const char* policy_name,
    onc::ONCSource onc_source,
    const char* pref_path)
    : TypeCheckingPolicyHandler(policy_name, base::Value::Type::STRING),
      onc_source_(onc_source),
      pref_path_(pref_path) {}

// static
std::optional<base::Value>
NetworkConfigurationPolicyHandler::SanitizeNetworkConfig(
    const base::Value* config) {
  if (!config) {
    return std::nullopt;
  }

  std::optional<base::Value::Dict> config_dict =
      chromeos::onc::ReadDictionaryFromJson(config->GetString());
  if (!config_dict.has_value()) {
    return std::nullopt;
  }

  // Placeholder to insert in place of the filtered setting.
  const char kPlaceholder[] = "********";

  base::Value::Dict toplevel_dict = chromeos::onc::MaskCredentialsInOncObject(
      chromeos::onc::kToplevelConfigurationSignature, config_dict.value(),
      kPlaceholder);

  std::string json_string;
  base::JSONWriter::WriteWithOptions(
      toplevel_dict, base::JSONWriter::OPTIONS_PRETTY_PRINT, &json_string);
  return base::Value(json_string);
}

PinnedLauncherAppsPolicyHandler::PinnedLauncherAppsPolicyHandler()
    : ListPolicyHandler(key::kPinnedLauncherApps, base::Value::Type::STRING) {}

PinnedLauncherAppsPolicyHandler::~PinnedLauncherAppsPolicyHandler() = default;

bool PinnedLauncherAppsPolicyHandler::CheckListEntry(const base::Value& value) {
  const std::string& policy_id = value.GetString();
  return IsSupportedAppTypePolicyId(policy_id);
}

void PinnedLauncherAppsPolicyHandler::ApplyList(base::Value::List filtered_list,
                                                PrefValueMap* prefs) {
  base::Value::List pinned_apps_list;
  for (base::Value& entry : filtered_list) {
    auto app_dict = base::Value::Dict().Set(
        ChromeShelfPrefs::kPinnedAppsPrefAppIDKey, std::move(entry));
    pinned_apps_list.Append(std::move(app_dict));
  }
  prefs->SetValue(prefs::kPolicyPinnedLauncherApps,
                  base::Value(std::move(pinned_apps_list)));
}

DefaultHandlersForFileExtensionsPolicyHandler::
    DefaultHandlersForFileExtensionsPolicyHandler(
        const policy::Schema& chrome_schema)
    : SchemaValidatingPolicyHandler(
          key::kDefaultHandlersForFileExtensions,
          chrome_schema.GetKnownProperty(
              key::kDefaultHandlersForFileExtensions),
          policy::SCHEMA_ALLOW_UNKNOWN_AND_INVALID_LIST_ENTRY) {}

// Verifies that each file extension is handler by no more that one app.
bool DefaultHandlersForFileExtensionsPolicyHandler::CheckPolicySettings(
    const PolicyMap& policies,
    PolicyErrorMap* errors) {
  std::unique_ptr<base::Value> policy_value;
  if (!CheckAndGetValue(policies, errors, &policy_value) || !policy_value) {
    return false;
  }

  base::flat_map<std::string, std::string> file_extension_to_policy_id;

  const auto& list = policy_value->GetList();
  for (uint32_t index = 0; index < list.size(); index++) {
    const auto& policy_entry_dict = list[index].GetDict();

    const std::string* policy_id =
        policy_entry_dict.FindString(kPolicyEntryPolicyIdKey);
    DCHECK(policy_id);

    if (!IsValidPolicyId(*policy_id)) {
      errors->AddError(policy_name(), IDS_POLICY_VALUE_FORMAT_ERROR,
                       PolicyErrorPath{index, kPolicyEntryPolicyIdKey});
      continue;
    }

    const auto* file_extensions =
        policy_entry_dict.FindList(kPolicyEntryFileExtensionsKey);
    DCHECK(file_extensions);

    for (const auto& file_extension_entry : *file_extensions) {
      const std::string& file_extension = file_extension_entry.GetString();

      if (auto it = file_extension_to_policy_id.find(file_extension);
          it != file_extension_to_policy_id.end()) {
        errors->AddError(
            policy_name(), IDS_POLICY_DUPLICATE_FILE_EXTENSION_ERROR,
            /*replacement_a=*/file_extension,
            /*replacement_b=*/base::JoinString({*policy_id, it->second}, ", "),
            /*error_path=*/{},
            /*error_level=*/PolicyMap::MessageType::kWarning);
        continue;
      }

      file_extension_to_policy_id[file_extension] = *policy_id;
    }
  }

  return true;
}

// Applies an inverse mapping to `prefs::kDefaultHandlersForFileExtensions`:
// file_extension -> id.
void DefaultHandlersForFileExtensionsPolicyHandler::ApplyPolicySettings(
    const PolicyMap& policies,
    PrefValueMap* prefs) {
  std::unique_ptr<base::Value> policy_value;
  CheckAndGetValue(policies, nullptr, &policy_value);

  base::Value::Dict pref_mapping;
  for (const auto& policy_entry : policy_value->GetList()) {
    const auto& policy_entry_dict = policy_entry.GetDict();

    const std::string* policy_id =
        policy_entry_dict.FindString(kPolicyEntryPolicyIdKey);
    if (!IsValidPolicyId(*policy_id)) {
      continue;
    }

    const auto* file_extensions =
        policy_entry_dict.FindList(kPolicyEntryFileExtensionsKey);

    for (const auto& file_extension_entry : *file_extensions) {
      pref_mapping.Set(base::StrCat({".", file_extension_entry.GetString()}),
                       *policy_id);
    }
  }

  prefs->SetValue(prefs::kDefaultHandlersForFileExtensions,
                  base::Value(std::move(pref_mapping)));
}

bool DefaultHandlersForFileExtensionsPolicyHandler::IsValidPolicyId(
    std::string_view policy_id) const {
  return IsSupportedAppTypePolicyId(policy_id) ||
         apps_util::IsFileManagerVirtualTaskPolicyId(policy_id);
}

ScreenMagnifierPolicyHandler::ScreenMagnifierPolicyHandler()
    : IntRangePolicyHandlerBase(key::kScreenMagnifierType,
                                static_cast<int>(MagnifierType::kDisabled),
                                static_cast<int>(MagnifierType::kDocked),
                                false) {}

ScreenMagnifierPolicyHandler::~ScreenMagnifierPolicyHandler() = default;

void ScreenMagnifierPolicyHandler::ApplyPolicySettings(
    const PolicyMap& policies,
    PrefValueMap* prefs) {
  // It is safe to use `GetValueUnsafe()` because type checking is performed
  // before the value is used.
  const base::Value* value = policies.GetValueUnsafe(policy_name());
  int value_in_range;
  if (value && EnsureInRange(value, &value_in_range, nullptr)) {
    prefs->SetBoolean(ash::prefs::kAccessibilityScreenMagnifierEnabled,
                      value_in_range == static_cast<int>(MagnifierType::kFull));
    prefs->SetBoolean(
        ash::prefs::kDockedMagnifierEnabled,
        value_in_range == static_cast<int>(MagnifierType::kDocked));
  }
}

LoginScreenPowerManagementPolicyHandler::
    LoginScreenPowerManagementPolicyHandler(const Schema& chrome_schema)
    : SchemaValidatingPolicyHandler(key::kDeviceLoginScreenPowerManagement,
                                    chrome_schema.GetKnownProperty(
                                        key::kDeviceLoginScreenPowerManagement),
                                    SCHEMA_ALLOW_UNKNOWN) {}

LoginScreenPowerManagementPolicyHandler::
    ~LoginScreenPowerManagementPolicyHandler() = default;

void LoginScreenPowerManagementPolicyHandler::ApplyPolicySettings(
    const PolicyMap& policies,
    PrefValueMap* prefs) {}

DeprecatedIdleActionHandler::DeprecatedIdleActionHandler()
    : IntRangePolicyHandlerBase(
          key::kIdleAction,
          chromeos::PowerPolicyController::ACTION_SUSPEND,
          chromeos::PowerPolicyController::ACTION_DO_NOTHING,
          false) {}

DeprecatedIdleActionHandler::~DeprecatedIdleActionHandler() = default;

void DeprecatedIdleActionHandler::ApplyPolicySettings(const PolicyMap& policies,
                                                      PrefValueMap* prefs) {
  // It is safe to use `GetValueUnsafe()` because type checking is performed
  // before the value is used.
  const base::Value* value = policies.GetValueUnsafe(policy_name());
  if (value && EnsureInRange(value, nullptr, nullptr)) {
    if (!prefs->GetValue(ash::prefs::kPowerAcIdleAction, nullptr)) {
      prefs->SetValue(ash::prefs::kPowerAcIdleAction, value->Clone());
    }
    if (!prefs->GetValue(ash::prefs::kPowerBatteryIdleAction, nullptr)) {
      prefs->SetValue(ash::prefs::kPowerBatteryIdleAction, value->Clone());
    }
  }
}

PowerManagementIdleSettingsPolicyHandler::
    PowerManagementIdleSettingsPolicyHandler(const Schema& chrome_schema)
    : SchemaValidatingPolicyHandler(
          key::kPowerManagementIdleSettings,
          chrome_schema.GetKnownProperty(key::kPowerManagementIdleSettings),
          SCHEMA_ALLOW_UNKNOWN) {}

PowerManagementIdleSettingsPolicyHandler::
    ~PowerManagementIdleSettingsPolicyHandler() = default;

void PowerManagementIdleSettingsPolicyHandler::ApplyPolicySettings(
    const PolicyMap& policies,
    PrefValueMap* prefs) {
  std::unique_ptr<base::Value> policy_value;
  if (!CheckAndGetValue(policies, nullptr, &policy_value) || !policy_value) {
    return;
  }
  const base::Value::Dict& policy_value_dict = policy_value->GetDict();

  SetPrefValueIfNotNull(prefs, ash::prefs::kPowerAcScreenDimDelayMs,
                        policy_value_dict.FindByDottedPath(kScreenDimDelayAC));
  SetPrefValueIfNotNull(prefs, ash::prefs::kPowerAcScreenOffDelayMs,
                        policy_value_dict.FindByDottedPath(kScreenOffDelayAC));
  SetPrefValueIfNotNull(
      prefs, ash::prefs::kPowerAcIdleWarningDelayMs,
      policy_value_dict.FindByDottedPath(kIdleWarningDelayAC));

  const base::Value* idle_delay_ac_value =
      policy_value_dict.FindByDottedPath(kIdleDelayAC);
  SetPrefValueIfNotNull(prefs, ash::prefs::kPowerAcIdleDelayMs,
                        idle_delay_ac_value);

  base::Value idle_action_ac_value = CalculateIdleActionValue(
      policy_value_dict.FindByDottedPath(kIdleActionAC), idle_delay_ac_value);
  if (!idle_action_ac_value.is_none()) {
    prefs->SetValue(ash::prefs::kPowerAcIdleAction,
                    std::move(idle_action_ac_value));
  }

  SetPrefValueIfNotNull(
      prefs, ash::prefs::kPowerBatteryScreenDimDelayMs,
      policy_value_dict.FindByDottedPath(kScreenDimDelayBattery));
  SetPrefValueIfNotNull(
      prefs, ash::prefs::kPowerBatteryScreenOffDelayMs,
      policy_value_dict.FindByDottedPath(kScreenOffDelayBattery));
  SetPrefValueIfNotNull(
      prefs, ash::prefs::kPowerBatteryIdleWarningDelayMs,
      policy_value_dict.FindByDottedPath(kIdleWarningDelayBattery));

  const base::Value* idle_delay_battery_value =
      policy_value_dict.FindByDottedPath(kIdleDelayBattery);
  SetPrefValueIfNotNull(prefs, ash::prefs::kPowerBatteryIdleDelayMs,
                        idle_delay_battery_value);

  base::Value idle_action_battery_value = CalculateIdleActionValue(
      policy_value_dict.FindByDottedPath(kIdleActionBattery),
      idle_delay_battery_value);
  if (!idle_action_battery_value.is_none()) {
    prefs->SetValue(ash::prefs::kPowerBatteryIdleAction,
                    std::move(idle_action_battery_value));
  }
}

ScreenLockDelayPolicyHandler::ScreenLockDelayPolicyHandler(
    const Schema& chrome_schema)
    : SchemaValidatingPolicyHandler(
          key::kScreenLockDelays,
          chrome_schema.GetKnownProperty(key::kScreenLockDelays),
          SCHEMA_ALLOW_UNKNOWN) {}

ScreenLockDelayPolicyHandler::~ScreenLockDelayPolicyHandler() = default;

void ScreenLockDelayPolicyHandler::ApplyPolicySettings(
    const PolicyMap& policies,
    PrefValueMap* prefs) {
  std::unique_ptr<base::Value> policy_value;
  if (!CheckAndGetValue(policies, nullptr, &policy_value) || !policy_value) {
    return;
  }
  const base::Value::Dict& policy_value_dict = policy_value->GetDict();

  SetPrefValueIfNotNull(prefs, ash::prefs::kPowerAcScreenLockDelayMs,
                        policy_value_dict.Find(kScreenLockDelayAC));
  SetPrefValueIfNotNull(prefs, ash::prefs::kPowerBatteryScreenLockDelayMs,
                        policy_value_dict.Find(kScreenLockDelayBattery));
}

ScreenBrightnessPercentPolicyHandler::ScreenBrightnessPercentPolicyHandler(
    const Schema& chrome_schema)
    : SchemaValidatingPolicyHandler(
          key::kScreenBrightnessPercent,
          chrome_schema.GetKnownProperty(key::kScreenBrightnessPercent),
          SCHEMA_ALLOW_UNKNOWN) {}

ScreenBrightnessPercentPolicyHandler::~ScreenBrightnessPercentPolicyHandler() =
    default;

void ScreenBrightnessPercentPolicyHandler::ApplyPolicySettings(
    const PolicyMap& policies,
    PrefValueMap* prefs) {
  std::unique_ptr<base::Value> policy_value;
  if (!CheckAndGetValue(policies, nullptr, &policy_value) || !policy_value) {
    return;
  }
  const base::Value::Dict& policy_value_dict = policy_value->GetDict();

  SetPrefValueIfNotNull(prefs, ash::prefs::kPowerAcScreenBrightnessPercent,
                        policy_value_dict.Find(kScreenBrightnessPercentAC));
  SetPrefValueIfNotNull(
      prefs, ash::prefs::kPowerBatteryScreenBrightnessPercent,
      policy_value_dict.Find(kScreenBrightnessPercentBattery));
}

ArcServicePolicyHandler::ArcServicePolicyHandler(const char* policy,
                                                 const char* pref)
    : IntRangePolicyHandlerBase(
          policy,
          static_cast<int>(ArcServicePolicyValue::kDisabled),
          static_cast<int>(ArcServicePolicyValue::kEnabled),
          false /* clamp */),
      pref_(pref) {}

void ArcServicePolicyHandler::ApplyPolicySettings(const PolicyMap& policies,
                                                  PrefValueMap* prefs) {
  const base::Value* const value =
      policies.GetValue(policy_name(), base::Value::Type::INTEGER);
  if (!value) {
    return;
  }
  const base::Value* current_value = nullptr;
  if (prefs->GetValue(pref_, &current_value)) {
    // If a value for this policy was already set by another handler, do not
    // clobber it. This is necessary so that the DefaultGeolocationSetting
    // policy can take precedence over ArcLocationServiceEnabled.
    return;
  }
  if (value->GetInt() == static_cast<int>(ArcServicePolicyValue::kDisabled)) {
    prefs->SetBoolean(pref_, false);
  } else if (value->GetInt() ==
             static_cast<int>(ArcServicePolicyValue::kEnabled)) {
    prefs->SetBoolean(pref_, true);
  }
}

ArcLocationServicePolicyHandler::ArcLocationServicePolicyHandler(
    const char* policy,
    const char* pref)
    : ArcServicePolicyHandler(policy, pref) {}

void ArcLocationServicePolicyHandler::ApplyPolicySettings(
    const PolicyMap& policies,
    PrefValueMap* prefs) {
  // After the Privacy Hub rollout, the Android location toggle will be replaced
  // by the ChromeOS location toggle in the OOBE dialog. This new toggle will be
  // controlled by `kGoogleLocationServicesEnabled`. This new toggle will no
  // longer support force-setting only the initial value during the setup flow,
  // so we can ignore this policy.
  if (ash::features::IsCrosPrivacyHubLocationEnabled()) {
    return;
  }

  // Legacy handling.
  ArcServicePolicyHandler::ApplyPolicySettings(policies, prefs);
}

}  // namespace policy