summaryrefslogtreecommitdiff
path: root/libre/iceweasel/9001-FSDG-sync-remote-settings-with-local-dump.patch
blob: c46d90f51edcec4e78791fb830cb773f62b77f9e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
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
From bec8749011d7dba665eace92557f9d36b36c3060 Mon Sep 17 00:00:00 2001
From: grizzlyuser <grizzlyuser@protonmail.com>
Date: Wed, 30 Dec 2020 17:20:39 +0200
Subject: [PATCH 01/13] Point to local omni.ja files, not remote server

This patch series tries to remove any network communication with Remote
Settings [1], which can be used by Mozilla to silently push data to client
browsers. This data can include references to nonfree software, for example,
to search engines or other websites that contain nonfree JavaScript code.
Without this patching, it would be hard to make sure the browser does not
violate paragraph 4 of [2]: "Programs in the system should not suggest
installing nonfree plugins, documentation, and so on."

Changes in the current patch:
First of all, replace every occurrence of Remote Settings server domain name
with URIs that point to built-in local files within omni.ja.

Some links to json files may point to non-existing files, but that's OK
because it's better than leave them point to Remote Settings server.
If necessary, missing files can be added later.

[1] https://remote-settings.readthedocs.io/en/latest/introduction.html
[2] https://www.gnu.org/distros/free-system-distribution-guidelines.en.html#license-rules
---
 .../components/ASRouterAdmin/ASRouterAdmin.jsx            | 2 +-
 .../newtab/data/content/activity-stream.bundle.js         | 2 +-
 modules/libpref/init/all.js                               | 2 +-
 services/settings/Utils.jsm                               | 4 ++--
 .../periodic-updates/scripts/periodic_file_updates.sh     | 2 +-
 toolkit/components/search/SearchUtils.jsm                 | 8 ++++----
 toolkit/components/search/docs/DefaultSearchEngines.rst   | 2 +-
 .../components/search/docs/SearchEngineConfiguration.rst  | 2 +-
 toolkit/mozapps/defaultagent/RemoteSettings.cpp           | 2 +-
 9 files changed, 13 insertions(+), 13 deletions(-)

diff --git a/browser/components/newtab/content-src/components/ASRouterAdmin/ASRouterAdmin.jsx b/browser/components/newtab/content-src/components/ASRouterAdmin/ASRouterAdmin.jsx
index 0a9da8d804..fdc387aa63 100644
--- a/browser/components/newtab/content-src/components/ASRouterAdmin/ASRouterAdmin.jsx
+++ b/browser/components/newtab/content-src/components/ASRouterAdmin/ASRouterAdmin.jsx
@@ -1226,7 +1226,7 @@ export class ASRouterAdminInner extends React.PureComponent {
                   <a
                     className="providerUrl"
                     target="_blank"
-                    href="https://firefox.settings.services.mozilla.com/v1/buckets/main/collections/nimbus-desktop-experiments/records"
+                    href="resource://app/defaults/settings/main/nimbus-desktop-experiments.json"
                     rel="noopener noreferrer"
                   >
                     nimbus-desktop-experiments
diff --git a/browser/components/newtab/data/content/activity-stream.bundle.js b/browser/components/newtab/data/content/activity-stream.bundle.js
index 6e7cc5e33d..f2b4f3fcc9 100644
--- a/browser/components/newtab/data/content/activity-stream.bundle.js
+++ b/browser/components/newtab/data/content/activity-stream.bundle.js
@@ -1819,7 +1819,7 @@ class ASRouterAdminInner extends react__WEBPACK_IMPORTED_MODULE_3___default.a.Pu
         label = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("span", null, "remote settings (", /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("a", {
           className: "providerUrl",
           target: "_blank",
-          href: "https://firefox.settings.services.mozilla.com/v1/buckets/main/collections/nimbus-desktop-experiments/records",
+          href: "resource://app/defaults/settings/main/nimbus-desktop-experiments.json",
           rel: "noopener noreferrer"
         }, "nimbus-desktop-experiments"), ")");
       }
diff --git a/modules/libpref/init/all.js b/modules/libpref/init/all.js
index 651d38c0e2..cb72224e1b 100644
--- a/modules/libpref/init/all.js
+++ b/modules/libpref/init/all.js
@@ -2198,7 +2198,7 @@ pref("security.insecure_field_warning.ignore_local_ip_address", true);
 // Remote settings preferences
 // Note: if you change this, make sure to also review security.onecrl.maximum_staleness_in_seconds
 pref("services.settings.poll_interval", 86400); // 24H
-pref("services.settings.server", "https://firefox.settings.services.mozilla.com/v1");
+pref("services.settings.server", "resource://app/defaults/settings");
 pref("services.settings.default_bucket", "main");
 
 // The percentage of clients who will report uptake telemetry as
