File: profile_network_context_service.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 (1650 lines) | stat: -rw-r--r-- 67,173 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
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
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
// Copyright 2017 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/net/profile_network_context_service.h"

#include <memory>
#include <string>
#include <string_view>

#include "base/base64.h"
#include "base/check_op.h"
#include "base/command_line.h"
#include "base/containers/flat_map.h"
#include "base/containers/span.h"
#include "base/containers/to_vector.h"
#include "base/feature_list.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/functional/bind.h"
#include "base/functional/callback_helpers.h"
#include "base/metrics/field_trial.h"
#include "base/metrics/field_trial_params.h"
#include "base/metrics/histogram_macros.h"
#include "base/notreached.h"
#include "base/strings/string_split.h"
#include "base/strings/string_util.h"
#include "base/strings/string_view_util.h"
#include "base/task/sequenced_task_runner.h"
#include "base/task/task_traits.h"
#include "base/task/thread_pool.h"
#include "base/trace_event/trace_event.h"
#include "build/build_config.h"
#include "build/chromeos_buildflags.h"
#include "chrome/browser/browser_features.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/content_settings/cookie_settings_factory.h"
#include "chrome/browser/content_settings/host_content_settings_map_factory.h"
#include "chrome/browser/domain_reliability/service_factory.h"
#include "chrome/browser/first_party_sets/first_party_sets_policy_service.h"
#include "chrome/browser/first_party_sets/first_party_sets_policy_service_factory.h"
#include "chrome/browser/ip_protection/ip_protection_core_host.h"
#include "chrome/browser/ip_protection/ip_protection_core_host_factory.h"
#include "chrome/browser/net/system_network_context_manager.h"
#include "chrome/browser/privacy_sandbox/privacy_sandbox_settings_factory.h"
#include "chrome/browser/privacy_sandbox/tracking_protection_settings_factory.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ssl/sct_reporting_service.h"
#include "chrome/browser/ssl/sct_reporting_service_factory.h"
#include "chrome/browser/webid/federated_identity_permission_context.h"
#include "chrome/browser/webid/federated_identity_permission_context_factory.h"
#include "chrome/common/buildflags.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_content_client.h"
#include "chrome/common/chrome_features.h"
#include "chrome/common/chrome_paths_internal.h"
#include "chrome/common/pref_names.h"
#include "components/certificate_transparency/pref_names.h"
#include "components/content_settings/core/browser/cookie_settings.h"
#include "components/content_settings/core/browser/host_content_settings_map.h"
#include "components/content_settings/core/common/content_settings.h"
#include "components/content_settings/core/common/content_settings_types.h"
#include "components/content_settings/core/common/content_settings_utils.h"
#include "components/content_settings/core/common/pref_names.h"
#include "components/embedder_support/pref_names.h"
#include "components/embedder_support/switches.h"
#include "components/language/core/browser/language_prefs.h"
#include "components/language/core/browser/pref_names.h"
#include "components/metrics/metrics_pref_names.h"
#include "components/permissions/features.h"
#include "components/pref_registry/pref_registry_syncable.h"
#include "components/prefs/pref_registry_simple.h"
#include "components/prefs/pref_service.h"
#include "components/privacy_sandbox/privacy_sandbox_prefs.h"
#include "components/safe_browsing/core/common/safe_browsing_prefs.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/first_party_sets_handler.h"
#include "content/public/browser/network_service_instance.h"
#include "content/public/browser/shared_cors_origin_access_list.h"
#include "content/public/browser/storage_partition.h"
#include "content/public/common/url_constants.h"
#include "crypto/crypto_buildflags.h"
#include "mojo/public/cpp/bindings/pending_remote.h"
#include "net/base/features.h"
#include "net/cert/asn1_util.h"
#include "net/disk_cache/backend_experiment.h"
#include "net/http/http_auth_preferences.h"
#include "net/http/http_util.h"
#include "net/net_buildflags.h"
#include "net/ssl/client_cert_store.h"
#include "services/cert_verifier/public/mojom/cert_verifier_service_factory.mojom.h"
#include "services/network/public/cpp/cors/origin_access_list.h"
#include "services/network/public/cpp/features.h"
#include "services/network/public/cpp/network_switches.h"
#include "services/network/public/mojom/cert_verifier_service.mojom.h"
#include "services/network/public/mojom/first_party_sets_access_delegate.mojom.h"
#include "services/network/public/mojom/network_context.mojom.h"
#include "services/network/public/mojom/network_service.mojom.h"
#include "third_party/blink/public/common/features.h"

#if BUILDFLAG(IS_CHROMEOS)
#include "ash/constants/ash_features.h"
#include "ash/constants/ash_switches.h"
#include "chrome/browser/ash/kcer/kcer_factory_ash.h"
#include "chrome/browser/ash/net/client_cert_store_ash.h"
#include "chrome/browser/ash/net/client_cert_store_kcer.h"
#include "chrome/browser/ash/profiles/profile_helper.h"
#include "chrome/browser/certificate_provider/certificate_provider.h"
#include "chrome/browser/certificate_provider/certificate_provider_service.h"
#include "chrome/browser/certificate_provider/certificate_provider_service_factory.h"
#include "chrome/browser/policy/networking/policy_cert_service.h"
#include "chrome/browser/policy/networking/policy_cert_service_factory.h"
#include "chrome/browser/policy/profile_policy_connector.h"
#include "chromeos/components/kiosk/kiosk_utils.h"
#include "chromeos/constants/chromeos_features.h"
#include "components/user_manager/user.h"
#include "components/user_manager/user_manager.h"
#include "net/cert/x509_util.h"
#endif

#if BUILDFLAG(USE_NSS_CERTS)
#include "chrome/browser/ui/crypto_module_delegate_nss.h"
#include "net/ssl/client_cert_store_nss.h"
#endif  // BUILDFLAG(USE_NSS_CERTS)

#if BUILDFLAG(IS_WIN)
#include "net/ssl/client_cert_store_win.h"
#endif  // BUILDFLAG(IS_WIN)

#if BUILDFLAG(IS_MAC)
#include "net/ssl/client_cert_store_mac.h"
#endif  // BUILDFLAG(IS_MAC)

#if BUILDFLAG(ENABLE_EXTENSIONS)
#include "extensions/common/constants.h"
#endif

#if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC) || BUILDFLAG(IS_LINUX)
#include "chrome/browser/enterprise/client_certificates/certificate_provisioning_service_factory.h"
#include "chrome/browser/policy/chrome_browser_policy_connector.h"
#include "components/enterprise/browser/controller/chrome_browser_cloud_management_controller.h"
#include "components/enterprise/client_certificates/core/certificate_provisioning_service.h"
#include "components/enterprise/client_certificates/core/client_certificates_service.h"
#include "components/enterprise/client_certificates/core/features.h"
#include "components/policy/core/browser/browser_policy_connector.h"
#endif

#if BUILDFLAG(CHROME_ROOT_STORE_CERT_MANAGEMENT_UI)
#include "chrome/browser/net/server_certificate_database_service_factory.h"  // nogncheck
#include "components/server_certificate_database/server_certificate_database.h"  // nogncheck
#include "components/server_certificate_database/server_certificate_database.pb.h"  // nogncheck
#include "components/server_certificate_database/server_certificate_database_service.h"  // nogncheck
#endif

