forked from Floorp-Projects/Floorp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRemoteSettingsClient.jsm
1070 lines (990 loc) · 35 KB
/
RemoteSettingsClient.jsm
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
/* 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/. */
"use strict";
var EXPORTED_SYMBOLS = ["RemoteSettingsClient"];
const { XPCOMUtils } = ChromeUtils.import(
"resource://gre/modules/XPCOMUtils.jsm"
);
const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
XPCOMUtils.defineLazyModuleGetters(this, {
ClientEnvironmentBase:
"resource://gre/modules/components-utils/ClientEnvironment.jsm",
Database: "resource://services-settings/Database.jsm",
Downloader: "resource://services-settings/Attachments.jsm",
IDBHelpers: "resource://services-settings/IDBHelpers.jsm",
KintoHttpClient: "resource://services-common/kinto-http-client.js",
ObjectUtils: "resource://gre/modules/ObjectUtils.jsm",
PerformanceCounters: "resource://gre/modules/PerformanceCounters.jsm",
RemoteSettingsWorker: "resource://services-settings/RemoteSettingsWorker.jsm",
UptakeTelemetry: "resource://services-common/uptake-telemetry.js",
Utils: "resource://services-settings/Utils.jsm",
});
XPCOMUtils.defineLazyGlobalGetters(this, ["fetch"]);
const TELEMETRY_COMPONENT = "remotesettings";
XPCOMUtils.defineLazyGetter(this, "console", () => Utils.log);
XPCOMUtils.defineLazyPreferenceGetter(
this,
"gTimingEnabled",
"services.settings.enablePerformanceCounters",
false
);
XPCOMUtils.defineLazyPreferenceGetter(
this,
"gLoadDump",
"services.settings.load_dump",
true
);
/**
* cacheProxy returns an object Proxy that will memoize properties of the target.
* @param {Object} target the object to wrap.
* @returns {Proxy}
*/
function cacheProxy(target) {
const cache = new Map();
return new Proxy(target, {
get(target, prop, receiver) {
if (!cache.has(prop)) {
cache.set(prop, target[prop]);
}
return cache.get(prop);
},
});
}
/**
* Minimalist event emitter.
*
* Note: we don't use `toolkit/modules/EventEmitter` because **we want** to throw
* an error when a listener fails to execute.
*/
class EventEmitter {
constructor(events) {
this._listeners = new Map();
for (const event of events) {
this._listeners.set(event, []);
}
}
/**
* Event emitter: will execute the registered listeners in the order and
* sequentially.
*
* @param {string} event the event name
* @param {Object} payload the event payload to call the listeners with
*/
async emit(event, payload) {
const callbacks = this._listeners.get(event);
let lastError;
for (const cb of callbacks) {
try {
await cb(payload);
} catch (e) {
lastError = e;
}
}
if (lastError) {
throw lastError;
}
}
on(event, callback) {
if (!this._listeners.has(event)) {
throw new Error(`Unknown event type ${event}`);
}
this._listeners.get(event).push(callback);
}
off(event, callback) {
if (!this._listeners.has(event)) {
throw new Error(`Unknown event type ${event}`);
}
const callbacks = this._listeners.get(event);
const i = callbacks.indexOf(callback);
if (i < 0) {
throw new Error(`Unknown callback`);
} else {
callbacks.splice(i, 1);
}
}
}
class NetworkOfflineError extends Error {
constructor(cid) {
super("Network is offline");
this.name = "NetworkOfflineError";
}
}
class InvalidSignatureError extends Error {
constructor(cid) {
super(`Invalid content signature (${cid})`);
this.name = "InvalidSignatureError";
}
}
class MissingSignatureError extends InvalidSignatureError {
constructor(cid) {
super(cid);
this.message = `Missing signature (${cid})`;
this.name = "MissingSignatureError";
}
}
class CorruptedDataError extends InvalidSignatureError {
constructor(cid) {
super(cid);
this.message = `Corrupted local data (${cid})`;
this.name = "CorruptedDataError";
}
}
class UnknownCollectionError extends Error {
constructor(cid) {
super(`Unknown Collection "${cid}"`);
this.name = "UnknownCollectionError";
}
}
class AttachmentDownloader extends Downloader {
constructor(client) {
super(client.bucketName, client.collectionName);
this._client = client;
}
get cacheImpl() {
const cacheImpl = {
get: async attachmentId => {
return this._client.db.getAttachment(attachmentId);
},
set: async (attachmentId, attachment) => {
return this._client.db.saveAttachment(attachmentId, attachment);
},
delete: async attachmentId => {
return this._client.db.saveAttachment(attachmentId, null);
},
};
Object.defineProperty(this, "cacheImpl", { value: cacheImpl });
return cacheImpl;
}
/**
* Download attachment and report Telemetry on failure.
*
* @see Downloader.download
*/
async download(record, options) {
try {
// Explicitly await here to ensure we catch a network error.
return await super.download(record, options);
} catch (err) {
// Report download error.
let status = UptakeTelemetry.STATUS.DOWNLOAD_ERROR;
if (Utils.isOffline) {
status = UptakeTelemetry.STATUS.NETWORK_OFFLINE_ERROR;
} else if (/NetworkError/.test(err.message)) {
status = UptakeTelemetry.STATUS.NETWORK_ERROR;
}
// If the file failed to be downloaded, report it as such in Telemetry.
await UptakeTelemetry.report(TELEMETRY_COMPONENT, status, {
source: this._client.identifier,
});
throw err;
}
}
/**
* Delete all downloaded records attachments.
*
* Note: the list of attachments to be deleted is based on the
* current list of records.
*/
async deleteAll() {
let allRecords = await this._client.db.list();
return Promise.all(
allRecords.filter(r => !!r.attachment).map(r => this.delete(r))
);
}
}
class RemoteSettingsClient extends EventEmitter {
static get NetworkOfflineError() {
return NetworkOfflineError;
}
static get InvalidSignatureError() {
return InvalidSignatureError;
}
static get MissingSignatureError() {
return MissingSignatureError;
}
static get CorruptedDataError() {
return CorruptedDataError;
}
static get UnknownCollectionError() {
return UnknownCollectionError;
}
constructor(
collectionName,
{
bucketNamePref,
signerName,
filterFunc,
localFields = [],
lastCheckTimePref,
}
) {
super(["sync"]); // emitted events
this.collectionName = collectionName;
this.signerName = signerName;
this.filterFunc = filterFunc;
this.localFields = localFields;
this._lastCheckTimePref = lastCheckTimePref;
this._verifier = null;
this._syncRunning = false;
// This attribute allows signature verification to be disabled, when running tests
// or when pulling data from a dev server.
this.verifySignature = true;
// The bucket preference value can be changed (eg. `main` to `main-preview`) in order
// to preview the changes to be approved in a real client.
this.bucketNamePref = bucketNamePref;
XPCOMUtils.defineLazyPreferenceGetter(
this,
"bucketName",
this.bucketNamePref
);
XPCOMUtils.defineLazyGetter(
this,
"db",
() => new Database(this.identifier)
);
XPCOMUtils.defineLazyGetter(
this,
"attachments",
() => new AttachmentDownloader(this)
);
}
get identifier() {
return `${this.bucketName}/${this.collectionName}`;
}
get lastCheckTimePref() {
return (
this._lastCheckTimePref ||
`services.settings.${this.bucketName}.${this.collectionName}.last_check`
);
}
httpClient() {
const api = new KintoHttpClient(Utils.SERVER_URL);
return api.bucket(this.bucketName).collection(this.collectionName);
}
/**
* Retrieve the collection timestamp for the last synchronization.
* This is an opaque and comparable value assigned automatically by
* the server.
*
* @returns {number}
* The timestamp in milliseconds, returns -1 if retrieving
* the timestamp from the kinto collection fails.
*/
async getLastModified() {
let timestamp = -1;
try {
timestamp = await this.db.getLastModified();
} catch (err) {
console.warn(
`Error retrieving the getLastModified timestamp from ${this.identifier} RemoteSettingsClient`,
err
);
}
return timestamp;
}
/**
* Lists settings.
*
* @param {Object} options The options object.
* @param {Object} options.filters Filter the results (default: `{}`).
* @param {String} options.order The order to apply (eg. `"-last_modified"`).
* @param {boolean} options.syncIfEmpty Synchronize from server if local data is empty (default: `true`).
* @param {boolean} options.verifySignature Verify the signature of the local data (default: `false`).
* @return {Promise}
*/
async get(options = {}) {
const {
filters = {},
order = "", // not sorted by default.
syncIfEmpty = true,
} = options;
let { verifySignature = false } = options;
if (syncIfEmpty && !(await Utils.hasLocalData(this))) {
try {
// .get() was called before we had the chance to synchronize the local database.
// We'll try to avoid returning an empty list.
const importedFromDump = gLoadDump ? await this._importJSONDump() : -1;
if (importedFromDump < 0) {
// There is no JSON dump to load, force a synchronization from the server.
console.debug(
`${this.identifier} Local DB is empty, pull data from server`
);
await this.sync({ loadDump: false });
}
// Either from trusted dump, or already done during sync.
verifySignature = false;
} catch (e) {
// Report but return an empty list since there will be no data anyway.
Cu.reportError(e);
return [];
}
}
// Read from the local DB.
const data = await this.db.list({ filters, order });
console.debug(
`${this.identifier} ${data.length} records before filtering.`
);
if (verifySignature) {
console.debug(
`${this.identifier} verify signature of local data on read`
);
const allData = ObjectUtils.isEmpty(filters)
? data
: await this.db.list();
const localRecords = allData.map(r => this._cleanLocalFields(r));
const timestamp = await this.db.getLastModified();
let metadata = await this.db.getMetadata();
if (syncIfEmpty && ObjectUtils.isEmpty(metadata)) {
// No sync occured yet, may have records from dump but no metadata.
await this.sync({ loadDump: false });
metadata = await this.db.getMetadata();
}
// Will throw MissingSignatureError if no metadata and `syncIfEmpty` is false.
await this._validateCollectionSignature(
localRecords,
timestamp,
metadata
);
}
// Filter the records based on `this.filterFunc` results.
const final = await this._filterEntries(data);
console.debug(
`${this.identifier} ${final.length} records after filtering.`
);
return final;
}
/**
* Synchronize the local database with the remote server.
*
* @param {Object} options See #maybeSync() options.
*/
async sync(options) {
// We want to know which timestamp we are expected to obtain in order to leverage
// cache busting. We don't provide ETag because we don't want a 304.
const { changes } = await Utils.fetchLatestChanges(Utils.SERVER_URL, {
filters: {
collection: this.collectionName,
bucket: this.bucketName,
},
});
if (changes.length === 0) {
throw new RemoteSettingsClient.UnknownCollectionError(this.identifier);
}
// According to API, there will be one only (fail if not).
const [{ last_modified: expectedTimestamp }] = changes;
return this.maybeSync(expectedTimestamp, { ...options, trigger: "forced" });
}
/**
* Synchronize the local database with the remote server, **only if necessary**.
*
* @param {int} expectedTimestamp the lastModified date (on the server) for the remote collection.
* This will be compared to the local timestamp, and will be used for
* cache busting if local data is out of date.
* @param {Object} options additional advanced options.
* @param {bool} options.loadDump load initial dump from disk on first sync (default: true, unless
* `services.settings.load_dump` says otherwise).
* @param {string} options.trigger label to identify what triggered this sync (eg. ``"timer"``, default: `"manual"`)
* @return {Promise} which rejects on sync or process failure.
*/
async maybeSync(expectedTimestamp, options = {}) {
// Should the clients try to load JSON dump? (mainly disabled in tests)
const { loadDump = gLoadDump, trigger = "manual" } = options;
// Make sure we don't run several synchronizations in parallel, mainly
// in order to avoid race conditions in "sync" events listeners.
if (this._syncRunning) {
console.warn(`${this.identifier} sync already running`);
return;
}
// Prevent network requests and IndexedDB calls to be initiated
// during shutdown.
if (Services.startup.shuttingDown) {
console.warn(`${this.identifier} sync interrupted by shutdown`);
return;
}
this._syncRunning = true;
let importedFromDump = [];
const startedAt = new Date();
let reportStatus = null;
let thrownError = null;
try {
// If network is offline, we can't synchronize.
if (Utils.isOffline) {
throw new RemoteSettingsClient.NetworkOfflineError();
}
// Read last timestamp and local data before sync.
let collectionLastModified = await this.db.getLastModified();
const allData = await this.db.list();
// Local data can contain local fields, strip them.
let localRecords = allData.map(r => this._cleanLocalFields(r));
const localMetadata = await this.db.getMetadata();
// If there is no data currently in the collection, attempt to import
// initial data from the application defaults.
// This allows to avoid synchronizing the whole collection content on
// cold start.
if (!collectionLastModified && loadDump) {
try {
const imported = await this._importJSONDump();
// The worker only returns an integer. List the imported records to build the sync event.
if (imported > 0) {
console.debug(
`${this.identifier} ${imported} records loaded from JSON dump`
);
importedFromDump = await this.db.list();
// Local data is the data loaded from dump. We will need this later
// to compute the sync result.
localRecords = importedFromDump;
}
collectionLastModified = await this.db.getLastModified();
} catch (e) {
// Report but go-on.
Cu.reportError(e);
}
}
let syncResult;
try {
// Is local timestamp up to date with the server?
if (expectedTimestamp == collectionLastModified) {
console.debug(`${this.identifier} local data is up-to-date`);
reportStatus = UptakeTelemetry.STATUS.UP_TO_DATE;
// 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)) {
console.debug(`${this.identifier} pull collection metadata`);
const metadata = await this.httpClient().getData({
query: { _expected: expectedTimestamp },
});
await this.db.saveMetadata(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()).
if (this.verifySignature && importedFromDump.length == 0) {
console.debug(
`${this.identifier} verify signature of local data`
);
await this._validateCollectionSignature(
localRecords,
collectionLastModified,
metadata
);
}
}
// Since the data is up-to-date, if we didn't load any dump then we're done here.
if (importedFromDump.length == 0) {
return;
}
// Otherwise we want to continue with sending the sync event to notify about the created records.
syncResult = {
current: importedFromDump,
created: importedFromDump,
updated: [],
deleted: [],
};
} else {
// Local data is either outdated or tampered.
// In both cases we will fetch changes from server,
// and make sure we overwrite local data.
const startSyncDB = Cu.now() * 1000;
syncResult = await this._importChanges(
localRecords,
collectionLastModified,
localMetadata,
expectedTimestamp
);
if (gTimingEnabled) {
const endSyncDB = Cu.now() * 1000;
PerformanceCounters.storeExecutionTime(
`remotesettings/${this.identifier}`,
"syncDB",
endSyncDB - startSyncDB,
"duration"
);
}
// The records imported from the dump should be considered as "created" for the
// listeners.
const importedById = importedFromDump.reduce((acc, r) => {
acc.set(r.id, r);
return acc;
}, new Map());
// Deleted records should not appear as created.
syncResult.deleted.forEach(r => importedById.delete(r.id));
// Records from dump that were updated should appear in their newest form.
syncResult.updated.forEach(u => {
if (importedById.has(u.old.id)) {
importedById.set(u.old.id, u.new);
}
});
syncResult.created = syncResult.created.concat(
Array.from(importedById.values())
);
}
} catch (e) {
if (e instanceof InvalidSignatureError) {
// Signature verification failed during synchronization.
reportStatus =
e instanceof CorruptedDataError
? UptakeTelemetry.STATUS.CORRUPTION_ERROR
: UptakeTelemetry.STATUS.SIGNATURE_ERROR;
// If sync fails with a signature error, it's likely that our
// local data has been modified in some way.
// We will attempt to fix this by retrieving the whole
// remote collection.
try {
console.warn(
`Signature verified failed for ${this.identifier}. Retry from scratch`
);
syncResult = await this._importChanges(
localRecords,
collectionLastModified,
localMetadata,
expectedTimestamp,
{ retry: true }
);
} catch (e) {
// If the signature fails again, or if an error occured during wiping out the
// local data, then we report it as a *signature retry* error.
reportStatus = UptakeTelemetry.STATUS.SIGNATURE_RETRY_ERROR;
throw e;
}
} else {
// The sync has thrown for other reason than signature verification.
// Default status for errors at this step is SYNC_ERROR.
reportStatus = this._telemetryFromError(e, {
default: UptakeTelemetry.STATUS.SYNC_ERROR,
});
throw e;
}
}
// Filter the synchronization results using `filterFunc` (ie. JEXL).
const filteredSyncResult = await this._filterSyncResult(syncResult);
// If every changed entry is filtered, we don't even fire the event.
if (filteredSyncResult) {
try {
await this.emit("sync", { data: filteredSyncResult });
} catch (e) {
reportStatus = UptakeTelemetry.STATUS.APPLY_ERROR;
throw e;
}
} else {
console.info(
`All changes are filtered by JEXL expressions for ${this.identifier}`
);
}
} catch (e) {
thrownError = e;
// If browser is shutting down, then we can report a specific status.
// (eg. IndexedDB will abort transactions)
if (Services.startup.shuttingDown) {
reportStatus = UptakeTelemetry.STATUS.SHUTDOWN_ERROR;
}
// If no Telemetry status was determined yet (ie. outside sync step),
// then introspect error, default status at this step is UNKNOWN.
else if (reportStatus == null) {
reportStatus = this._telemetryFromError(e, {
default: UptakeTelemetry.STATUS.UNKNOWN_ERROR,
});
}
throw e;
} finally {
const durationMilliseconds = new Date() - startedAt;
// No error was reported, this is a success!
if (reportStatus === null) {
reportStatus = UptakeTelemetry.STATUS.SUCCESS;
}
// Report success/error status to Telemetry.
let reportArgs = {
source: this.identifier,
trigger,
duration: durationMilliseconds,
};
// In Bug 1617133, we will try to break down specific errors into
// more precise statuses by reporting the JavaScript error name
// ("TypeError", etc.) to Telemetry on Nightly.
const channel = UptakeTelemetry.Policy.getChannel();
if (
thrownError !== null &&
channel == "nightly" &&
[
UptakeTelemetry.STATUS.SYNC_ERROR,
UptakeTelemetry.STATUS.CUSTOM_1_ERROR, // IndexedDB.
UptakeTelemetry.STATUS.UNKNOWN_ERROR,
UptakeTelemetry.STATUS.SHUTDOWN_ERROR,
].includes(reportStatus)
) {
// List of possible error names for IndexedDB:
// https://searchfox.org/mozilla-central/rev/49ed791/dom/base/DOMException.cpp#28-53
reportArgs = { ...reportArgs, errorName: thrownError.name };
}
await UptakeTelemetry.report(
TELEMETRY_COMPONENT,
reportStatus,
reportArgs
);
console.debug(`${this.identifier} sync status is ${reportStatus}`);
this._syncRunning = false;
}
}
/**
* Determine the Telemetry uptake status based on the specified
* error.
*/
_telemetryFromError(e, options = { default: null }) {
let reportStatus = options.default;
if (e instanceof RemoteSettingsClient.NetworkOfflineError) {
reportStatus = UptakeTelemetry.STATUS.NETWORK_OFFLINE_ERROR;
} else if (e instanceof IDBHelpers.ShutdownError) {
reportStatus = UptakeTelemetry.STATUS.SHUTDOWN_ERROR;
} else if (/unparseable/.test(e.message)) {
reportStatus = UptakeTelemetry.STATUS.PARSE_ERROR;
} else if (/NetworkError/.test(e.message)) {
reportStatus = UptakeTelemetry.STATUS.NETWORK_ERROR;
} else if (/Timeout/.test(e.message)) {
reportStatus = UptakeTelemetry.STATUS.TIMEOUT_ERROR;
} else if (/HTTP 5??/.test(e.message)) {
reportStatus = UptakeTelemetry.STATUS.SERVER_ERROR;
} else if (/Backoff/.test(e.message)) {
reportStatus = UptakeTelemetry.STATUS.BACKOFF;
} else if (
// Errors from kinto.js IDB adapter.
e instanceof IDBHelpers.IndexedDBError ||
// Other IndexedDB errors (eg. RemoteSettingsWorker).
/IndexedDB/.test(e.message)
) {
reportStatus = UptakeTelemetry.STATUS.CUSTOM_1_ERROR;
}
return reportStatus;
}
/**
* Import the JSON files from services/settings/dump into the local DB.
*/
async _importJSONDump() {
console.info(`${this.identifier} restore dump`);
// When using the preview bucket, we still want to load the main dump.
const bucketName = this.bucketName.replace("-preview", "");
const start = Cu.now() * 1000;
const result = await RemoteSettingsWorker.importJSONDump(
bucketName,
this.collectionName
);
if (gTimingEnabled) {
const end = Cu.now() * 1000;
PerformanceCounters.storeExecutionTime(
`remotesettings/${this.identifier}`,
"importJSONDump",
end - start,
"duration"
);
}
return result;
}
/**
* Fetch the signature info from the collection metadata and verifies that the
* local set of records has the same.
*
* @param {Array<Object>} records The list of records to validate.
* @param {int} timestamp The timestamp associated with the list of remote records.
* @param {Object} metadata The collection metadata, that contains the signature payload.
* @returns {Promise}
*/
async _validateCollectionSignature(records, timestamp, metadata) {
const start = Cu.now() * 1000;
if (!metadata?.signature) {
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 },
} = metadata;
const certChain = await (await 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
))
) {
throw new InvalidSignatureError(this.identifier);
}
if (gTimingEnabled) {
const end = Cu.now() * 1000;
PerformanceCounters.storeExecutionTime(
`remotesettings/${this.identifier}`,
"validateCollectionSignature",
end - start,
"duration"
);
}
}
/**
* This method is in charge of fetching data from server, applying the diff-based
* changes to the local DB, validating the signature, and computing a synchronization
* result with the list of creation, updates, and deletions.
*
* @param {Array<Object>} localRecords Current list of records in local DB.
* @param {int} localTimestamp Current timestamp in local DB.
* @param {Object} localMetadata Current metadata in local DB.
* @param {int} expectedTimestamp Cache busting of collection metadata
* @param {Object} options
* @param {bool} options.retry Whether this method is called in the
* retry situation.
*
* @returns {Promise<Object>} the computed sync result.
*/
async _importChanges(
localRecords,
localTimestamp,
localMetadata,
expectedTimestamp,
options = {}
) {
const { retry = false } = options;
const since = retry || !localTimestamp ? undefined : `"${localTimestamp}"`;
// Fetch collection metadata and list of changes from server.
console.debug(
`${this.identifier} Fetch changes from server (expected=${expectedTimestamp}, since=${since})`
);
const {
metadata,
remoteTimestamp,
remoteRecords,
} = await this._fetchChangeset(expectedTimestamp, since);
// We build a sync result, based on remote changes.
const syncResult = {
current: localRecords,
created: [],
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;
}
// Separate tombstones from creations/updates.
const toDelete = remoteRecords.filter(r => r.deleted);
const toInsert = remoteRecords.filter(r => !r.deleted);
console.debug(
`${this.identifier} ${toDelete.length} to delete, ${toInsert.length} to insert`
);
const start = Cu.now() * 1000;
// Delete local records for each tombstone.
await this.db.deleteBulk(toDelete);
// Overwrite all other data.
await this.db.importBulk(toInsert);
await this.db.saveLastModified(remoteTimestamp);
await this.db.saveMetadata(metadata);
if (gTimingEnabled) {
const end = Cu.now() * 1000;
PerformanceCounters.storeExecutionTime(
`remotesettings/${this.identifier}`,
"loadRawData",
end - start,
"duration"
);
}
// Read the new local data, after updating.
const newLocal = await this.db.list();
const newRecords = newLocal.map(r => this._cleanLocalFields(r));
// And verify the signature on what is now stored.
if (this.verifySignature) {
try {
await this._validateCollectionSignature(
newRecords,
remoteTimestamp,
metadata
);
} catch (e) {
console.error(
`${this.identifier} Signature failed ${retry ? "again" : ""} ${e}`
);
if (!(e instanceof InvalidSignatureError)) {
// If it failed for any other kind of error (eg. shutdown)
// then give up quickly.
throw e;
}
// In order to distinguish signature errors that happen
// during sync, from hijacks of local DBs, we will verify
// the signature on the data that we had before syncing.
let localTrustworthy = false;
try {
await this._validateCollectionSignature(
localRecords,
localTimestamp,
localMetadata
);
localTrustworthy = true;
} catch (sigerr) {
if (!(sigerr instanceof InvalidSignatureError)) {
// If it fails for other reason, keep original error and give up.
throw sigerr;
}
}
// Signature failed, clear local DB because it contains
// bad data (local + remote changes).
console.debug(`${this.identifier} clear local data`);
await this.db.clear();
if (!localTrustworthy && !retry) {
// 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);
} else if (localTrustworthy) {
// Signature of data before importing changes was good.
// If we retry, we will pull and import changes again on top of them.
// If we retried already, we will restore the local data before
// throwing.
await this.db.importBulk(localRecords);
await this.db.saveLastModified(localTimestamp);
await this.db.saveMetadata(localMetadata);
} else {
// The local data was tampered.
// We retried and signature failed again.
// So restore the dump if available (no-op if no dump)
await this._importJSONDump();
}
throw e;
}
} else {
console.warn(`${this.identifier} has signature disabled`);
}
// Compute the changes, comparing records before and after.
syncResult.current = newRecords;
const oldById = new Map(localRecords.map(e => [e.id, e]));
for (const r of newRecords) {
const old = oldById.get(r.id);
if (old) {
oldById.delete(r.id);
if (r.last_modified != old.last_modified) {
syncResult.updated.push({ old, new: r });
}
} else {
syncResult.created.push(r);
}
}
syncResult.deleted = syncResult.deleted.concat(
Array.from(oldById.values())
);
console.debug(
`${this.identifier} ${syncResult.created.length} created. ${syncResult.updated.length} updated. ${syncResult.deleted.length} deleted.`
);
return syncResult;
}
/**
* Fetch information from changeset endpoint.
*
* @param expectedTimestamp cache busting value
* @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,
},
}
);
return {
remoteTimestamp,
metadata,
remoteRecords,
};
}
/**
* Use the filter func to filter the lists of changes obtained from synchronization,
* and return them along with the filtered list of local records.
*
* If the filtered lists of changes are all empty, we return null (and thus don't
* bother listing local DB).
*
* @param {Object} syncResult Synchronization result without filtering.
*
* @returns {Promise<Object>} the filtered list of local records, plus the filtered
* list of created, updated and deleted records.