diff --git a/services/settings/Utils.jsm b/services/settings/Utils.jsm
index f91e5dcb67..c09c58e693 100644
--- a/services/settings/Utils.jsm
+++ b/services/settings/Utils.jsm
@@ -90,10 +90,10 @@ var Utils = {
   get SERVER_URL() {
     return allowServerURLOverride
       ? gServerURL
-      : "https://firefox.settings.services.mozilla.com/v1";
+      : "resource://app/defaults/settings";
   },
 
-  CHANGES_PATH: "/buckets/monitor/collections/changes/changeset",
+  CHANGES_PATH: "/monitor/changes",
 
   /**
    * Logger instance.
diff --git a/taskcluster/docker/periodic-updates/scripts/periodic_file_updates.sh b/taskcluster/docker/periodic-updates/scripts/periodic_file_updates.sh
index 191d3d563b..49fb961be2 100755
--- a/taskcluster/docker/periodic-updates/scripts/periodic_file_updates.sh
+++ b/taskcluster/docker/periodic-updates/scripts/periodic_file_updates.sh
@@ -285,7 +285,7 @@ function compare_suffix_lists {
 }
 
 function compare_remote_settings_files {
-  REMOTE_SETTINGS_SERVER="https://firefox.settings.services.mozilla.com/v1"
+  REMOTE_SETTINGS_SERVER="resource://app/defaults/settings"
 
   # 1. List remote settings collections from server.
   echo "INFO: fetch remote settings list from server"
diff --git a/toolkit/components/search/SearchUtils.jsm b/toolkit/components/search/SearchUtils.jsm
index 41d2a23e55..e123f3f392 100644
--- a/toolkit/components/search/SearchUtils.jsm
+++ b/toolkit/components/search/SearchUtils.jsm
@@ -159,13 +159,13 @@ var SearchUtils = {
 
   ENGINES_URLS: {
     "prod-main":
-      "https://firefox.settings.services.mozilla.com/v1/buckets/main/collections/search-config/records",
+      "resource://app/defaults/settings/main/search-config.json",
     "prod-preview":
-      "https://firefox.settings.services.mozilla.com/v1/buckets/main-preview/collections/search-config/records",
+      "resource://app/defaults/settings/main/search-config.json",
     "stage-main":
-      "https://settings.stage.mozaws.net/v1/buckets/main/collections/search-config/records",
+      "resource://app/defaults/settings/main/search-config.json",
     "stage-preview":
-      "https://settings.stage.mozaws.net/v1/buckets/main-preview/collections/search-config/records",
+      "resource://app/defaults/settings/main/search-config.json",
   },
 
   // The following constants are left undocumented in nsISearchService.idl
diff --git a/toolkit/components/search/docs/DefaultSearchEngines.rst b/toolkit/components/search/docs/DefaultSearchEngines.rst
index 1506af2913..5f43ff26f3 100644
--- a/toolkit/components/search/docs/DefaultSearchEngines.rst
+++ b/toolkit/components/search/docs/DefaultSearchEngines.rst
@@ -99,4 +99,4 @@ is updated.
 
 .. _configuration schema: SearchConfigurationSchema.html
 .. _remote settings: /services/settings/index.html
-.. _search-default-override-allowlist bucket: https://firefox.settings.services.mozilla.com/v1/buckets/main/collections/search-default-override-allowlist/records
+.. _search-default-override-allowlist bucket: resource://app/defaults/settings/main/search-default-override-allowlist.json
diff --git a/toolkit/components/search/docs/SearchEngineConfiguration.rst b/toolkit/components/search/docs/SearchEngineConfiguration.rst
index e9041affb8..7a9466d294 100644
--- a/toolkit/components/search/docs/SearchEngineConfiguration.rst
+++ b/toolkit/components/search/docs/SearchEngineConfiguration.rst
@@ -68,5 +68,5 @@ related. As a result several situations may occur:
 .. _JSON schema: https://json-schema.org/
 .. _stored in mozilla-central: https://searchfox.org/mozilla-central/source/toolkit/components/search/schema/
 .. _Search Configuration Schema: SearchConfigurationSchema.html
-.. _viewed live: https://firefox.settings.services.mozilla.com/v1/buckets/main/collections/search-config/records
+.. _viewed live: resource://app/defaults/settings/main/search-config.json
 .. _Normandy: /toolkit/components/normandy/normandy/services.html
diff --git a/toolkit/mozapps/defaultagent/RemoteSettings.cpp b/toolkit/mozapps/defaultagent/RemoteSettings.cpp
index 667d9fc628..b2bf628f29 100644
--- a/toolkit/mozapps/defaultagent/RemoteSettings.cpp
+++ b/toolkit/mozapps/defaultagent/RemoteSettings.cpp
@@ -23,7 +23,7 @@ extern "C" {
 HRESULT IsAgentRemoteDisabledRust(const char* szUrl, DWORD* lpdwDisabled);
 }
 
-#define PROD_ENDPOINT "https://firefox.settings.services.mozilla.com/v1"
+#define PROD_ENDPOINT "resource://app/defaults/settings"
 #define PROD_BID "main"
 #define PROD_CID "windows-default-browser-agent"
 #define PROD_ID "state"
-- 
2.35.1


From 99e7bd7760ebcd68575d19761d35a6db20ac8b48 Mon Sep 17 00:00:00 2001
From: grizzlyuser <grizzlyuser@protonmail.com>
Date: Wed, 30 Dec 2020 17:34:08 +0200
Subject: [PATCH 02/13] Remove polling triggered by push broadcasts

When initialized, remote-settings.js adds a listener to push broadcasts,
that let Remote Settings server send push messages to trigger polling
for changes from the client side. This is not needed for local-only
setup. Remove the record from broadcast-listeners.json file stored in
the user profile, so that it doesn't get picked up by push broadcast
service.
---
 dom/push/PushBroadcastService.jsm    | 13 +++++++++++++
 services/settings/remote-settings.js |  7 ++-----
 2 files changed, 15 insertions(+), 5 deletions(-)

diff --git a/dom/push/PushBroadcastService.jsm b/dom/push/PushBroadcastService.jsm
index aa1504211d..d635a2c3aa 100644
--- a/dom/push/PushBroadcastService.jsm
+++ b/dom/push/PushBroadcastService.jsm
@@ -178,6 +178,19 @@ var BroadcastService = class {
     }
   }
 
+  async deleteListener(broadcastId) {
+    await this.initializePromise;
+
+    if (this.jsonFile.data.listeners.hasOwnProperty(broadcastId)) {
+      console.info(
+        "deleteListener: deleting listener",
+        broadcastId
+      );
+      delete this.jsonFile.data.listeners[broadcastId];
+      this.jsonFile.saveSoon();
+    }
+  }
+
   /**
    * Call the listeners of the specified broadcasts.
    *
diff --git a/services/settings/remote-settings.js b/services/settings/remote-settings.js
index 4307597351..64cad55929 100644
--- a/services/settings/remote-settings.js
+++ b/services/settings/remote-settings.js
@@ -446,7 +446,7 @@ function remoteSettingsFunction() {
       moduleURI: __URI__,
       symbolName: "remoteSettingsBroadcastHandler",
     };
-    pushBroadcastService.addListener(BROADCAST_ID, currentVersion, moduleInfo);
+    pushBroadcastService.deleteListener(BROADCAST_ID);
   };
 
   return remoteSettings;
@@ -466,9 +466,6 @@ var remoteSettingsBroadcastHandler = {
       `Push notification received (version=${version} phase=${phase})`
     );
 
-    return RemoteSettings.pollChanges({
-      expectedTimestamp: version,
-      trigger: isStartup ? "startup" : "broadcast",
-    });
+    return;
   },
 };
-- 
2.35.1


From 52e9a179bc94e96fd8959b5fea9884ef9aa5fe77 Mon Sep 17 00:00:00 2001
From: grizzlyuser <grizzlyuser@protonmail.com>
Date: Wed, 30 Dec 2020 17:41:54 +0200
Subject: [PATCH 03/13] Remove timer that triggers polling for changes

That is not needed for local-only setup.
---
 services/settings/components.conf           | 9 +--------
 services/settings/servicesSettings.manifest | 4 ----
 2 files changed, 1 insertion(+), 12 deletions(-)

diff --git a/services/settings/components.conf b/services/settings/components.conf
index 9a737802ee..25109415a7 100644
--- a/services/settings/components.conf
+++ b/services/settings/components.conf
@@ -4,11 +4,4 @@
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
-Classes = [
-    {
-        'cid': '{5e756573-234a-49ea-bbe4-59ec7a70657d}',
-        'contract_ids': ['@mozilla.org/services/settings;1'],
-        'jsm': 'resource://services-settings/RemoteSettingsComponents.jsm',
-        'constructor': 'RemoteSettingsTimer',
-    },
-]
+Classes = []
diff --git a/services/settings/servicesSettings.manifest b/services/settings/servicesSettings.manifest
index 3bfed26ea4..807eb220ec 100644
--- a/services/settings/servicesSettings.manifest
+++ b/services/settings/servicesSettings.manifest
@@ -1,7 +1,3 @@
 # Register resource aliases
 resource services-settings resource://gre/modules/services-settings/
 
-# Schedule polling of remote settings changes
-# (default 24H, max 72H)
-# see syntax https://searchfox.org/mozilla-central/rev/cc280c4be94ff8cf64a27cc9b3d6831ffa49fa45/toolkit/components/timermanager/UpdateTimerManager.jsm#155
-category update-timer RemoteSettingsComponents @mozilla.org/services/settings;1,getService,services-settings-poll-changes,services.settings.poll_interval,86400,259200
-- 
2.35.1


From 04b7e9a6af031487d55eef867e581eb68c4d07c9 Mon Sep 17 00:00:00 2001
From: grizzlyuser <grizzlyuser@protonmail.com>
Date: Wed, 30 Dec 2020 17:47:41 +0200
Subject: [PATCH 04/13] Utils: fetch timestamps of each collection locally

Utils.CHANGES_PATH points to
services/settings/dumps/monitor/changes
which will be generated later by JSON processing script. Fetch the
timestamps from that file and mock response headers to not confuse any
code that expects them.
---
 browser/installer/package-manifest.in     |  1 +
 services/settings/Utils.jsm               | 17 ++++++++++++++---
 services/settings/dumps/monitor/moz.build |  8 ++++++++
 services/settings/dumps/moz.build         |  1 +
 4 files changed, 24 insertions(+), 3 deletions(-)
 create mode 100644 services/settings/dumps/monitor/moz.build

diff --git a/browser/installer/package-manifest.in b/browser/installer/package-manifest.in
index 73a41dc25b..04c2a3fb6a 100644
--- a/browser/installer/package-manifest.in
+++ b/browser/installer/package-manifest.in
@@ -275,6 +275,7 @@
 @RESPATH@/browser/defaults/settings/last_modified.json
 @RESPATH@/browser/defaults/settings/blocklists
 @RESPATH@/browser/defaults/settings/main
+@RESPATH@/browser/defaults/settings/monitor
 @RESPATH@/browser/defaults/settings/security-state
 
 ; Warning: changing the path to channel-prefs.js can cause bugs (Bug 756325)
diff --git a/services/settings/Utils.jsm b/services/settings/Utils.jsm
index c09c58e693..f5605b1b16 100644
--- a/services/settings/Utils.jsm
+++ b/services/settings/Utils.jsm
@@ -300,7 +300,7 @@ var Utils = {
   async fetchLatestChanges(serverUrl, options = {}) {
     const { expectedTimestamp, lastEtag = "", filters = {} } = options;
 
-    let url = serverUrl + Utils.CHANGES_PATH;
+    let url = Utils.SERVER_URL + Utils.CHANGES_PATH;
     const params = {
       ...filters,
       _expected: expectedTimestamp ?? 0,
@@ -315,7 +315,11 @@ var Utils = {
           .map(([k, v]) => `${k}=${encodeURIComponent(v)}`)
           .join("&");
     }
-    const response = await Utils.fetch(url);
+    const response = await fetch(url);
+    const responseDate = new Date().toUTCString()
+    response.headers.set("Date", responseDate);
+    response.headers.set("Last-Modified", responseDate);
+    response.headers.set("Content-Type", "application/json");
 
     if (response.status >= 500) {
       throw new Error(`Server error ${response.status} ${response.statusText}`);
@@ -350,7 +353,15 @@ var Utils = {
       }
     }
 
-    const { changes = [], timestamp } = payload;
+    const { timestamp } = payload;
+    const { bucket, collection } = filters;
+    if (!bucket || !collection) {
+      throw new Error('Unable to fetch latest change without bucket or collection');
+    }
+    const change = payload.changes.find(
+        change => change.bucket === bucket && change.collection === collection
+      ) ?? { last_modified: 0, bucket, collection };
+    const changes = [change];
 
     let serverTimeMillis = Date.parse(response.headers.get("Date"));
     // Since the response is served via a CDN, the Date header value could have been cached.
diff --git a/services/settings/dumps/monitor/moz.build b/services/settings/dumps/monitor/moz.build
new file mode 100644
index 0000000000..d3d017fda5
--- /dev/null
+++ b/services/settings/dumps/monitor/moz.build
@@ -0,0 +1,8 @@
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+FINAL_TARGET_FILES.defaults.settings.monitor += ["changes"]
+
+if CONFIG["MOZ_BUILD_APP"] == "browser":
+    DIST_SUBDIR = "browser"
diff --git a/services/settings/dumps/moz.build b/services/settings/dumps/moz.build
index f407580bfa..53e9d8b45e 100644
--- a/services/settings/dumps/moz.build
+++ b/services/settings/dumps/moz.build
@@ -5,6 +5,7 @@
 DIRS += [
     "blocklists",
     "main",
+    "monitor",
     "security-state",
 ]
 
-- 
2.35.1


From d2b5ce3db6af3e000f9ab7a10b2608e77cde0067 Mon Sep 17 00:00:00 2001
From: grizzlyuser <grizzlyuser@protonmail.com>
Date: Wed, 30 Dec 2020 17:52:10 +0200
Subject: [PATCH 05/13] Utils: disable offline checking

Since only local data is read now, it should always return false for the
current and any future code that relies on it.
---
 services/settings/Utils.jsm | 9 ---------
 1 file changed, 9 deletions(-)

diff --git a/services/settings/Utils.jsm b/services/settings/Utils.jsm
index f5605b1b16..cd189f1500 100644
--- a/services/settings/Utils.jsm
+++ b/services/settings/Utils.jsm
@@ -109,15 +109,6 @@ var Utils = {
    * @return {bool} Whether network is down or not.
    */
   get isOffline() {
-    try {
-      return (
-        Services.io.offline ||
-        CaptivePortalService.state == CaptivePortalService.LOCKED_PORTAL ||
-        !gNetworkLinkService.isLinkUp
-      );
-    } catch (ex) {
-      log.warn("Could not determine network status.", ex);
-    }
     return false;
   },
 
-- 
2.35.1


From 588cd28c3cd000501be66af573ac136e55d7e1ea Mon Sep 17 00:00:00 2001
From: grizzlyuser <grizzlyuser@protonmail.com>
Date: Wed, 30 Dec 2020 17:56:02 +0200
Subject: [PATCH 06/13] Refactor hashing logic to a separate function

It is used instead of internal signature validation mechanism, for
integrity checking of the locally cached data.
---
 services/settings/RemoteSettingsWorker.jsm | 4 ++++
 services/settings/SharedUtils.jsm          | 9 +++++++--
 2 files changed, 11 insertions(+), 2 deletions(-)

diff --git a/services/settings/RemoteSettingsWorker.jsm b/services/settings/RemoteSettingsWorker.jsm
index 147ebb6b13..c86e218fd3 100644
--- a/services/settings/RemoteSettingsWorker.jsm
+++ b/services/settings/RemoteSettingsWorker.jsm
@@ -189,6 +189,10 @@ class Worker {
     // task on the current thread instead of the worker thread.
     return SharedUtils.checkContentHash(buffer, size, hash);
   }
+
+  async getContentHash(bytes) {
+    return SharedUtils.getContentHash(bytes);
+  }
 }
 
 // Now, first add a shutdown blocker. If that fails, we must have