namespace {

bool* g_discard_domain_reliability_uploads_for_testing = nullptr;

const char kHttpCacheFinchExperimentGroups[] =
    "profile_network_context_service.http_cache_finch_experiment_groups";

std::vector<std::string> TranslateStringArray(const base::Value::List& list) {
  std::vector<std::string> strings;
  for (const base::Value& value : list) {
    DCHECK(value.is_string());
    strings.push_back(value.GetString());
  }
  return strings;
}

std::string ComputeAcceptLanguageFromPref(const std::string& language_pref) {
  std::string accept_languages_str =
      net::HttpUtil::ExpandLanguageList(language_pref);
  return net::HttpUtil::GenerateAcceptLanguageHeader(accept_languages_str);
}

// Tests allowing ambient authentication with default credentials based on the
// profile type.
bool IsAmbientAuthAllowedForProfile(Profile* profile) {
  // Ambient authentication is always enabled for regular and system profiles.
  // System profiles (used in profile picker) may require authentication to
  // let user login.
  if (profile->IsRegularProfile() || profile->IsSystemProfile()) {
    return true;
  }

  // Non-primary OTR profiles are not used to create browser windows and are
  // only technical means for a task that does not need to leave state after
  // it's completed.
  if (profile->IsOffTheRecord() && !profile->IsPrimaryOTRProfile()) {
    return true;
  }

  PrefService* local_state = g_browser_process->local_state();
  DCHECK(local_state);
  DCHECK(local_state->FindPreference(
      prefs::kAmbientAuthenticationInPrivateModesEnabled));

  net::AmbientAuthAllowedProfileTypes type =
      static_cast<net::AmbientAuthAllowedProfileTypes>(local_state->GetInteger(
          prefs::kAmbientAuthenticationInPrivateModesEnabled));

  if (profile->IsGuestSession()) {
    return type == net::AmbientAuthAllowedProfileTypes::kGuestAndRegular ||
           type == net::AmbientAuthAllowedProfileTypes::kAll;
  } else if (profile->IsIncognitoProfile()) {
    return type == net::AmbientAuthAllowedProfileTypes::kIncognitoAndRegular ||
           type == net::AmbientAuthAllowedProfileTypes::kAll;
  }

  // Profile type not yet supported.
  NOTREACHED();
}

void UpdateAntiAbuseSettings(Profile* profile) {
  ContentSetting content_setting =
      HostContentSettingsMapFactory::GetForProfile(profile)
          ->GetDefaultContentSetting(ContentSettingsType::ANTI_ABUSE, nullptr);
  const bool block_trust_tokens = content_setting == CONTENT_SETTING_BLOCK;
  profile->ForEachLoadedStoragePartition(
      [&](content::StoragePartition* storage_partition) {
        storage_partition->GetNetworkContext()->SetBlockTrustTokens(
            block_trust_tokens);
      });
}

bool IsContentSettingsTypeEnabled(ContentSettingsType type) {
  switch (type) {
    case ContentSettingsType::STORAGE_ACCESS:
    case ContentSettingsType::TOP_LEVEL_STORAGE_ACCESS:
      return true;
    default:
      return content_settings::CookieSettings::GetContentSettingsTypes()
          .contains(type);
  }
}

void UpdateTrackingProtectionSettings(Profile* profile) {
  auto settings =
      HostContentSettingsMapFactory::GetForProfile(profile)
          ->GetSettingsForOneType(ContentSettingsType::TRACKING_PROTECTION);
  profile->ForEachLoadedStoragePartition(
      [&](content::StoragePartition* storage_partition) {
        storage_partition->GetNetworkContext()
            ->SetTrackingProtectionContentSetting(settings);
      });
}

void UpdateCookieSettings(Profile* profile, ContentSettingsType type) {
  if (!IsContentSettingsTypeEnabled(type)) {
    return;
  }

  ContentSettingsForOneType settings;
  if (type == ContentSettingsType::FEDERATED_IDENTITY_SHARING) {
    // Note: FederatedIdentityPermissionContext also syncs the permissions
    // directly, in order to avoid a race condition. (Namely,
    // FederatedIdentityPermissionContext must guarantee that the permissions
    // have propagated before it calls its callback. However, the syncing that
    // occurs in this class is unsynchronized, so it would be racy to rely on
    // this update finishing before calling the context's callback.) This
    // unfortunately triggers a double-update here.
    if (FederatedIdentityPermissionContext* fedcm_context =
            FederatedIdentityPermissionContextFactory::GetForProfile(profile);
        fedcm_context) {
      settings = fedcm_context->GetSharingPermissionGrantsAsContentSettings();
    }
  } else {
    settings = HostContentSettingsMapFactory::GetForProfile(profile)
                   ->GetSettingsForOneType(type);
  }
  profile->ForEachLoadedStoragePartition(
      [&](content::StoragePartition* storage_partition) {
        storage_partition->GetCookieManagerForBrowserProcess()
            ->SetContentSettings(type, settings, base::NullCallback());
      });
}

#if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC) || BUILDFLAG(IS_LINUX)
std::unique_ptr<net::ClientCertStore> GetWrappedCertStore(
    Profile* profile,
    std::unique_ptr<net::ClientCertStore> platform_store) {
  client_certificates::CertificateProvisioningService*
      profile_provisioning_service = nullptr;
  if (profile && client_certificates::features::
                     IsManagedClientCertificateForUserEnabled()) {
    profile_provisioning_service = client_certificates::
        CertificateProvisioningServiceFactory::GetForProfile(profile);
  }

  client_certificates::CertificateProvisioningService*
      browser_provisioning_service = nullptr;
  if (client_certificates::features::
          IsManagedBrowserClientCertificateEnabled()) {
    browser_provisioning_service =
        g_browser_process->browser_policy_connector()
            ->chrome_browser_cloud_management_controller()
            ->GetCertificateProvisioningService();
  }

  if (!browser_provisioning_service && !profile_provisioning_service) {
    return platform_store;
  }

  return client_certificates::ClientCertificatesService::Create(
      profile_provisioning_service, browser_provisioning_service,
      std::move(platform_store));
}
#endif  // BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC) || BUILDFLAG(IS_LINUX)

bool IsValidDNSConstraint(std::string_view possible_dns_constraint) {
  return base::IsStringASCII(possible_dns_constraint) &&
         possible_dns_constraint.length() <= 255;
}

bool MaskFromIPAndPrefixLength(const net::IPAddress& ip,
                               size_t prefix_length,
                               net::IPAddress* mask) {
  if (ip.IsIPv4()) {
    if (!net::IPAddress::CreateIPv4Mask(mask, prefix_length)) {
      return false;
    }
  } else if (ip.IsIPv6()) {
    if (!net::IPAddress::CreateIPv6Mask(mask, prefix_length)) {
      return false;
    }
  } else {
    // Somehow got an IP address that isn't ipv4 or ipv6?
    return false;
  }
  return true;
}

// Parses the |possible_cidr_constraint|, populating |parsed_cidr| and |mask|,
// and then return true.
//
// If |possible_cidr_constraint| did not properly parse, returns false. The
// state of |parsed_cidr| and |mask| in this case is not guaranteed.
bool ParseCIDRConstraint(std::string_view possible_cidr_constraint,
                         net::IPAddress* parsed_cidr,
                         net::IPAddress* mask) {
  size_t prefix_length;
  if (!net::ParseCIDRBlock(possible_cidr_constraint, parsed_cidr,
                           &prefix_length)) {
    return false;
  }
  return MaskFromIPAndPrefixLength(*parsed_cidr, prefix_length, mask);
}

#if BUILDFLAG(CHROME_ROOT_STORE_CERT_MANAGEMENT_UI)
// Add a cert with constraints to the provided list.
// This will add a certificate from |cert_info| to the |cert_list| with
// any added constraints that are in |cert_info.cert_metadata|. It is okay for
// there to be no constraints in |cert_info.cert_metadata|.
//
// If any constraints in |cert_info.cert_metadata| are not valid, then the
// certificate will not be added to |cert_list| and this function will return
// false. Otherwise, the certificate will be added to |cert_list| and this
// function will return true.
bool MaybeAddCertWithConstraints(
    const net::ServerCertificateDatabase::CertInformation& cert_info,
    std::vector<cert_verifier::mojom::CertWithConstraintsPtr>* cert_list) {
  auto cert_with_constraints_mojo =
      cert_verifier::mojom::CertWithConstraints::New();
  cert_with_constraints_mojo->certificate = cert_info.der_cert;
  for (const auto& dns_constraint :
       cert_info.cert_metadata.constraints().dns_names()) {
    if (IsValidDNSConstraint(dns_constraint)) {
      cert_with_constraints_mojo->permitted_dns_names.push_back(dns_constraint);
    } else {
      return false;
    }
  }
  for (const auto& cidr_constraint :
       cert_info.cert_metadata.constraints().cidrs()) {
    net::IPAddress ip(base::as_byte_span(cidr_constraint.ip()));
    net::IPAddress mask;
    if (!MaskFromIPAndPrefixLength(ip, cidr_constraint.prefix_length(),
                                   &mask)) {
      return false;
    }
    cert_with_constraints_mojo->permitted_cidrs.push_back(
        cert_verifier::mojom::CIDR::New(/*ip=*/ip,
                                        /*mask=*/mask));
  }

  cert_list->push_back(std::move(cert_with_constraints_mojo));
  return true;
}
#endif

// Returns true if IP Protection is needed.
// Returns false if any of the following:
//   1. ipp_core_host == nullptr. A nullptr implies the profile does not
//      participate in IPP.
//   2. kIpPrivacyIncognitoMode is enabled and the profile in not incognito.
bool NeedsIpProtection(const IpProtectionCoreHost* ipp_core_host,
                       const Profile& profile) {
  return ipp_core_host && (profile.IsIncognitoProfile() ||
                           !net::features::kIpPrivacyOnlyInIncognito.Get());
}

}  // namespace

ProfileNetworkContextService::ProfileNetworkContextService(Profile* profile)
    : profile_(profile),
      proxy_config_monitor_(std::make_unique<ProxyConfigMonitor>(profile)) {
  TRACE_EVENT0("startup", "ProfileNetworkContextService::ctor");
  PrefService* profile_prefs = profile->GetPrefs();
  quic_allowed_.Init(prefs::kQuicAllowed, profile_prefs,
                     base::BindRepeating(
                         &ProfileNetworkContextService::DisableQuicIfNotAllowed,
                         base::Unretained(this)));
  pref_accept_language_.Init(
      language::prefs::kAcceptLanguages, profile_prefs,
      base::BindRepeating(&ProfileNetworkContextService::UpdateAcceptLanguage,
                          base::Unretained(this)));
  enable_referrers_.Init(
      prefs::kEnableReferrers, profile_prefs,
      base::BindRepeating(&ProfileNetworkContextService::UpdateReferrersEnabled,
                          base::Unretained(this)));
  cookie_settings_ = CookieSettingsFactory::GetForProfile(profile);
  cookie_settings_observation_.Observe(cookie_settings_.get());

  DisableQuicIfNotAllowed();

  // Observe content settings so they can be synced to the network service.
  HostContentSettingsMapFactory::GetForProfile(profile_)->AddObserver(this);

  pref_change_registrar_.Init(profile_prefs);

  // When any of the following CT preferences change, we schedule an update
  // to aggregate the actual update using a |ct_policy_update_timer_|.
  pref_change_registrar_.Add(
      certificate_transparency::prefs::kCTExcludedHosts,
      base::BindRepeating(&ProfileNetworkContextService::ScheduleUpdateCTPolicy,
                          base::Unretained(this)));
  pref_change_registrar_.Add(
      certificate_transparency::prefs::kCTExcludedSPKIs,
      base::BindRepeating(&ProfileNetworkContextService::ScheduleUpdateCTPolicy,
                          base::Unretained(this)));
  // When any of the following Certificate preferences change, we schedule an
  // update to aggregate the actual update using a |cert_policy_update_timer_|.
  base::RepeatingClosure schedule_update_cert_policy = base::BindRepeating(
      &ProfileNetworkContextService::ScheduleUpdateCertificatePolicy,
      base::Unretained(this));
  pref_change_registrar_.Add(prefs::kCACertificates,
                             schedule_update_cert_policy);
  pref_change_registrar_.Add(prefs::kCACertificatesWithConstraints,
                             schedule_update_cert_policy);
  pref_change_registrar_.Add(prefs::kCADistrustedCertificates,
                             schedule_update_cert_policy);
  pref_change_registrar_.Add(prefs::kCAHintCertificates,
                             schedule_update_cert_policy);
#if !BUILDFLAG(IS_CHROMEOS)
  pref_change_registrar_.Add(prefs::kCAPlatformIntegrationEnabled,
                             schedule_update_cert_policy);
#endif

#if BUILDFLAG(CHROME_ROOT_STORE_CERT_MANAGEMENT_UI)
  if (base::FeatureList::IsEnabled(features::kEnableCertManagementUIV2Write)) {
    // Register observer to update certificates when changes are made to the
    // server cert database. Unretained is safe as the
    // `server_cert_database_observer_` is a CallbackListSubscription which
    // will unregister the observer once the ProfileNetworkContextService is
    // destroyed.
    net::ServerCertificateDatabaseService* server_cert_db_service =
        net::ServerCertificateDatabaseServiceFactory::GetForBrowserContext(
            profile_);
    // The service can be null for AshInternals profiles.
    if (server_cert_db_service) {
      server_cert_database_observer_ =
          server_cert_db_service->AddObserver(base::BindRepeating(
              &ProfileNetworkContextService::UpdateAdditionalCertificates,
              base::Unretained(this)));
    }
  }
#endif

  pref_change_registrar_.Add(
      prefs::kGloballyScopeHTTPAuthCacheEnabled,
      base::BindRepeating(&ProfileNetworkContextService::
                              UpdateSplitAuthCacheByNetworkIsolationKey,
                          base::Unretained(this)));
  pref_change_registrar_.Add(
      prefs::kCorsNonWildcardRequestHeadersSupport,
      base::BindRepeating(&ProfileNetworkContextService::
                              UpdateCorsNonWildcardRequestHeadersSupport,
                          base::Unretained(this)));

#if BUILDFLAG(ENABLE_REPORTING)
  if (base::FeatureList::IsEnabled(
          net::features::kReportingApiEnableEnterpriseCookieIssues)) {
    pref_change_registrar_.Add(
        prefs::kReportingEndpoints,
        base::BindRepeating(
            &ProfileNetworkContextService::UpdateEnterpriseReportingEndpoints,
            base::Unretained(this)));
  }
#endif  // BUILDFLAG(ENABLE_REPORTING)
}

ProfileNetworkContextService::~ProfileNetworkContextService() = default;

void ProfileNetworkContextService::ConfigureNetworkContextParams(
    bool in_memory,
    const base::FilePath& relative_partition_path,
    network::mojom::NetworkContextParams* network_context_params,
    cert_verifier::mojom::CertVerifierCreationParams*
        cert_verifier_creation_params) {
  if (is_shutting_down_) {
    return;
  }
  ConfigureNetworkContextParamsInternal(in_memory, relative_partition_path,
                                        network_context_params,
                                        cert_verifier_creation_params);

  if ((!in_memory && !profile_->IsOffTheRecord())) {
    // TODO(jam): delete this code 1 year after Network Service shipped to all
    // stable users, which would be after M83 branches.
    base::FilePath base_cache_path;
    chrome::GetUserCacheDirectory(GetPartitionPath(relative_partition_path),
                                  &base_cache_path);
    base::FilePath media_cache_path =
        base_cache_path.Append(chrome::kMediaCacheDirname);
    base::ThreadPool::PostTask(
        FROM_HERE,
        {base::TaskPriority::BEST_EFFORT, base::MayBlock(),
         base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN},
        base::GetDeletePathRecursivelyCallback(media_cache_path));
  }
}

// static
void ProfileNetworkContextService::RegisterProfilePrefs(
    user_prefs::PrefRegistrySyncable* registry) {
  registry->RegisterBooleanPref(embedder_support::kAlternateErrorPagesEnabled,
                                true);
  registry->RegisterBooleanPref(prefs::kQuicAllowed, true);
  registry->RegisterBooleanPref(prefs::kGloballyScopeHTTPAuthCacheEnabled,
                                false);
  registry->RegisterListPref(prefs::kHSTSPolicyBypassList);
  registry->RegisterListPref(prefs::kCACertificates);
  registry->RegisterListPref(prefs::kCACertificatesWithConstraints);
  registry->RegisterListPref(prefs::kCADistrustedCertificates);
  registry->RegisterListPref(prefs::kCAHintCertificates);
#if !BUILDFLAG(IS_CHROMEOS)
  // Include user added platform certs by default.
  registry->RegisterBooleanPref(prefs::kCAPlatformIntegrationEnabled, true);
#endif
#if BUILDFLAG(IS_CHROMEOS)
  net::ServerCertificateDatabaseService::RegisterProfilePrefs(registry);
#endif
}

// static
void ProfileNetworkContextService::RegisterLocalStatePrefs(
    PrefRegistrySimple* registry) {
  registry->RegisterIntegerPref(
      prefs::kAmbientAuthenticationInPrivateModesEnabled,
      static_cast<int>(net::AmbientAuthAllowedProfileTypes::kRegularOnly));

  // For information about whether to reset the HTTP Cache or not, defaults
  // to the empty string, which does not prompt a reset.
  registry->RegisterStringPref(kHttpCacheFinchExperimentGroups, "");
}

void ProfileNetworkContextService::DisableQuicIfNotAllowed() {
  if (!quic_allowed_.IsManaged()) {
    return;
  }

  // If QUIC is allowed, do nothing (re-enabling QUIC is not supported).
  if (quic_allowed_.GetValue()) {
    return;
  }

  g_browser_process->system_network_context_manager()->DisableQuic();
}

void ProfileNetworkContextService::UpdateAcceptLanguage() {
  const std::string accept_language = ComputeAcceptLanguage();
  profile_->ForEachLoadedStoragePartition(
      [&](content::StoragePartition* storage_partition) {
        storage_partition->GetNetworkContext()->SetAcceptLanguage(
            accept_language);
      });
}

void ProfileNetworkContextService::OnThirdPartyCookieBlockingChanged(
    bool block_third_party_cookies) {
  profile_->ForEachLoadedStoragePartition(
      [&](content::StoragePartition* storage_partition) {
        storage_partition->GetCookieManagerForBrowserProcess()
            ->BlockThirdPartyCookies(block_third_party_cookies);
      });
}