diff --git a/services/settings/SharedUtils.jsm b/services/settings/SharedUtils.jsm
index db5017a742..1a8e83c2e8 100644
--- a/services/settings/SharedUtils.jsm
+++ b/services/settings/SharedUtils.jsm
@@ -28,11 +28,16 @@ var SharedUtils = {
       return false;
     }
     // Has expected content?
+    const hashStr = await this.getContentHash(bytes);
+    return hashStr == hash;
+  },
+
+  async getContentHash(bytes) {
     const hashBuffer = await crypto.subtle.digest("SHA-256", bytes);
     const hashBytes = new Uint8Array(hashBuffer);
     const toHex = b => b.toString(16).padStart(2, "0");
-    const hashStr = Array.from(hashBytes, toHex).join("");
-    return hashStr == hash;
+
+    return Array.from(hashBytes, toHex).join("");
   },
 
   /**
-- 
2.35.1


From bce803bdb3e4f7203042454c65c386db6f385439 Mon Sep 17 00:00:00 2001
From: grizzlyuser <grizzlyuser@protonmail.com>
Date: Wed, 30 Dec 2020 18:05:02 +0200
Subject: [PATCH 07/13] Client: Fetch and hash records from local dump

Read the records from local dumps. See [1] for details on how to prepare
custom dumps). Records are cached in the local IndexedDB, and the client
updates cached records each time there's a change. Also it verifies
integrity of the data. Then the list of current / created / updated /
deleted records is generated and emitted to every registered listener.

Change upstream signature validation mechanism to a simpler one.
Otherwise, it'd be necessary to sign local records, which is redundant,
because the application package should be signed already by the distro.

Instead of signature property from metadata records, json_dump_metadata
has been introduced. It contains the checksum of the records and size in
bytes. Also added app_build_id property for version checking and updates
of cached data.

Although it's possible to disable integrity checking via preference, it
seems to be not a good idea, because the logic that detects invalid
local data relies on it. In the context of local-only setup, data that
has been received from real Remote Settings server will not contain the
custom metadata, and thus will be considered invalid and then discarded,
while the client gets a chance to gracefully inform registered listeners
about these changes so that they can discard the data received before
the upgrade to local-only setup.

[1] https://firefox-source-docs.mozilla.org/services/common/services/RemoteSettings.html#initial-data
---
 services/settings/RemoteSettingsClient.jsm | 62 ++++++++++------------
 1 file changed, 27 insertions(+), 35 deletions(-)

diff --git a/services/settings/RemoteSettingsClient.jsm b/services/settings/RemoteSettingsClient.jsm
index bd3fddbcf2..1c9dd2378f 100644
--- a/services/settings/RemoteSettingsClient.jsm
+++ b/services/settings/RemoteSettingsClient.jsm
@@ -587,11 +587,9 @@ class RemoteSettingsClient extends EventEmitter {
 
           // If the data is up-to-date but don't have metadata (records loaded from dump),
           // we fetch them and validate the signature immediately.
-          if (this.verifySignature && ObjectUtils.isEmpty(localMetadata)) {
+          if (this.verifySignature && ObjectUtils.isEmpty(localMetadata?.json_dump_metadata)) {
             console.debug(`${this.identifier} pull collection metadata`);
-            const metadata = await this.httpClient().getData({
-              query: { _expected: expectedTimestamp },
-            });
+            const { metadata } = await this._fetchChangeset(expectedTimestamp);
             await this.db.importChanges(metadata);
             // We don't bother validating the signature if the dump was just loaded. We do
             // if the dump was loaded at some other point (eg. from .get()).
@@ -844,32 +842,23 @@ class RemoteSettingsClient extends EventEmitter {
   async _validateCollectionSignature(records, timestamp, metadata) {
     const start = Cu.now() * 1000;
 
-    if (!metadata?.signature) {
+    if (!metadata?.json_dump_metadata) {
       throw new MissingSignatureError(this.identifier);
     }
 
-    if (!this._verifier) {
-      this._verifier = Cc[
-        "@mozilla.org/security/contentsignatureverifier;1"
-      ].createInstance(Ci.nsIContentSignatureVerifier);
-    }
-
-    // This is a content-signature field from an autograph response.
     const {
-      signature: { x5u, signature },
+      json_dump_metadata: { hash, size },
     } = metadata;
-    const certChain = await (await Utils.fetch(x5u)).text();
     // Merge remote records with local ones and serialize as canonical JSON.
     const serialized = await RemoteSettingsWorker.canonicalStringify(
       records,
       timestamp
     );
     if (
-      !(await this._verifier.asyncVerifyContentSignature(
-        serialized,
-        "p384ecdsa=" + signature,
-        certChain,
-        this.signerName
+      !(await RemoteSettingsWorker.checkContentHash(
+        new TextEncoder().encode(serialized),
+        size,
+        hash
       ))
     ) {
       throw new InvalidSignatureError(this.identifier);
@@ -1061,24 +1050,27 @@ class RemoteSettingsClient extends EventEmitter {
    * @param since timestamp of last sync (optional)
    */
   async _fetchChangeset(expectedTimestamp, since) {
-    const client = this.httpClient();
-    const {
-      metadata,
-      timestamp: remoteTimestamp,
-      changes: remoteRecords,
-    } = await client.execute(
-      {
-        path: `/buckets/${this.bucketName}/collections/${this.collectionName}/changeset`,
-      },
-      {
-        query: {
-          _expected: expectedTimestamp,
-          _since: since,
-        },
-      }
+    const { data } = await SharedUtils.loadJSONDump(
+      this.bucketName,
+      this.collectionName
     );
+    const remoteRecords = data ?? [];
+
+    const serialized = await RemoteSettingsWorker.canonicalStringify(
+      remoteRecords,
+      expectedTimestamp
+    );
+    const bytes = new TextEncoder().encode(serialized);
+    const metadata = {
+      app_build_id: Services.appinfo.appBuildID,
+      json_dump_metadata: {
+        hash: await RemoteSettingsWorker.getContentHash(bytes),
+        size: bytes.length,
+      },
+    }
+
     return {
-      remoteTimestamp,
+      remoteTimestamp: expectedTimestamp,
       metadata,
       remoteRecords,
     };
-- 
2.35.1


From dd4897ba2ece2d0deb23953c044c44323d9934d0 Mon Sep 17 00:00:00 2001
From: grizzlyuser <grizzlyuser@protonmail.com>
Date: Wed, 30 Dec 2020 18:42:56 +0200
Subject: [PATCH 08/13] Client: start deferred sync on get() or on()

The users of the RemoteSettingsClient.jsm can receive records from it in
two ways: by calling get(), and by subscribing to events by calling
on().

So hook a deferred sync whenever something calls these methods. Because
multiple of those calls can be made quite early and in very short time,
set up a deferred task that will be armed only when needed and only once
in a second. When the task is running it first checks if the local data
came from the dump of the current app build, and no-ops if true. If
false, it triggers a sync. Then adds a flag if the client has been
correctly synchronized with the dump, so that no metadata checking
occurs during the session.
---
 services/settings/RemoteSettingsClient.jsm | 30 +++++++++++++++++++++-
 1 file changed, 29 insertions(+), 1 deletion(-)

diff --git a/services/settings/RemoteSettingsClient.jsm b/services/settings/RemoteSettingsClient.jsm
index 1c9dd2378f..f7a0b3bdaa 100644
--- a/services/settings/RemoteSettingsClient.jsm
+++ b/services/settings/RemoteSettingsClient.jsm
@@ -16,6 +16,7 @@ XPCOMUtils.defineLazyModuleGetters(this, {
   ClientEnvironmentBase:
     "resource://gre/modules/components-utils/ClientEnvironment.jsm",
   Database: "resource://services-settings/Database.jsm",
+  DeferredTask: "resource://gre/modules/DeferredTask.jsm",
   Downloader: "resource://services-settings/Attachments.jsm",
   IDBHelpers: "resource://services-settings/IDBHelpers.jsm",
   KintoHttpClient: "resource://services-common/kinto-http-client.js",
@@ -28,6 +29,7 @@ XPCOMUtils.defineLazyModuleGetters(this, {
 });
 
 const TELEMETRY_COMPONENT = "remotesettings";
+const DEFERRED_SYNC_DELAY_MILLISECONDS = 1000;
 
 XPCOMUtils.defineLazyGetter(this, "console", () => Utils.log);
 
@@ -259,6 +261,14 @@ class RemoteSettingsClient extends EventEmitter {
     this._lastCheckTimePref = lastCheckTimePref;
     this._verifier = null;
     this._syncRunning = false;
+    this._deferredSync = new DeferredTask(
+      async () => {
+        if (!this._syncRunning && !(await this._isSynced())) {
+          await this.sync();
+        }
+      },
+      DEFERRED_SYNC_DELAY_MILLISECONDS
+    );
 
     // This attribute allows signature verification to be disabled, when running tests
     // or when pulling data from a dev server.
@@ -293,6 +303,11 @@ class RemoteSettingsClient extends EventEmitter {
     );
   }
 
+  on(event, callback) {
+    super.on(event, callback);
+    this._deferredSync.arm();
+  }
+
   get identifier() {
     return `${this.bucketName}/${this.collectionName}`;
   }
@@ -361,6 +376,10 @@ class RemoteSettingsClient extends EventEmitter {
       let lastModified = await this.db.getLastModified();
       let hasLocalData = lastModified !== null;
 
+      if (!(await this._isSynced())) {
+        throw new MissingSignatureError(this.identifier);
+      }
+
       if (syncIfEmpty && !hasLocalData) {
         // .get() was called before we had the chance to synchronize the local database.
         // We'll try to avoid returning an empty list.
@@ -445,7 +464,10 @@ class RemoteSettingsClient extends EventEmitter {
       // No need to verify signature on JSON dumps.
       // If local DB cannot be read, then we don't even try to do anything,
       // we return results early.
-      return this._filterEntries(data);
+      const filtered = this._filterEntries(data);
+      this._deferredSync.arm();
+
+      return filtered;
     }
 
     console.debug(
@@ -483,6 +505,12 @@ class RemoteSettingsClient extends EventEmitter {
     return final;
   }
 
+  async _isSynced() {
+    this._synced ||=
+      Services.appinfo.appBuildID === (await this.db.getMetadata())?.app_build_id;
+    return this._synced;
+  }
+
   /**
    * Synchronize the local database with the remote server.
    *
-- 
2.35.1


From 192096cd8caa2cbdfdc294a71056e6ee1b7e513d Mon Sep 17 00:00:00 2001
From: grizzlyuser <grizzlyuser@protonmail.com>
Date: Wed, 30 Dec 2020 18:53:51 +0200
Subject: [PATCH 09/13] Client: deep compare records if timestamps match

When the list of current / updated / deleted records is generated, their
modification timestamps are compared to detect the updates.

Although in practice this is unlikely to happen, in theory the
timestamp of some older record received from Remote Settings can match
with the modified record in the dump. Although JSON processing script
makes sure to add unique timestamps to each of the modified records,
it's still possible to update dumps manually and simply forget to update
timestamps. So serialize the records and compare them as strings to be
on the safe side. This should happen only once after upgrading to each
new version of the application, so is not likely to introduce any
noticeable performance issues.
---
 services/settings/RemoteSettingsClient.jsm | 6 +++++-
 1 file changed, 5 insertions(+), 1 deletion(-)

diff --git a/services/settings/RemoteSettingsClient.jsm b/services/settings/RemoteSettingsClient.jsm
index f7a0b3bdaa..64ac27d149 100644
--- a/services/settings/RemoteSettingsClient.jsm
+++ b/services/settings/RemoteSettingsClient.jsm
@@ -13,6 +13,7 @@ const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
 
 XPCOMUtils.defineLazyModuleGetters(this, {
   AppConstants: "resource://gre/modules/AppConstants.jsm",
+  CanonicalJSON: "resource://gre/modules/CanonicalJSON.jsm",
   ClientEnvironmentBase:
     "resource://gre/modules/components-utils/ClientEnvironment.jsm",
   Database: "resource://services-settings/Database.jsm",
@@ -1053,7 +1054,10 @@ class RemoteSettingsClient extends EventEmitter {
         const old = oldById.get(r.id);
         if (old) {
           oldById.delete(r.id);
-          if (r.last_modified != old.last_modified) {
+          if (
+            r.last_modified != old.last_modified ||
+            CanonicalJSON.stringify(r) != CanonicalJSON.stringify(old)
+          ) {
             syncResult.updated.push({ old, new: r });
           }
         } else {
-- 
2.35.1


From c834cd3beeb989f30c88aabea480d08989c02abc Mon Sep 17 00:00:00 2001
From: grizzlyuser <grizzlyuser@protonmail.com>
Date: Wed, 30 Dec 2020 19:01:39 +0200
Subject: [PATCH 10/13] Client: delete more data on cleanup

When the client detects the local data is invalid (i.e. it came from
real Remote Settings and can have unwanted records), delete not only
the records, but also the attachments that came with them, because they
too can be problematic. And last check time preference, because it's not
useful anyway when remote-settings.js doesn't do any polling for changes.

Note that attachments should be deleted before the records, because the
logic gets the data about the attachments from those records.
---
 services/settings/RemoteSettingsClient.jsm | 15 ++++++++++++---
 1 file changed, 12 insertions(+), 3 deletions(-)

diff --git a/services/settings/RemoteSettingsClient.jsm b/services/settings/RemoteSettingsClient.jsm
index 64ac27d149..ac6259ca2c 100644
--- a/services/settings/RemoteSettingsClient.jsm
+++ b/services/settings/RemoteSettingsClient.jsm
@@ -219,7 +219,7 @@ class AttachmentDownloader extends Downloader {
       allRecords
         .filter(r => !!r.attachment)
         .map(r =>
-          Promise.all([this.deleteDownloaded(r), this.deleteFromDisk(r)])
+          Promise.all([this.deleteDownloaded(r), this.deleteFromDisk(r), this.deleteCached(r.id)])
         )
     );
   }
@@ -1013,7 +1016,7 @@ class RemoteSettingsClient extends EventEmitter {
           // Signature failed, clear local DB because it contains
           // bad data (local + remote changes).
           console.debug(`${this.identifier} clear local data`);
-          await this.db.clear();
+          await this._clearAll();
           // Local data was tampered, throw and it will retry from empty DB.
           console.error(`${this.identifier} local data was corrupted`);
           throw new CorruptedDataError(this.identifier);
@@ -1035,7 +1038,7 @@ class RemoteSettingsClient extends EventEmitter {
             // _importJSONDump() only clears DB if dump is available,
             // therefore do it here!
             if (imported < 0) {
-              await this.db.clear();
+              await this._clearAll();
             }
           }
         }
@@ -1075,6 +1078,12 @@ class RemoteSettingsClient extends EventEmitter {
     return syncResult;
   }
 
+  async _clearAll() {
+    await this.attachments.deleteAll();
+    await this.db.clear();
+    Services.prefs.clearUserPref(this.lastCheckTimePref);
+  }
+
   /**
    * Fetch information from changeset endpoint.
    *
-- 
2.35.1


From 68ee3019155c605ea3fefd9370209d548d1049c2 Mon Sep 17 00:00:00 2001
From: grizzlyuser <grizzlyuser@protonmail.com>
Date: Wed, 30 Dec 2020 19:07:56 +0200
Subject: [PATCH 11/13] Client: remove comparison of collection timestamps

In case if the cached data that came from real Remote Settings server
(before the upgrade to local-only setup) has collection timestamp, that
is newer than the packaged local dump, then this comparison logic can
lead to early return of old data, skipping the integrity checking and
necessary cleanup. So remove the checks.
---
 services/settings/RemoteSettingsClient.jsm | 5 -----
 1 file changed, 5 deletions(-)

diff --git a/services/settings/RemoteSettingsClient.jsm b/services/settings/RemoteSettingsClient.jsm
index ac6259ca2c..e59845a337 100644
--- a/services/settings/RemoteSettingsClient.jsm
+++ b/services/settings/RemoteSettingsClient.jsm
@@ -948,14 +948,9 @@ class RemoteSettingsClient extends EventEmitter {
       updated: [],
       deleted: [],
     };
-    // If data wasn't changed, return empty sync result.
-    // This can happen when we update the signature but not the data.
     console.debug(
       `${this.identifier} local timestamp: ${localTimestamp}, remote: ${remoteTimestamp}`
     );
-    if (localTimestamp && remoteTimestamp < localTimestamp) {
-      return syncResult;
-    }
 
     const start = Cu.now() * 1000;
     await this.db.importChanges(metadata, remoteTimestamp, remoteRecords, {
-- 
2.35.1


From aa15f1fee8030b3a315312fba2f1b19e6694aad4 Mon Sep 17 00:00:00 2001
From: grizzlyuser <grizzlyuser@protonmail.com>
Date: Wed, 30 Dec 2020 19:15:44 +0200
Subject: [PATCH 12/13] Attachments: load only from dump and drop cached

---
 services/settings/Attachments.jsm | 35 +++++++------------------------
 1 file changed, 8 insertions(+), 27 deletions(-)

diff --git a/services/settings/Attachments.jsm b/services/settings/Attachments.jsm
index 70c02627ac..d24d8907fd 100644
--- a/services/settings/Attachments.jsm
+++ b/services/settings/Attachments.jsm
@@ -151,9 +151,10 @@ class Downloader {
       retries,
       checkHash,
       attachmentId = record?.id,
-      fallbackToCache = false,
       fallbackToDump = false,
     } = options || {};
+    const fallbackToCache = false;
+    
     if (!attachmentId) {
       // Check for pre-condition. This should not happen, but it is explicitly
       // checked to avoid mixing up attachments, which could be dangerous.
@@ -204,6 +205,7 @@ class Downloader {
         const newBuffer = await this.downloadAsBytes(record, {
           retries,
           checkHash,
+          dumpInfo,
         });
         const blob = new Blob([newBuffer]);
         // Store in cache but don't wait for it before returning.
@@ -239,7 +241,7 @@ class Downloader {
       }
 
       try {
-        return { ...(await cacheInfo.getResult()), _source: "cache_fallback" };
+        await this.cacheImpl.delete(attachmentId);
       } catch (e) {
         // Failed to read from cache, e.g. IndexedDB unusable.
         Cu.reportError(e);
@@ -276,7 +278,7 @@ class Downloader {
    * @returns {String} the absolute file path to the downloaded attachment.
    */
   async downloadToDisk(record, options = {}) {
-    const { retries = 3 } = options;
+    const retries = 0;
     const {
       attachment: { filename, size, hash },
     } = record;
@@ -333,31 +335,10 @@ class Downloader {
    */
   async downloadAsBytes(record, options = {}) {
     const {
-      attachment: { location, hash, size },
-    } = record;
-
-    const remoteFileUrl = (await this._baseAttachmentsURL()) + location;
+      dumpInfo = new LazyRecordAndBuffer(() => this._readAttachmentDump(attachmentId))
+    } = options;
 
-    const { retries = 3, checkHash = true } = options;
-    let retried = 0;
-    while (true) {
-      try {
-        const buffer = await this._fetchAttachment(remoteFileUrl);
-        if (!checkHash) {
-          return buffer;
-        }
-        if (await RemoteSettingsWorker.checkContentHash(buffer, size, hash)) {
-          return buffer;
-        }
-        // Content is corrupted.
-        throw new Downloader.BadContentError(location);
-      } catch (e) {
-        if (retried >= retries) {
-          throw e;
-        }
-      }
-      retried++;
-    }
+    return (await dumpInfo.getResult()).buffer;
   }
 
   /**
-- 
2.35.1


From 271e88d8a18a6ae30ccc616c57fe7a36290ba520 Mon Sep 17 00:00:00 2001
From: grizzlyuser <grizzlyuser@protonmail.com>
Date: Wed, 30 Dec 2020 19:22:20 +0200
Subject: [PATCH 13/13] Disable CRLite entirely for now

It's designed to fetch the data from Remote Settings. One of the main
selling points is that new revocations can be pushed to the clients
within minutes. That won't work with local-only setup. Although (some?)
of the JSON dumps for it are in place, obviously the updates won't
happen that fast.

Right now CRLite doesn't enforce anything, and works just for telemetry
collection (which is hopefully disabled anyway). So disable the
preference right in the source code, so that the patch fails to apply
when the upstream decides to set it to enforcing mode by default.

The solution with CRLite is up for discussion. If necessary, it's
possible to make clients for blessed collections to communicate to real
Remote Settings server. For example, for collections related to
certificate revocations.
---
 modules/libpref/init/all.js | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/modules/libpref/init/all.js b/modules/libpref/init/all.js
index cb72224e1b..79940b598a 100644
--- a/modules/libpref/init/all.js
+++ b/modules/libpref/init/all.js
@@ -160,7 +160,7 @@ pref("security.xfocsp.errorReporting.automatic", false);
 // 1: Consult CRLite but only collect telemetry.
 // 2: Consult CRLite and enforce both "Revoked" and "Not Revoked" results.
 // 3: Consult CRLite and enforce "Not Revoked" results, but defer to OCSP for "Revoked".
-pref("security.pki.crlite_mode", 3);
+pref("security.pki.crlite_mode", 0);
 
 // Issuer we use to detect MitM proxies. Set to the issuer of the cert of the
 // Firefox update service. The string format is whatever NSS uses to print a DN.
-- 
2.35.1