void ProfileNetworkContextService::OnMitigationsEnabledFor3pcdChanged(
    bool enable) {
  profile_->ForEachLoadedStoragePartition(
      [&](content::StoragePartition* storage_partition) {
        storage_partition->GetCookieManagerForBrowserProcess()
            ->SetMitigationsEnabledFor3pcd(enable);
      });
}

void ProfileNetworkContextService::OnTrackingProtectionEnabledFor3pcdChanged(
    bool enable) {
  profile_->ForEachLoadedStoragePartition(
      [&](content::StoragePartition* storage_partition) {
        storage_partition->GetCookieManagerForBrowserProcess()
            ->SetTrackingProtectionEnabledFor3pcd(enable);
      });
}

std::string ProfileNetworkContextService::ComputeAcceptLanguage() const {
  // TODO:(https://crbug.com/40224802) Return only single language without
  // expanding the language list if the DisableReduceAcceptLanguage deprecation
  // trial ends.

  if (profile_->IsOffTheRecord()) {
    // In incognito mode return only the first language.
    return ComputeAcceptLanguageFromPref(
        language::GetFirstLanguage(pref_accept_language_.GetValue()));
  }
  return ComputeAcceptLanguageFromPref(pref_accept_language_.GetValue());
}

void ProfileNetworkContextService::UpdateReferrersEnabled() {
  const bool enable_referrers = enable_referrers_.GetValue();
  profile_->ForEachLoadedStoragePartition(
      [&](content::StoragePartition* storage_partition) {
        storage_partition->GetNetworkContext()->SetEnableReferrers(
            enable_referrers);
      });
}

network::mojom::CTPolicyPtr ProfileNetworkContextService::GetCTPolicy() {
  auto* prefs = profile_->GetPrefs();
  const base::Value::List& ct_excluded =
      prefs->GetList(certificate_transparency::prefs::kCTExcludedHosts);
  const base::Value::List& ct_excluded_spkis =
      prefs->GetList(certificate_transparency::prefs::kCTExcludedSPKIs);

  std::vector<std::string> excluded(TranslateStringArray(ct_excluded));
  std::vector<std::string> excluded_spkis(
      TranslateStringArray(ct_excluded_spkis));

  return network::mojom::CTPolicy::New(std::move(excluded),
                                       std::move(excluded_spkis));
}

void ProfileNetworkContextService::UpdateCTPolicy() {
  // TODO(crbug.com/41392053): CT policy needs to be sent to both network
  // service and cert verifier service. Finish refactoring so that it is only
  // sent to cert verifier service.
  std::vector<network::mojom::NetworkContext*> contexts;
  profile_->ForEachLoadedStoragePartition(
      [&](content::StoragePartition* storage_partition) {
        storage_partition->GetNetworkContext()->SetCTPolicy(GetCTPolicy());
        storage_partition->GetCertVerifierServiceUpdater()->SetCTPolicy(
            GetCTPolicy());
      });
}

void ProfileNetworkContextService::ScheduleUpdateCTPolicy() {
  ct_policy_update_timer_.Start(FROM_HERE, base::Seconds(0), this,
                                &ProfileNetworkContextService::UpdateCTPolicy);
}

cert_verifier::mojom::AdditionalCertificatesPtr
ProfileNetworkContextService::GetCertificatePolicy(
    const base::FilePath& storage_partition_path) {
  auto* prefs = profile_->GetPrefs();
  auto additional_certificates =
      cert_verifier::mojom::AdditionalCertificates::New();

#if BUILDFLAG(IS_CHROMEOS)
  const policy::PolicyCertService* policy_cert_service =
      policy::PolicyCertServiceFactory::GetForProfile(profile_);
  if (policy_cert_service) {
    net::CertificateList all_certificates;
    net::CertificateList trust_anchors;
    policy_cert_service->GetPolicyCertificatesForStoragePartition(
        storage_partition_path, &all_certificates, &trust_anchors);

    for (const auto& cert : all_certificates) {
      base::span<const uint8_t> cert_bytes =
          net::x509_util::CryptoBufferAsSpan(cert->cert_buffer());
      additional_certificates->all_certificates.push_back(
          std::vector<uint8_t>(cert_bytes.begin(), cert_bytes.end()));
    }
    for (const auto& cert : trust_anchors) {
      base::span<const uint8_t> cert_bytes =
          net::x509_util::CryptoBufferAsSpan(cert->cert_buffer());
      additional_certificates->trust_anchors.push_back(
          std::vector<uint8_t>(cert_bytes.begin(), cert_bytes.end()));
    }
  }
#endif  // BUILDFLAG(IS_CHROMEOS)

  for (const base::Value& cert_b64 :
       prefs->GetList(prefs::kCAHintCertificates)) {
    std::optional<std::vector<uint8_t>> decoded_opt =
        base::Base64Decode(cert_b64.GetString());

    if (decoded_opt.has_value()) {
      additional_certificates->all_certificates.push_back(
          std::move(*decoded_opt));
    }
  }

  for (const base::Value& cert_b64 : prefs->GetList(prefs::kCACertificates)) {
    if (!cert_b64.is_string()) {
      continue;
    }
    std::optional<std::vector<uint8_t>> decoded_opt =
        base::Base64Decode(cert_b64.GetString());

    if (decoded_opt.has_value()) {
      additional_certificates->trust_anchors_with_enforced_constraints
          .push_back(std::move(*decoded_opt));
    }
  }

  // Add trust anchors with constraints outside the cert
  for (const base::Value& cert_with_constraints :
       prefs->GetList(prefs::kCACertificatesWithConstraints)) {
    const base::Value::Dict* cert_with_constraints_dict =
        cert_with_constraints.GetIfDict();
    if (!cert_with_constraints_dict) {
      continue;
    }

    const std::string* cert_b64 =
        cert_with_constraints_dict->FindString("certificate");
    const base::Value::Dict* constraints_dict =
        cert_with_constraints_dict->FindDict("constraints");
    if (!constraints_dict) {
      continue;
    }
    const base::Value::List* permitted_cidrs =
        constraints_dict->FindList("permitted_cidrs");
    const base::Value::List* permitted_dns_names =
        constraints_dict->FindList("permitted_dns_names");

    // Need to have a cert, and at least one set of restrictions.
    if (!cert_b64) {
      continue;
    }

    if (!((permitted_cidrs && permitted_cidrs->size() > 0) ||
          (permitted_dns_names && permitted_dns_names->size() > 0))) {
      continue;
    }

    std::optional<std::vector<uint8_t>> decoded_cert_opt =
        base::Base64Decode(*cert_b64);
    if (!decoded_cert_opt.has_value()) {
      // Cert isn't valid b64, continue.
      continue;
    }

    bool invalid_constraint = false;
    auto cert_with_constraints_mojo =
        cert_verifier::mojom::CertWithConstraints::New();
    cert_with_constraints_mojo->certificate = std::move(*decoded_cert_opt);
    if (permitted_dns_names) {
      for (const base::Value& dns_name : *permitted_dns_names) {
        if (dns_name.is_string() &&
            IsValidDNSConstraint(dns_name.GetString())) {
          cert_with_constraints_mojo->permitted_dns_names.push_back(
              dns_name.GetString());
        } else {
          invalid_constraint = true;
          break;
        }
      }
    }
    if (invalid_constraint) {
      continue;
    }

    if (permitted_cidrs) {
      for (const base::Value& cidr : *permitted_cidrs) {
        if (!cidr.is_string()) {
          invalid_constraint = true;
          break;
        }
        net::IPAddress parsed_cidr;
        net::IPAddress mask;
        if (ParseCIDRConstraint(cidr.GetString(), &parsed_cidr, &mask)) {
          cert_with_constraints_mojo->permitted_cidrs.push_back(
              cert_verifier::mojom::CIDR::New(/*ip=*/parsed_cidr,
                                              /*mask=*/mask));

        } else {
          invalid_constraint = true;
          break;
        }
      }
    }
    if (invalid_constraint) {
      continue;
    }

    additional_certificates->trust_anchors_with_additional_constraints
        .push_back(std::move(cert_with_constraints_mojo));
  }

  for (const base::Value& cert_b64 :
       prefs->GetList(prefs::kCADistrustedCertificates)) {
    std::string decoded;
    if (!base::Base64Decode(cert_b64.GetString(), &decoded)) {
      continue;
    }
    std::string_view spki_piece;
    bool success = net::asn1::ExtractSPKIFromDERCert(decoded, &spki_piece);
    if (success) {
      additional_certificates->distrusted_spkis.push_back(
          base::ToVector(base::as_byte_span(spki_piece)));
    }
  }

#if !BUILDFLAG(IS_CHROMEOS)
  additional_certificates->include_system_trust_store =
      prefs->GetBoolean(prefs::kCAPlatformIntegrationEnabled);
#endif

  return additional_certificates;
}

void ProfileNetworkContextService::UpdateAdditionalCertificates() {
  CHECK(!is_shutting_down_);

#if BUILDFLAG(CHROME_ROOT_STORE_CERT_MANAGEMENT_UI)
  if (base::FeatureList::IsEnabled(features::kEnableCertManagementUIV2Write)) {
    net::ServerCertificateDatabaseService* cert_db_service =
        net::ServerCertificateDatabaseServiceFactory::GetForBrowserContext(
            profile_);
    // The service can be null for AshInternals profiles. If it's null, fall
    // through to updating the additional certs without it.
    if (cert_db_service) {
      cert_db_service->GetAllCertificates(
          base::BindOnce(&ProfileNetworkContextService::
                             UpdateAdditionalCertificatesWithUserAddedCerts,
                         weak_factory_.GetWeakPtr()));
      return;
    }
  }
#endif
  profile_->ForEachLoadedStoragePartition(
      [&](content::StoragePartition* storage_partition) {
        storage_partition->GetCertVerifierServiceUpdater()
            ->UpdateAdditionalCertificates(
                GetCertificatePolicy(storage_partition->GetPath()));
      });
}

#if BUILDFLAG(CHROME_ROOT_STORE_CERT_MANAGEMENT_UI)
void ProfileNetworkContextService::
    UpdateAdditionalCertificatesWithUserAddedCerts(
        std::vector<net::ServerCertificateDatabase::CertInformation>
            cert_infos) {
  profile_->ForEachLoadedStoragePartition([&](content::StoragePartition*
                                                  storage_partition) {
    cert_verifier::mojom::AdditionalCertificatesPtr additional_certs =
        GetCertificatePolicy(storage_partition->GetPath());

    for (const auto& cert_info : cert_infos) {
      std::optional<bssl::CertificateTrustType> trust =
          net::ServerCertificateDatabase::GetUserCertificateTrust(cert_info);
      if (!trust) {
        continue;
      }
      switch (trust.value()) {
        case bssl::CertificateTrustType::UNSPECIFIED:
          additional_certs->all_certificates.push_back(cert_info.der_cert);
          break;

        case bssl::CertificateTrustType::DISTRUSTED: {
          std::string_view spki_piece;
          bool success = net::asn1::ExtractSPKIFromDERCert(
              base::as_string_view(cert_info.der_cert), &spki_piece);
          if (success) {
            additional_certs->distrusted_spkis.push_back(
                base::ToVector(base::as_byte_span(spki_piece)));
          }
          break;
        }

        case bssl::CertificateTrustType::TRUSTED_ANCHOR:
          if (!cert_info.cert_metadata.has_constraints() ||
              (cert_info.cert_metadata.constraints().dns_names_size() == 0 &&
               cert_info.cert_metadata.constraints().cidrs_size() == 0)) {
            additional_certs->trust_anchors_with_enforced_constraints.push_back(
                cert_info.der_cert);
          } else {
            MaybeAddCertWithConstraints(
                cert_info,
                &additional_certs->trust_anchors_with_additional_constraints);
          }
          break;

        case bssl::CertificateTrustType::TRUSTED_ANCHOR_OR_LEAF:
          MaybeAddCertWithConstraints(
              cert_info, &additional_certs->trust_anchors_and_leafs);
          break;
        case bssl::CertificateTrustType::TRUSTED_LEAF:
          MaybeAddCertWithConstraints(cert_info,
                                      &additional_certs->trust_leafs);
          break;
      }
    }
    storage_partition->GetCertVerifierServiceUpdater()
        ->UpdateAdditionalCertificates(std::move(additional_certs));
  });
}
#endif  // BUILDFLAG(CHROME_ROOT_STORE_CERT_MANAGEMENT_UI)

void ProfileNetworkContextService::ScheduleUpdateCertificatePolicy() {
  cert_policy_update_timer_.Start(
      FROM_HERE, base::Seconds(0), this,
      &ProfileNetworkContextService::UpdateAdditionalCertificates);
}

ProfileNetworkContextService::CertificatePoliciesForView::
    CertificatePoliciesForView() = default;
ProfileNetworkContextService::CertificatePoliciesForView::
    ~CertificatePoliciesForView() = default;

ProfileNetworkContextService::CertificatePoliciesForView::
    CertificatePoliciesForView(CertificatePoliciesForView&&) = default;
ProfileNetworkContextService::CertificatePoliciesForView&
ProfileNetworkContextService::CertificatePoliciesForView::operator=(
    CertificatePoliciesForView&& other) = default;

ProfileNetworkContextService::CertificatePoliciesForView
ProfileNetworkContextService::GetCertificatePolicyForView() {
  // This method is called by the certificate manager WebUI, which should be
  // destroyed before this service begins shutting down (and therefore can't
  // call this method after shutdown has started).
  CHECK(!is_shutting_down_);
  CertificatePoliciesForView policies;
  policies.certificate_policies =
      GetCertificatePolicy(profile_->GetDefaultStoragePartition()->GetPath());

  auto* prefs = profile_->GetPrefs();
  for (const base::Value& cert_b64 :
       prefs->GetList(prefs::kCADistrustedCertificates)) {
    std::optional<std::vector<uint8_t>> decoded_opt =
        base::Base64Decode(cert_b64.GetString());

    if (decoded_opt.has_value()) {
      policies.full_distrusted_certs.push_back(std::move(*decoded_opt));
    }
  }

#if !BUILDFLAG(IS_CHROMEOS)
  policies.is_include_system_trust_store_managed =
      prefs->FindPreference(prefs::kCAPlatformIntegrationEnabled)->IsManaged();
#endif
  return policies;
}

bool ProfileNetworkContextService::ShouldSplitAuthCacheByNetworkIsolationKey()
    const {
  if (profile_->GetPrefs()->GetBoolean(
          prefs::kGloballyScopeHTTPAuthCacheEnabled)) {
    return false;
  }
  return base::FeatureList::IsEnabled(
      network::features::kSplitAuthCacheByNetworkIsolationKey);
}

void ProfileNetworkContextService::UpdateSplitAuthCacheByNetworkIsolationKey() {
  const bool split_auth_cache_by_network_isolation_key =
      ShouldSplitAuthCacheByNetworkIsolationKey();

  profile_->ForEachLoadedStoragePartition(
      [&](content::StoragePartition* storage_partition) {
        storage_partition->GetNetworkContext()
            ->SetSplitAuthCacheByNetworkAnonymizationKey(
                split_auth_cache_by_network_isolation_key);
      });
}

void ProfileNetworkContextService::
    UpdateCorsNonWildcardRequestHeadersSupport() {
  const bool value = profile_->GetPrefs()->GetBoolean(
      prefs::kCorsNonWildcardRequestHeadersSupport);

  profile_->ForEachLoadedStoragePartition(
      [&](content::StoragePartition* storage_partition) {
        storage_partition->GetNetworkContext()
            ->SetCorsNonWildcardRequestHeadersSupport(value);
      });
}

#if BUILDFLAG(ENABLE_REPORTING)
base::flat_map<std::string, GURL>
ProfileNetworkContextService::GetEnterpriseReportingEndpoints() const {
  using FlatMap = base::flat_map<std::string, GURL>;
  // Create the underlying container first to allow sorting to
  // be done in a single pass.
  FlatMap::container_type pairs;
  const base::Value::Dict& pref_dict =
      profile_->GetPrefs()->GetDict(prefs::kReportingEndpoints);
  pairs.reserve(pref_dict.size());
  // The iterator for base::Value::Dict returns a temporary value when
  // dereferenced, so a const reference is not used below.
  for (const auto [endpoint_name, endpoint_url] : pref_dict) {
    GURL endpoint(endpoint_url.GetString());
    if (endpoint.is_valid() && endpoint.SchemeIsCryptographic()) {
      pairs.emplace_back(endpoint_name, std::move(endpoint));
    }
  }
  return FlatMap(std::move(pairs));
}

void ProfileNetworkContextService::UpdateEnterpriseReportingEndpoints() {
  base::flat_map<std::string, GURL> endpoints =
      GetEnterpriseReportingEndpoints();
  profile_->ForEachLoadedStoragePartition(
      [&](content::StoragePartition* storage_partition) {
        storage_partition->GetNetworkContext()->SetEnterpriseReportingEndpoints(
            endpoints);
      });
}
#endif

// static
network::mojom::CookieManagerParamsPtr
ProfileNetworkContextService::CreateCookieManagerParams(
    Profile* profile,
    const content_settings::CookieSettings& cookie_settings) {
  auto out = network::mojom::CookieManagerParams::New();
  out->block_third_party_cookies =
      cookie_settings.ShouldBlockThirdPartyCookies();
  // This allows cookies to be sent on https requests from chrome:// pages,
  // ignoring SameSite attribute rules. For example, this is needed for browser
  // UI to interact with SameSite cookies on accounts.google.com, which is used
  // for displaying a list of available accounts on the NTP
  // (chrome://new-tab-page), etc.
  out->secure_origin_cookies_allowed_schemes.push_back(
      content::kChromeUIScheme);
#if BUILDFLAG(ENABLE_EXTENSIONS)
  // TODO(chlily): To be consistent with the content_settings version of
  // CookieSettings, we should probably also add kExtensionScheme to the list of
  // matching_scheme_cookies_allowed_schemes.
  out->third_party_cookies_allowed_schemes.push_back(
      extensions::kExtensionScheme);
  out->third_party_cookies_allowed_schemes.push_back(
      content::kChromeDevToolsScheme);
#endif

  HostContentSettingsMap* host_content_settings_map =
      HostContentSettingsMapFactory::GetForProfile(profile);
  for (auto type :
       content_settings::CookieSettings::GetContentSettingsTypes()) {
    if (!IsContentSettingsTypeEnabled(type)) {
      continue;
    }
    if (type == ContentSettingsType::FEDERATED_IDENTITY_SHARING) {
      if (FederatedIdentityPermissionContext* fedcm_context =
              FederatedIdentityPermissionContextFactory::GetForProfile(profile);
          fedcm_context) {
        out->content_settings[type] =
            fedcm_context->GetSharingPermissionGrantsAsContentSettings();
      } else {
        out->content_settings[type] = ContentSettingsForOneType();
      }
    } else {
      out->content_settings[type] =
          host_content_settings_map->GetSettingsForOneType(type);
    }
  }

  out->cookie_access_delegate_type =
      network::mojom::CookieAccessDelegateType::USE_CONTENT_SETTINGS;

  out->mitigations_enabled_for_3pcd =
      cookie_settings.MitigationsEnabledFor3pcd();

  out->tracking_protection_enabled_for_3pcd =
      TrackingProtectionSettingsFactory::GetForProfile(profile)
          ->IsTrackingProtection3pcdEnabled();

  return out;
}

void ProfileNetworkContextService::FlushCachedClientCertIfNeeded(
    const net::HostPortPair& host,
    const scoped_refptr<net::X509Certificate>& certificate) {
  if (is_shutting_down_) {
    return;
  }
  profile_->ForEachLoadedStoragePartition(
      [&](content::StoragePartition* storage_partition) {
        storage_partition->GetNetworkContext()->FlushCachedClientCertIfNeeded(
            host, certificate);
      });
}

void ProfileNetworkContextService::FlushProxyConfigMonitorForTesting() {
  proxy_config_monitor_->FlushForTesting();  // IN-TEST
}

void ProfileNetworkContextService::SetDiscardDomainReliabilityUploadsForTesting(
    bool value) {
  g_discard_domain_reliability_uploads_for_testing = new bool(value);
}

#if BUILDFLAG(IS_CHROMEOS)
void ProfileNetworkContextService::CreateClientCertIssuerSourcesWithDBCerts(
    net::ClientCertIssuerSourceGetterCallback callback,
    std::vector<net::ServerCertificateDatabase::CertInformation>
        db_cert_infos) {
  cert_verifier::mojom::AdditionalCertificatesPtr policy_certs =
      GetCertificatePolicy(profile_->GetDefaultStoragePartition()->GetPath());

  std::vector<bssl::UniquePtr<CRYPTO_BUFFER>> certs;
  for (const auto& cert : policy_certs->all_certificates) {
    certs.push_back(net::x509_util::CreateCryptoBuffer(cert));
  }
  for (const auto& cert : db_cert_infos) {
    certs.push_back(net::x509_util::CreateCryptoBuffer(cert.der_cert));
  }
  net::ClientCertIssuerSourceCollection sources;
  if (!certs.empty()) {
    sources.push_back(std::make_unique<net::ClientCertIssuerSourceInMemory>(
        std::move(certs)));
  }

  // Intermediates from NSS are used unconditionally. There are 2 reasons why
  // the NSS source is used:
  // 1) If the ServerCertificateDatabase feature is not enabled
  // (kEnableCertManagementUIV2Write is false), user-added intermediates
  // still come from NSS, so checking NSS is required.
  // 2) Device-wide ONC intermediate certificates may be needed as well. It's
  // unclear if the use of device-wide policy in non-signin-profile client cert
  // verification was intended or just an accidental side effect of NSS state
  // being global, but enterprises might be depending on it (at least one
  // browser_test depends on it:
  // SuccessViaCaAndIntermediate/SigninFrameWebviewClientCertsLoginTest.LockscreenTest/0).
  // TODO(https://crbug.com/40554868): once kEnableCertManagementUIV2Write has
  // fully launched, consider removing the NSS source and making this read from
  // the device ONC policy directly (or decide if using the device ONC policy
  // here is not intended and change the test to not do that).
  sources.push_back(
      std::make_unique<net::ClientCertStoreNSS::IssuerSourceNSS>());

  std::move(callback).Run(std::move(sources));
}

void ProfileNetworkContextService::CreateClientCertIssuerSources(
    net::ClientCertIssuerSourceGetterCallback callback) {
  if (base::FeatureList::IsEnabled(features::kEnableCertManagementUIV2Write)) {
    net::ServerCertificateDatabaseService* cert_db_service =
        net::ServerCertificateDatabaseServiceFactory::GetForBrowserContext(
            profile_);
    // The service can be null for AshInternals profiles. If it's null fall
    // through to creating the ClientCertIssuerSource without it.
    if (cert_db_service) {
      cert_db_service->GetAllCertificates(
          base::BindOnce(&ProfileNetworkContextService::
                             CreateClientCertIssuerSourcesWithDBCerts,
                         weak_factory_.GetWeakPtr(), std::move(callback)));
      return;
    }
  }

  CreateClientCertIssuerSourcesWithDBCerts(std::move(callback),
                                           /*db_cert_infos=*/{});
}

net::ClientCertIssuerSourceGetter
ProfileNetworkContextService::GetClientCertIssuerSourceFactory() {
  return base::BindOnce(
      &ProfileNetworkContextService::CreateClientCertIssuerSources,
      weak_factory_.GetWeakPtr());
}
#endif

std::unique_ptr<net::ClientCertStore>
ProfileNetworkContextService::CreateClientCertStore() {
  if (is_shutting_down_) {
    return nullptr;
  }
  if (!client_cert_store_factory_for_testing_.is_null()) {
    return client_cert_store_factory_for_testing_.Run();
  }

#if BUILDFLAG(IS_CHROMEOS)
  chromeos::CertificateProviderService* cert_provider_service =
      chromeos::CertificateProviderServiceFactory::GetForBrowserContext(
          profile_);
  std::unique_ptr<chromeos::CertificateProvider> certificate_provider;
  if (cert_provider_service) {
    certificate_provider = cert_provider_service->CreateCertificateProvider();
  }
#endif

#if BUILDFLAG(IS_CHROMEOS)
  bool use_system_key_slot = false;
  // Enable client certificates for the Chrome OS sign-in frame, if this feature
  // is not disabled by a flag.
  // Note that while this applies to the whole sign-in profile / lock screen
  // profile, client certificates will only be selected for the StoragePartition
  // currently used in the sign-in frame (see SigninPartitionManager).
  if (ash::ProfileHelper::IsSigninProfile(profile_) ||
      ash::ProfileHelper::IsLockScreenProfile(profile_)) {
    use_system_key_slot = true;
  }

  if (ash::features::ShouldUseKcerClientCertStore()) {
    return std::make_unique<ash::ClientCertStoreKcer>(
        std::move(certificate_provider),
        kcer::KcerFactoryAsh::GetKcer(profile_),
        GetClientCertIssuerSourceFactory());
  } else {
    std::string username_hash;
    const user_manager::User* user =
        ash::ProfileHelper::Get()->GetUserByProfile(profile_);
    if (user && !user->username_hash().empty()) {
      username_hash = user->username_hash();

      // Use the device-wide system key slot only if the user is affiliated on
      // the device.
      if (user->IsAffiliated()) {
        use_system_key_slot = true;
      }
    }

    return std::make_unique<ash::ClientCertStoreAsh>(
        std::move(certificate_provider), use_system_key_slot, username_hash,
        base::BindRepeating(&CreateCryptoModuleBlockingPasswordDelegate,
                            kCryptoModulePasswordClientAuth));
  }

#elif BUILDFLAG(USE_NSS_CERTS)
  std::unique_ptr<net::ClientCertStore> store =
      std::make_unique<net::ClientCertStoreNSS>(
          base::BindRepeating(&CreateCryptoModuleBlockingPasswordDelegate,
                              kCryptoModulePasswordClientAuth));
#if BUILDFLAG(IS_LINUX)
  return GetWrappedCertStore(profile_, std::move(store));
#else
  return store;
#endif  // BUILDFLAG(IS_LINUX)
#elif BUILDFLAG(IS_WIN)
  return GetWrappedCertStore(profile_,
                             std::make_unique<net::ClientCertStoreWin>());
#elif BUILDFLAG(IS_MAC)
  return GetWrappedCertStore(profile_,
                             std::make_unique<net::ClientCertStoreMac>());
#elif BUILDFLAG(IS_ANDROID)
  // Android does not use the ClientCertStore infrastructure. On Android client
  // cert matching is done by the OS as part of the call to show the cert
  // selection dialog.
  return nullptr;
#else
#error Unknown platform.
#endif
}

bool GetHttpCacheBackendResetParam(PrefService* local_state) {
  // Get the field trial groups.  If the server cannot be reached, then
  // this corresponds to "None" for each experiment.
  base::FieldTrial* field_trial = base::FeatureList::GetFieldTrial(
      net::features::kSplitCacheByNetworkIsolationKey);
  std::string current_field_trial_status =
      (field_trial ? field_trial->group_name() : "None");
  // This used to be used for keying on main frame only vs main frame +
  // innermost frame, but the feature was removed, and now it's always keyed on
  // both.
  current_field_trial_status += " None";
  // This used to be for keying on scheme + eTLD+1 vs origin, but the trial was
  // removed, and now it's always keyed on eTLD+1. Still keeping a third "None"
  // to avoid resetting the disk cache.
  current_field_trial_status += " None ";

  field_trial = base::FeatureList::GetFieldTrial(
      net::features::kSplitCacheByIncludeCredentials);
  current_field_trial_status +=
      (field_trial ? field_trial->group_name() : "None");

  if (disk_cache::InBackendExperiment()) {
    if (disk_cache::InSimpleBackendExperimentGroup()) {
      current_field_trial_status += " 20241007-DiskCache-Simple";
    } else {
      current_field_trial_status += " 20241007-DiskCache-Blockfile";
    }
  }

  std::string previous_field_trial_status =
      local_state->GetString(kHttpCacheFinchExperimentGroups);
  local_state->SetString(kHttpCacheFinchExperimentGroups,
                         current_field_trial_status);

  return !previous_field_trial_status.empty() &&
         current_field_trial_status != previous_field_trial_status;
}

void ProfileNetworkContextService::ConfigureNetworkContextParamsInternal(
    bool in_memory,
    const base::FilePath& relative_partition_path,
    network::mojom::NetworkContextParams* network_context_params,
    cert_verifier::mojom::CertVerifierCreationParams*
        cert_verifier_creation_params) {
  TRACE_EVENT0(
      "startup",
      "ProfileNetworkContextService::ConfigureNetworkContextParamsInternal");
  if (profile_->IsOffTheRecord()) {
    in_memory = true;
  }
  base::FilePath path(GetPartitionPath(relative_partition_path));

  g_browser_process->system_network_context_manager()
      ->ConfigureDefaultNetworkContextParams(network_context_params);

  network_context_params->enable_zstd = true;
  network_context_params->accept_language = ComputeAcceptLanguage();
  network_context_params->enable_referrers = enable_referrers_.GetValue();

  base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
  if (command_line->HasSwitch(embedder_support::kShortReportingDelay)) {
    network_context_params->reporting_delivery_interval =
        base::Milliseconds(100);
  }

  // Always enable the HTTP cache.
  network_context_params->http_cache_enabled = true;

  network_context_params->http_auth_static_network_context_params =
      network::mojom::HttpAuthStaticNetworkContextParams::New();

  if (IsAmbientAuthAllowedForProfile(profile_)) {
    network_context_params->http_auth_static_network_context_params
        ->allow_default_credentials =
        net::HttpAuthPreferences::ALLOW_DEFAULT_CREDENTIALS;
  } else {
    network_context_params->http_auth_static_network_context_params
        ->allow_default_credentials =
        net::HttpAuthPreferences::DISALLOW_DEFAULT_CREDENTIALS;
  }

  network_context_params->cookie_manager_params =
      CreateCookieManagerParams(profile_, *cookie_settings_);

  // Configure on-disk storage for non-OTR profiles. OTR profiles just use
  // default behavior (in memory storage, default sizes).
  if (!in_memory) {
    PrefService* local_state = g_browser_process->local_state();
    // Configure the HTTP cache path and size.
    base::FilePath base_cache_path;
    chrome::GetUserCacheDirectory(path, &base_cache_path);
    base::FilePath disk_cache_dir =
        local_state->GetFilePath(prefs::kDiskCacheDir);
    if (!disk_cache_dir.empty()) {
      base_cache_path = disk_cache_dir.Append(base_cache_path.BaseName());
    }
    const int disk_cache_size = local_state->GetInteger(prefs::kDiskCacheSize);
    network_context_params->http_cache_max_size = disk_cache_size;
    network_context_params->shared_dictionary_cache_max_size = disk_cache_size;

    network_context_params->file_paths =
        ::network::mojom::NetworkContextFilePaths::New();

    network_context_params->file_paths->http_cache_directory =
        base_cache_path.Append(chrome::kCacheDirname);
    network_context_params->file_paths->data_directory =
        path.Append(chrome::kNetworkDataDirname);
    network_context_params->file_paths->unsandboxed_data_path = path;
    network_context_params->file_paths->trigger_migration =
        base::FeatureList::IsEnabled(features::kTriggerNetworkDataMigration);

    // Currently this just contains HttpServerProperties, but that will likely
    // change.
    network_context_params->file_paths->http_server_properties_file_name =
        base::FilePath(chrome::kNetworkPersistentStateFilename);
    network_context_params->file_paths->cookie_database_name =
        base::FilePath(chrome::kCookieFilename);

    g_browser_process->system_network_context_manager()
        ->AddCookieEncryptionManagerToNetworkContextParams(
            network_context_params);

    network_context_params->file_paths->trust_token_database_name =
        base::FilePath(chrome::kTrustTokenFilename);

#if BUILDFLAG(ENABLE_REPORTING)
    network_context_params->file_paths->reporting_and_nel_store_database_name =
        base::FilePath(chrome::kReportingAndNelStoreFilename);

    if (base::FeatureList::IsEnabled(
            net::features::kReportingApiEnableEnterpriseCookieIssues)) {
      network_context_params->enterprise_reporting_endpoints =
          GetEnterpriseReportingEndpoints();
    }
#endif  // BUILDFLAG(ENABLE_REPORTING)

    if (relative_partition_path.empty()) {  // This is the main partition.
      network_context_params->restore_old_session_cookies =
          profile_->ShouldRestoreOldSessionCookies();
      network_context_params->persist_session_cookies =
          profile_->ShouldPersistSessionCookies();
    } else {
      // Copy behavior of ProfileImplIOData::InitializeAppRequestContext.
      network_context_params->restore_old_session_cookies = false;
      network_context_params->persist_session_cookies = false;
    }

    network_context_params->file_paths->transport_security_persister_file_name =
        base::FilePath(chrome::kTransportSecurityPersisterFilename);
    network_context_params->file_paths->sct_auditing_pending_reports_file_name =
        base::FilePath(chrome::kSCTAuditingPendingReportsFileName);
    network_context_params->file_paths->device_bound_sessions_database_name =
        base::FilePath(chrome::kDeviceBoundSessionsFilename);
  }
  const base::Value::List& hsts_policy_bypass_list =
      profile_->GetPrefs()->GetList(prefs::kHSTSPolicyBypassList);
  for (const auto& value : hsts_policy_bypass_list) {
    const std::string* string_value = value.GetIfString();
    if (!string_value) {
      continue;
    }
    network_context_params->hsts_policy_bypass_list.push_back(*string_value);
  }

  proxy_config_monitor_->AddToNetworkContextParams(network_context_params);

  network_context_params->enable_certificate_reporting = true;

  SCTReportingService* sct_reporting_service =
      SCTReportingServiceFactory::GetForBrowserContext(profile_);
  if (sct_reporting_service) {
    network_context_params->sct_auditing_mode =
        sct_reporting_service->GetReportingMode();
  } else {
    network_context_params->sct_auditing_mode =
        network::mojom::SCTAuditingMode::kDisabled;
  }

  network_context_params->ct_policy = GetCTPolicy();
  cert_verifier_creation_params->ct_policy = GetCTPolicy();

  if (domain_reliability::ShouldCreateService()) {
    network_context_params->enable_domain_reliability = true;
    network_context_params->domain_reliability_upload_reporter =
        domain_reliability::kUploadReporterString;
    network_context_params->discard_domain_reliablity_uploads =
        g_discard_domain_reliability_uploads_for_testing
            ? *g_discard_domain_reliability_uploads_for_testing
            : !g_browser_process->local_state()->GetBoolean(
                  metrics::prefs::kMetricsReportingEnabled);
  }

#if BUILDFLAG(IS_CHROMEOS)
  bool profile_supports_policy_certs = false;
  if (ash::ProfileHelper::IsSigninProfile(profile_) ||
      ash::ProfileHelper::IsLockScreenProfile(profile_)) {
    profile_supports_policy_certs = true;
  }
  user_manager::UserManager* user_manager = user_manager::UserManager::Get();
  if (user_manager) {
    const user_manager::User* user =
        ash::ProfileHelper::Get()->GetUserByProfile(profile_);
    if (user && !user->username_hash().empty()) {
      profile_supports_policy_certs = true;
    }
  }
  if (profile_supports_policy_certs) {
    auto* policy_cert_service =
        policy::PolicyCertServiceFactory::GetForProfile(profile_);

    // Note: in the case of Network Service restarts, we assume that
    // `profile_supports_policy_certs` will be calculated the same way on
    // subsequent NetworkContext creations as it was on the first one.
    // Using `base::Unretained(this)` here is safe because we call
    // `StopObservingCertChanges()` in `Shutdown()` which clears the callback.
    if (policy_cert_service && !policy_cert_service->IsObservingCertChanges()) {
      policy_cert_service->StartObservingCertChanges(base::BindRepeating(
          &ProfileNetworkContextService::UpdateAdditionalCertificates,
          base::Unretained(this)));
    }
  }
#endif

  // TODO(crbug.com/40928765): check to see if IsManaged() ensures the pref
  // isn't set in user profiles, or if that does something else. If that's true,
  // add an isManaged() check here.

#if BUILDFLAG(CHROME_ROOT_STORE_CERT_MANAGEMENT_UI)
  if (base::FeatureList::IsEnabled(features::kEnableCertManagementUIV2Write) &&
      net::ServerCertificateDatabaseServiceFactory::GetForBrowserContext(
          profile_)) {
    cert_verifier_creation_params->wait_for_update = true;
    UpdateAdditionalCertificates();
  } else {
    cert_verifier_creation_params->initial_additional_certificates =
        GetCertificatePolicy(GetPartitionPath(relative_partition_path));
  }
#else
  cert_verifier_creation_params->initial_additional_certificates =
      GetCertificatePolicy(GetPartitionPath(relative_partition_path));
#endif  // BUILDFLAG(CHROME_ROOT_STORE_CERT_MANAGEMENT_UI)

#if BUILDFLAG(IS_CHROMEOS)
  // Disable idle sockets close on memory pressure if configured by finch or
  // about://flags.
  if (base::FeatureList::IsEnabled(
          chromeos::features::kDisableIdleSocketsCloseOnMemoryPressure)) {
    network_context_params->disable_idle_sockets_close_on_memory_pressure =
        true;
  }
#endif

  network_context_params->reset_http_cache_backend =
      GetHttpCacheBackendResetParam(g_browser_process->local_state());

  network_context_params->split_auth_cache_by_network_anonymization_key =
      ShouldSplitAuthCacheByNetworkIsolationKey();

  // All consumers of the main NetworkContext must provide
  // NetworkAnonymizationKeys / IsolationInfos, so storage can be isolated on a
  // per-site basis.
  network_context_params->require_network_anonymization_key = true;

  ContentSetting anti_abuse_content_setting =
      HostContentSettingsMapFactory::GetForProfile(profile_)
          ->GetDefaultContentSetting(ContentSettingsType::ANTI_ABUSE, nullptr);
  network_context_params->block_trust_tokens =
      anti_abuse_content_setting == CONTENT_SETTING_BLOCK;

  network_context_params->first_party_sets_access_delegate_params =
      network::mojom::FirstPartySetsAccessDelegateParams::New();
  network_context_params->first_party_sets_access_delegate_params->enabled =
      PrivacySandboxSettingsFactory::GetForProfile(profile_)
          ->AreRelatedWebsiteSetsEnabled();

  mojo::Remote<network::mojom::FirstPartySetsAccessDelegate>
      fps_access_delegate_remote;
  network_context_params->first_party_sets_access_delegate_receiver =
      fps_access_delegate_remote.BindNewPipeAndPassReceiver();

  first_party_sets::FirstPartySetsPolicyService* fps_service =
      first_party_sets::FirstPartySetsPolicyServiceFactory::
          GetForBrowserContext(profile_);
  DCHECK(fps_service);
  fps_service->AddRemoteAccessDelegate(std::move(fps_access_delegate_remote));

  network_context_params->acam_preflight_spec_conformant =
      profile_->GetPrefs()->GetBoolean(
          prefs::kAccessControlAllowMethodsInCORSPreflightSpecConformant);

  IpProtectionCoreHost* ipp_core_host =
      IpProtectionCoreHostFactory::GetForProfile(profile_);
  if (NeedsIpProtection(ipp_core_host, *profile_)) {
    ipp_core_host->AddNetworkService(
        network_context_params->ip_protection_core_host
            .InitWithNewPipeAndPassReceiver(),
        network_context_params->ip_protection_control
            .InitWithNewPipeAndPassRemote());
    network_context_params->enable_ip_protection =
        ipp_core_host->IsIpProtectionEnabled();
    network_context_params->ip_protection_incognito =
        profile_->IsIncognitoProfile();
    if (base::CommandLine::ForCurrentProcess()->HasSwitch(
            network::switches::kStoreProbabilisticRevealTokens)) {
      network_context_params->ip_protection_data_directory =
          profile_->GetPath();
    }
  }

  network_context_params->device_bound_sessions_enabled =
      base::FeatureList::IsEnabled(net::features::kDeviceBoundSessions);
}

base::FilePath ProfileNetworkContextService::GetPartitionPath(
    const base::FilePath& relative_partition_path) {
  base::FilePath path = profile_->GetPath();
  if (!relative_partition_path.empty()) {
    path = path.Append(relative_partition_path);
  }
  return path;
}

void ProfileNetworkContextService::OnContentSettingChanged(
    const ContentSettingsPattern& primary_pattern,
    const ContentSettingsPattern& secondary_pattern,
    ContentSettingsType content_type) {
  switch (content_type) {
    case ContentSettingsType::ANTI_ABUSE:
      UpdateAntiAbuseSettings(profile_);
      break;
    case ContentSettingsType::TRACKING_PROTECTION:
      UpdateTrackingProtectionSettings(profile_);
      break;
    case ContentSettingsType::DEFAULT:
      UpdateAntiAbuseSettings(profile_);
      for (auto type :
           content_settings::CookieSettings::GetContentSettingsTypes()) {
        UpdateCookieSettings(profile_, type);
      }
      break;
    default:
      if (content_settings::CookieSettings::GetContentSettingsTypes().contains(
              content_type)) {
        UpdateCookieSettings(profile_, content_type);
        return;
      }
      return;
  }
}

void ProfileNetworkContextService::Shutdown() {
  is_shutting_down_ = true;

#if BUILDFLAG(CHROME_ROOT_STORE_CERT_MANAGEMENT_UI)
  server_cert_database_observer_ = {};
#endif

  cert_policy_update_timer_.Stop();
  ct_policy_update_timer_.Stop();

  HostContentSettingsMapFactory::GetForProfile(profile_)->RemoveObserver(this);
  cookie_settings_observation_.Reset();
  cookie_settings_ = nullptr;

#if BUILDFLAG(IS_CHROMEOS)
  policy::PolicyCertService* policy_cert_service =
      policy::PolicyCertServiceFactory::GetForProfile(profile_);

  if (policy_cert_service && policy_cert_service->IsObservingCertChanges()) {
    policy_cert_service->StopObservingCertChanges();
  }
#endif

  pref_change_registrar_.RemoveAll();
  enable_referrers_.Destroy();
  pref_accept_language_.Destroy();
  quic_allowed_.Destroy();

  proxy_config_monitor_ = nullptr;

  profile_ = nullptr;
}