Repository navigation
Expand file tree
/
Copy pathconfig-tests.js
More file actions
947 lines (873 loc) · 44.1 KB
/
Copy pathconfig-tests.js
File metadata and controls
947 lines (873 loc) · 44.1 KB
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
import { expect } from 'chai';
import fs from 'fs';
import path from 'path';
import { createValidator, formatErrors } from './schema-validation.js';
import platforms from './../platforms.js';
import { immutableJSONPatch } from 'immutable-json-patch';
import { getBaseFeatureConfigs, readJsoncFile } from '../util.js';
import { CURRENT_CONFIG_VERSION } from '../constants.js';
const platformOutput = platforms.map((item) => item.replace('browsers/', 'extension-'));
const latestVersion = `v${CURRENT_CONFIG_VERSION}`;
const previousVersion = `v${CURRENT_CONFIG_VERSION - 1}`;
const platformSpecificSchemas = {
[`${latestVersion}/android-config.json`]: 'AndroidCurrentConfig',
[`${previousVersion}/android-config.json`]: 'LegacyAndroidConfig',
};
// Test the latest 2 versions of each platform
const latestConfigs = platformOutput.map((plat) => {
return {
name: `${latestVersion}/${plat}-config.json`,
body: JSON.parse(fs.readFileSync(`./generated/${latestVersion}/${plat}-config.json`)),
};
});
const previousConfigs = platformOutput.map((plat) => {
return {
name: `${previousVersion}/${plat}-config.json`,
body: JSON.parse(fs.readFileSync(`./generated/${previousVersion}/${plat}-config.json`)),
};
});
describe('Config schema tests', () => {
const featurePlatformUsage = {};
for (const otherConfig of latestConfigs) {
for (const featureName of Object.keys(otherConfig.body.features)) {
// Skip over counting extension specific platforms
if (otherConfig.name.match(/extension-[a-z0-9]+-config/)) {
continue;
}
if (!(featureName in otherConfig.body.features)) {
continue;
}
featurePlatformUsage[featureName] = (featurePlatformUsage[featureName] || 0) + 1;
}
}
for (const config of latestConfigs) {
describe(`${config.name}`, () => {
// appTrackerProtection should only be on the Android config since it is a large feature
const shouldContainAppTP = config.name.split('/')[1] === 'android-config.json';
it('should contain appTrackerProtection or not', () => {
expect('appTrackerProtection' in config.body.features).to.be.equal(
shouldContainAppTP,
`appTrackerProtection expected: ${shouldContainAppTP}`,
);
});
it(`should validate against the full config${latestVersion.toUpperCase()} schema`, () => {
const validate = createValidator(platformSpecificSchemas[config.name] || 'CurrentGenericConfig');
expect(validate(config.body)).to.be.equal(true, formatErrors(validate.errors));
});
it('all features should be named correctly', () => {
const legacyFeatures = [
'androidBrowserConfig',
'androidNativeCrash',
'androidNewStateKillSwitch',
'windowsDownloadLink',
'windowsExternalPreviewReleases',
'windowsFireWindow',
'windowsNewTabPageExperiment',
'windowsPermissionUsage',
'windowsPrecisionScroll',
'windowsSpellChecker',
'windowsStartupBoost',
'windowsWaitlist',
'windowsWebviewFailures',
'windowsWebViewPermissionsSavesInProfile',
'macOSBrowserConfig',
'iOSBrowserConfig',
];
const deviceSpecificCheck = /(android|ios|windows|macos)/i;
const featureNameRegex = /^[a-zA-Z0-9]+$/;
for (const featureName of Object.keys(config.body.features)) {
expect(featureName).to.match(featureNameRegex);
// We can ignore legacy features and their sub-features.
if (legacyFeatures.includes(featureName)) {
continue;
}
// Otherwise, features should not have platform specific names so we can use the same config for all platforms.
expect(featureName).to.not.match(deviceSpecificCheck);
// All subfeatures should also be named correctly if not in a legacy feature
const feature = config.body.features[featureName];
if (feature.features) {
for (const subfeatureName of Object.keys(feature.features)) {
expect(subfeatureName).to.match(featureNameRegex);
expect(subfeatureName).to.not.match(deviceSpecificCheck);
}
}
}
});
it('All features should have a corresponding feature file if used in more than one platform', () => {
// Note: We should not add more to this list, only remove
const legacyFeatures = [
'webViewBlobDownload',
'experimentTest',
'eme',
'clientContentFeatures',
];
expect(featurePlatformUsage).to.be.an('object');
expect(Object.keys(featurePlatformUsage)).to.have.length.greaterThan(0);
for (const featureName of Object.keys(config.body.features)) {
// Skip over counting extension specific platforms
if (config.name.match(/extension-[a-z0-9]+-config/)) {
continue;
}
if (legacyFeatures.includes(featureName)) {
continue;
}
const dasherizedFeatureName = featureName.replace(/([a-z0-9])([A-Z0-9])/g, '$1-$2').toLowerCase();
const featureFile = `./features/${dasherizedFeatureName}.json`;
const featureFileExists = fs.existsSync(featureFile);
// Only check for other platforms if the feature file does not exist
expect(!featureFileExists && featurePlatformUsage[featureName] > 1).to.be.equal(
false,
`Feature file not found: ${featureFile} when it's used in ${config.name} and other platforms`,
);
}
});
it('All patchSettings should also be valid', () => {
const validate = createValidator(platformSpecificSchemas[config.name] || 'CurrentGenericConfig');
function applyPatchAndValidate(featureName, feature, conditionalChange, config) {
for (const change of conditionalChange) {
if (!change.patchSettings) {
continue;
}
let featureSettings = feature.settings;
featureSettings = immutableJSONPatch(featureSettings, change.patchSettings);
// Clone config and check the schema with the patched featureSettings
const clonedConfig = JSON.parse(JSON.stringify(config.body));
expect(clonedConfig.features[featureName].settings).to.not.be.equal(featureSettings);
clonedConfig.features[featureName].settings = featureSettings;
expect(validate(clonedConfig)).to.be.equal(true, formatErrors(validate.errors));
}
}
const legacyFeatures = [
'networkProtection',
];
for (const featureName of Object.keys(config.body.features)) {
// Ignore a non C-S-S feature that uses "domains"
if (legacyFeatures.includes(featureName)) {
continue;
}
const feature = config.body.features[featureName];
if (feature?.settings?.conditionalChanges) {
applyPatchAndValidate(featureName, feature, feature.settings.conditionalChanges, config);
}
if (feature?.settings?.domains) {
applyPatchAndValidate(featureName, feature, feature.settings.domains, config);
}
}
});
it('All experiment cohorts should be named correctly', () => {
const cohortNameRegex = /^[a-zA-Z0-9]+$/;
/** @type {Record<string, import('../schema/feature').GenericFeature>} */
const features = config.body.features;
for (const featureName of Object.keys(config.body.features)) {
for (const subfeatureName of Object.keys(features[featureName].features || {})) {
const subFeature = features[featureName].features[subfeatureName];
if (subFeature.cohorts) {
for (const cohort of subFeature.cohorts) {
expect(cohort.name).to.match(cohortNameRegex);
}
}
}
}
});
});
}
for (const config of previousConfigs) {
describe(`${config.name}`, () => {
// appTrackerProtection should only be on the Android config since it is a large feature
const shouldContainAppTP = config.name.split('/')[1] === 'android-config.json';
it('should contain appTrackerProtection or not', () => {
expect('appTrackerProtection' in config.body.features).to.be.equal(
shouldContainAppTP,
`appTrackerProtection expected: ${shouldContainAppTP}`,
);
});
it('should validate against the legacy schema', () => {
const validate = createValidator(platformSpecificSchemas[config.name] || 'LegacyConfig');
expect(validate(config.body)).to.be.equal(true, formatErrors(validate.errors));
});
});
}
});
describe('Config schema tests', () => {
it('All subfeatures must be defined in their overrides files if they apply', () => {
const baseFeatures = getBaseFeatureConfigs();
for (const platform of platforms) {
const dirname = import.meta.dirname;
const overrideConfig = readJsoncFile(path.join(dirname, `/../overrides/${platform}-override.json`));
// Skip over extension platforms:
if (platform.startsWith('browsers/')) {
continue;
}
for (const [
featureName,
baseFeature,
] of Object.entries(baseFeatures)) {
const overrideFeature = overrideConfig.features[featureName];
// Skip over if we have no override for this feature
if (!overrideFeature) continue;
if (!('features' in overrideFeature)) continue;
// Skip over if we have no subfeatures
if (!('features' in baseFeature)) continue;
for (const [
subFeatureName,
] of Object.entries(baseFeature.features)) {
expect(overrideFeature.features[subFeatureName]).to.be.an(
'object',
`Missing override for ${platform} ${featureName}.${subFeatureName}`,
);
}
}
}
});
});
/**
* @param {number | string} a
* @param {number | string} b
* @returns {number} negative if a < b, 0 if equal, positive if a > b
*/
function compareVersions(a, b) {
if (typeof a === 'number' && typeof b === 'number') {
return a - b;
}
const aParts = String(a).split('.').map(Number);
const bParts = String(b).split('.').map(Number);
for (let i = 0; i < Math.max(aParts.length, bParts.length); i++) {
const diff = (aParts[i] || 0) - (bParts[i] || 0);
if (diff !== 0) return diff;
}
return 0;
}
/**
* @param {Record<string, any>} features
* @returns {{ path: string, entry: Record<string, any> }[]} every feature and sub-feature
*/
function featureEntries(features) {
const entries = [];
for (const [
featureName,
feature,
] of Object.entries(features)) {
entries.push({ path: featureName, entry: feature });
for (const [
subFeatureName,
subFeature,
] of Object.entries(feature.features || {})) {
entries.push({ path: `${featureName}.${subFeatureName}`, entry: subFeature });
}
}
return entries;
}
describe('maxSupportedVersion', () => {
for (const config of latestConfigs) {
for (const { path: entryPath, entry } of featureEntries(config.body.features)) {
if (!('maxSupportedVersion' in entry) || !('minSupportedVersion' in entry)) continue;
it(`${config.name} ${entryPath} minSupportedVersion should not exceed maxSupportedVersion`, () => {
expect(compareVersions(entry.minSupportedVersion, entry.maxSupportedVersion)).to.be.at.most(
0,
`minSupportedVersion ${entry.minSupportedVersion} is above maxSupportedVersion ${entry.maxSupportedVersion}`,
);
});
}
}
for (const config of previousConfigs) {
it(`${config.name} should not contain maxSupportedVersion`, () => {
for (const { path: entryPath, entry } of featureEntries(config.body.features)) {
expect(entry, entryPath).to.not.have.property('maxSupportedVersion');
}
});
}
for (const latest of latestConfigs) {
const previous = previousConfigs.find((c) => c.name === latest.name.replace(latestVersion, previousVersion));
it(`${previous?.name} should disable features that set maxSupportedVersion in ${latest.name}`, () => {
for (const { path: entryPath, entry } of featureEntries(latest.body.features)) {
if (!('maxSupportedVersion' in entry)) continue;
const [
featureName,
subFeatureName,
] = entryPath.split('.');
const feature = previous?.body.features[featureName];
const previousEntry = subFeatureName ? feature?.features?.[subFeatureName] : feature;
// End-of-life features are absent from older versions entirely.
if (!previousEntry) continue;
expect(previousEntry.state, entryPath).to.equal('disabled');
}
});
}
});
// `immediate_v2` fires per de-duplicated delivery and `immediate` per raw occurrence, so clients
// must not treat them as aliases — but every validation rule below applies to both.
const IMMEDIATE_TRIGGER_TYPES = [
'immediate_v2',
'immediate',
];
const isImmediateTriggerType = (type) => IMMEDIATE_TRIGGER_TYPES.includes(type);
describe('EventHub validation tests', () => {
for (const config of latestConfigs) {
const eventHub = /** @type {import('../schema/features/event-hub').EventHubFeature<number> | undefined} */ (
config.body.features?.eventHub
);
if (!eventHub?.settings?.telemetry) continue;
const telemetry = eventHub.settings.telemetry;
describe(`${config.name} eventHub`, () => {
it('telemetry entry names should be valid pixel names', () => {
// Segments of [a-zA-Z][a-zA-Z0-9]* separated by underscores,
// e.g. "webTelemetry_adwalls_day" (at least two segments must
// be specified)
const pixelNameRegex = /^[a-zA-Z][a-zA-Z0-9]*(_[a-zA-Z][a-zA-Z0-9]*)+$/;
for (const name of Object.keys(telemetry)) {
expect(name).to.match(
pixelNameRegex,
`Telemetry name '${name}' is not a valid pixel name (must match ${pixelNameRegex})`,
);
}
});
it('trigger must be a valid period or immediate trigger', () => {
for (const [
name,
entry,
] of Object.entries(telemetry)) {
const trigger = entry.trigger;
expect(trigger).to.be.an('object', `Telemetry '${name}' is missing trigger`);
// `type` is optional and defaults to 'period'.
const type = trigger.type ?? 'period';
expect(type).to.be.oneOf(
[
'period',
...IMMEDIATE_TRIGGER_TYPES,
],
`Telemetry '${name}' has invalid trigger.type '${trigger.type}'`,
);
if (isImmediateTriggerType(type)) {
// Immediate triggers fire per event: no period, and a `source` naming the event.
expect(trigger.period, `Immediate telemetry '${name}' must not specify a period`).to.equal(undefined);
expect(trigger.source, `Immediate telemetry '${name}' source must be a string`).to.be.a('string');
expect(trigger.source.length, `Immediate telemetry '${name}' source must not be empty`).to.be.greaterThan(0);
} else {
// Period triggers carry a period and no trigger-level source.
expect(trigger.period, `Period telemetry '${name}' is missing trigger.period`).to.be.an('object');
expect(trigger.source, `Period telemetry '${name}' must not specify a trigger-level source`).to.equal(undefined);
}
}
});
// A client skips an immediate trigger name it does not parse, dropping the pixel. Apple
// parses only `immediate_v2`, which the build emits; Windows parses only `immediate`.
const unparsedImmediateType = {
'ios-config.json': 'immediate',
'macos-config.json': 'immediate',
'windows-config.json': 'immediate_v2',
}[config.name.split('/').pop() ?? ''];
if (unparsedImmediateType) {
it(`immediate triggers must not use '${unparsedImmediateType}', which this platform skips`, () => {
for (const [
name,
entry,
] of Object.entries(telemetry)) {
expect(entry.trigger.type).to.not.equal(
unparsedImmediateType,
`Telemetry '${name}' uses trigger.type '${unparsedImmediateType}', which this platform skips`,
);
}
});
}
it('each telemetry entry declares a parameters object, and non-immediate entries have at least one', () => {
for (const [
name,
entry,
] of Object.entries(telemetry)) {
const params = entry.parameters;
expect(params).to.be.an('object', `Telemetry '${name}' is missing parameters`);
// Immediate pixels fire once per event and may legitimately carry no parameters (e.g. a
// per-provider captcha pixel, where the provider is the pixel itself). Skip the check only
// for immediate triggers rather than matching on 'period', so any future trigger type is
// still required to carry at least one parameter until it's explicitly exempted here.
if (!isImmediateTriggerType(entry.trigger.type ?? 'period')) {
expect(Object.keys(params).length).to.be.greaterThan(
0,
`Non-immediate telemetry '${name}' must have at least one parameter`,
);
}
}
});
// Partition entries by trigger type once, defaulting a missing type to 'period' (the
// back-compat default). Grouping the type-specific checks under these buckets means each
// check only iterates the entries it applies to, and a future trigger type cannot slip
// through a period-only check (as it would with an `=== 'immediate'` skip guard).
const periodEntries = Object.entries(telemetry).filter(
([
,
entry,
]) => (entry.trigger.type ?? 'period') === 'period',
);
const immediateEntries = Object.entries(telemetry).filter(
([
,
entry,
]) => isImmediateTriggerType(entry.trigger.type),
);
describe('period telemetry entries', () => {
it('trigger period must specify at least one non-negative time unit', () => {
const timeUnits = [
'seconds',
'minutes',
'hours',
'days',
];
for (const [
name,
entry,
] of periodEntries) {
const period = entry.trigger.period;
expect(period).to.be.an('object', `Telemetry '${name}' is missing trigger.period`);
const hasTimeUnit = timeUnits.some((unit) => unit in period);
expect(hasTimeUnit).to.equal(
true,
`Telemetry '${name}' period must specify at least one of: ${timeUnits.join(', ')}`,
);
for (const unit of timeUnits) {
if (unit in period) {
expect(period[unit]).to.be.at.least(0, `Telemetry '${name}' period.${unit} must not be negative`);
}
}
}
});
it('total trigger period must be greater than zero', () => {
for (const [
name,
entry,
] of periodEntries) {
const period = entry.trigger.period;
const totalSeconds =
(period.seconds || 0) + (period.minutes || 0) * 60 + (period.hours || 0) * 3600 + (period.days || 0) * 86400;
expect(totalSeconds).to.be.greaterThan(
0,
`Telemetry '${name}' total period is ${totalSeconds}s — must be greater than zero`,
);
}
});
// Clients read an integer `trigger.period.seconds` and ignore days/hours/minutes, so
// config generation must collapse any authored unit object to a single integer `seconds`.
it('trigger period must be collapsed to a single integer seconds value', () => {
for (const [
name,
entry,
] of periodEntries) {
const period = entry.trigger.period;
expect(Object.keys(period)).to.deep.equal(
[
'seconds',
],
`Telemetry '${name}' period must be collapsed to only { seconds }, got: ${JSON.stringify(period)}`,
);
expect(Number.isInteger(period.seconds)).to.equal(
true,
`Telemetry '${name}' period.seconds must be an integer, got: ${period.seconds}`,
);
expect(period.seconds).to.be.greaterThan(0, `Telemetry '${name}' period.seconds must be greater than zero`);
}
});
});
describe('immediate telemetry entries', () => {
// The counter template aggregates a count across a window, which is meaningless for a
// pixel that fires once per event. Disallow it on immediate triggers for now.
it('must not use counter parameters', () => {
for (const [
name,
entry,
] of immediateEntries) {
for (const [
paramName,
param,
] of Object.entries(entry.parameters || {})) {
expect(param.template).to.not.equal(
'counter',
`Immediate telemetry '${name}' parameter '${paramName}' must not use the 'counter' template`,
);
}
}
});
});
// `eventHub_baseline_*` pixels fire purely on their period to
// provide a baseline / denominator: the `baseline` parameter is a
// counter sourced from an empty "baseline" stream, so its count
// stays at 0 and the single unbounded `0+` bucket always matches.
// For now these pixels may carry no other parameters.
const BASELINE_NAME_PREFIX = 'eventHub_baseline_';
describe('baseline telemetry entries', () => {
it('eventHub_baseline_* pixels may only declare the baseline parameter', () => {
for (const [
name,
entry,
] of Object.entries(telemetry)) {
if (!name.startsWith(BASELINE_NAME_PREFIX)) continue;
const paramNames = Object.keys(entry.parameters || {});
expect(paramNames).to.deep.equal(
[
'baseline',
],
`Baseline pixel '${name}' may only declare the 'baseline' parameter (no other parameters allowed for now), got: ${paramNames.join(', ')}`,
);
}
});
it('the baseline parameter is a counter sourced from "baseline" (fired even if no detector emits it)', () => {
for (const [
name,
entry,
] of Object.entries(telemetry)) {
if (!name.startsWith(BASELINE_NAME_PREFIX)) continue;
const param = (entry.parameters || {}).baseline;
expect(param, `Baseline pixel '${name}' must declare a 'baseline' parameter`).to.be.an('object');
expect(param.template).to.equal(
'counter',
`Baseline pixel '${name}' baseline parameter must use the 'counter' template`,
);
expect(param.source).to.equal('baseline', `Baseline pixel '${name}' baseline parameter source must be 'baseline'`);
expect(param.buckets).to.deep.equal(
{ '0+': { gte: 0 } },
`Baseline pixel '${name}' baseline parameter buckets must be exactly 0+`,
);
}
});
});
for (const [
entryName,
entry,
] of Object.entries(telemetry)) {
for (const [
paramName,
param,
] of Object.entries(entry.parameters || {})) {
describe(`${entryName}.${paramName}`, () => {
const isImmediateTrigger = isImmediateTriggerType(entry.trigger?.type);
if (param.template === 'data' && isImmediateTrigger) {
// Immediate-trigger data params forward the triggering event's payload; the
// event stream is named by the trigger's `source`, so a param-level `source`
// is disallowed.
it('source must be omitted on immediate-trigger data params', () => {
expect(
param.source,
`Parameter '${entryName}.${paramName}' must not specify source on an immediate trigger`,
).to.equal(undefined);
});
} else {
// Counter params and period data params identify their event stream via `source`.
it('source should be a non-empty string', () => {
expect(param.source).to.be.a('string', `Parameter '${entryName}.${paramName}' source must be a string`);
expect(param.source.length).to.be.greaterThan(
0,
`Parameter '${entryName}.${paramName}' source must not be empty`,
);
});
}
// Only the "counter" template defines buckets; other templates (e.g. "data",
// which forwards a value from the event payload) carry none, so skip the
// bucket-schema checks below for them.
if (param.template !== 'counter') {
if (param.template === 'data') {
it('dataKey should be a non-empty string', () => {
expect(param.dataKey).to.be.a(
'string',
`Parameter '${entryName}.${paramName}' dataKey must be a string`,
);
expect(param.dataKey.length).to.be.greaterThan(
0,
`Parameter '${entryName}.${paramName}' dataKey must not be empty`,
);
});
}
return;
}
it('buckets should not be empty', () => {
expect(param.buckets).to.be.an('object', `Parameter '${entryName}.${paramName}' buckets must be an object`);
const bucketNames = Object.keys(param.buckets);
expect(bucketNames.length).to.be.greaterThan(
0,
`Parameter '${entryName}.${paramName}' buckets must not be empty`,
);
});
it('lt must be greater than gte', () => {
for (const [
name,
bucket,
] of Object.entries(param.buckets)) {
if (bucket.lt !== undefined) {
expect(bucket.lt).to.be.greaterThan(
bucket.gte,
`Bucket '${name}' lt (${bucket.lt}) must be greater than gte (${bucket.gte})`,
);
}
}
});
it('every lt must match another bucket gte (no gaps)', () => {
const gteValues = new Set(Object.values(param.buckets).map((b) => b.gte));
for (const [
name,
bucket,
] of Object.entries(param.buckets)) {
if (bucket.lt !== undefined) {
expect(gteValues.has(bucket.lt)).to.equal(
true,
`Bucket '${name}' lt (${bucket.lt}) does not match any bucket's gte`,
);
}
}
});
it('gte values must be unique across buckets', () => {
const seen = new Set();
for (const [
name,
bucket,
] of Object.entries(param.buckets)) {
expect(seen.has(bucket.gte)).to.equal(false, `Duplicate gte value ${bucket.gte} in bucket '${name}'`);
seen.add(bucket.gte);
}
});
it('lt values must be unique across buckets', () => {
const seen = new Set();
for (const [
name,
bucket,
] of Object.entries(param.buckets)) {
if (bucket.lt !== undefined) {
expect(seen.has(bucket.lt)).to.equal(false, `Duplicate lt value ${bucket.lt} in bucket '${name}'`);
seen.add(bucket.lt);
}
}
});
it('should have at most one unbounded bucket (missing lt)', () => {
const unbounded = Object.entries(param.buckets).filter(
([
,
b,
]) => b.lt === undefined,
);
expect(unbounded.length).to.be.at.most(
1,
`Found ${unbounded.length} unbounded buckets: ${unbounded
.map(
([
n,
]) => n,
)
.join(', ')}`,
);
});
});
}
}
});
}
});
describe('EventHub telemetry override merge', () => {
// Windows declares only its platform-specific telemetry entries in its override; the build
// must merge in the base event-hub entries so the platform does not drift as base entries change.
const windowsConfig = latestConfigs.find((c) => c.name === `${latestVersion}/windows-config.json`);
const telemetry = windowsConfig?.body?.features?.eventHub?.settings?.telemetry || {};
const baseTelemetry = readJsoncFile('./features/event-hub.json').settings.telemetry;
it('inherits base telemetry entries not declared in the windows override', () => {
for (const baseName of Object.keys(baseTelemetry)) {
expect(telemetry, `Windows eventHub telemetry is missing inherited base entry '${baseName}'`).to.have.property(baseName);
}
});
it('keeps windows-specific telemetry entries', () => {
expect(telemetry).to.have.property('webTelemetry_youtube_videoAd_day');
});
});
describe('webInterferenceDetection interferenceTypes override merge', () => {
// Android declares only its platform-specific interference types in its override; the build
// must merge in the base types so the platform does not drift as base types change.
const androidConfig = latestConfigs.find((c) => c.name === `${latestVersion}/android-config.json`);
const interferenceTypes = androidConfig?.body?.features?.webInterferenceDetection?.settings?.interferenceTypes || {};
const baseInterferenceTypes = readJsoncFile('./features/web-interference-detection.json').settings.interferenceTypes;
it('inherits base interference types not declared in the android override', () => {
for (const baseName of Object.keys(baseInterferenceTypes)) {
expect(interferenceTypes, `Android webInterferenceDetection is missing inherited base type '${baseName}'`).to.have.property(
baseName,
);
}
});
it('keeps android-specific interference types', () => {
expect(interferenceTypes).to.have.property('youtubeAds');
});
});
describe('dbp revokedBundleSigningKeys', () => {
// Platform overrides of dbp.settings replace the base settings, so a key revoked in features/dbp.json
// must also be copied into any override that sets dbp.settings.
const baseRevokedKeys = readJsoncFile('./features/dbp.json').settings.revokedBundleSigningKeys;
for (const config of [
...latestConfigs,
...previousConfigs,
]) {
it(`${config.name} has exactly the revoked keys in features/dbp.json`, () => {
const revokedKeys = config.body.features.dbp?.settings?.revokedBundleSigningKeys || [];
expect(revokedKeys).to.have.members(baseRevokedKeys, `${config.name} revokedBundleSigningKeys`);
});
}
});
describe('Web detection detector schema', () => {
const validate = createValidator('DetectorConfig');
const images = { element: { selector: 'img' } };
const report = { breakageReportData: {} };
it('accepts self, with a path or a body, and {} for the bound value', () => {
const detector = {
match: {
...images,
using: {
api: {
path: 'Math.max.apply',
args: [
null,
{ self: {} },
],
},
},
is: { gt: { self: 'length' } },
},
actions: report,
};
expect(validate(detector), formatErrors(validate.errors)).to.equal(true);
});
it('accepts using as an expression over self', () => {
const detector = {
match: {
api: 'document',
using: {
div: [
{ self: 'title.length' },
{ self: { path: 'fonts.size' } },
],
},
is: { gt: 0 },
},
actions: report,
};
expect(validate(detector), formatErrors(validate.errors)).to.equal(true);
});
it('accepts self in the arguments of a field expression', () => {
const detector = {
match: {
element: {
selector: 'img',
field: {
api: {
path: 'Math.min',
args: [
{ self: 'naturalWidth' },
2000,
],
},
},
},
is: {},
},
actions: report,
};
expect(validate(detector), formatErrors(validate.errors)).to.equal(true);
});
it('accepts actions as a sequence of expressions: if, define, payloads and detector names', () => {
const detector = {
state: 'disabled',
actions: [
{ define: { n: { ...images, using: 'length' } } },
{ breakageReportData: { data: { n: { value: { ref: 'n' } } } } },
{
if: {
all: [
{ ref: 'n', is: { gte: 3 } },
{
none: [
{ ref: 'this.sent', is: true },
],
},
],
},
then: [
{ fireEvent: { type: 'manyImages' } },
{ define: { 'this.sent': true } },
],
else: { define: { few: true } },
},
],
};
expect(validate(detector), formatErrors(validate.errors)).to.equal(true);
});
it('accepts `match` with one object of several actions', () => {
expect(
validate({ match: images, actions: { fireEvent: { type: 'a' }, breakageReportData: {} } }),
formatErrors(validate.errors),
).to.equal(true);
});
it('accepts several expression keys beside `using` and `is`', () => {
const detector = {
match: { ...images, api: 'document.images', using: 'length', is: { gt: 0 } },
actions: report,
};
expect(validate(detector), formatErrors(validate.errors)).to.equal(true);
});
it('accepts `actions` without `match`', () => {
expect(validate({ actions: report }), formatErrors(validate.errors)).to.equal(true);
});
it('rejects a detector without `actions`, an unknown key, a key of another kind beside an action, and `state` on an action', () => {
expect(validate({ match: images })).to.equal(false);
expect(validate({ match: images, actions: report, when: images })).to.equal(false);
expect(validate({ actions: { fireEvent: { type: 'a' }, api: 'document' } })).to.equal(false);
expect(validate({ actions: { fireEvent: { type: 'a' }, is: true } })).to.equal(false);
expect(validate({ actions: { define: { n: 1 }, using: 'length' } })).to.equal(false);
expect(validate({ actions: { fireEvent: { type: 'a', state: 'enabled' } } })).to.equal(false);
});
});
describe('EventHub schema source rules', () => {
const validate = createValidator('EventHubSettings');
const periodEntry = (param) => ({
telemetry: {
test_pixel_day: {
state: 'enabled',
trigger: { period: { seconds: 86400 } },
parameters: { value: param },
},
},
});
const immediateEntry = (param, type = 'immediate_v2') => ({
telemetry: {
test_pixel_immediate: {
state: 'enabled',
trigger: { type, source: 'someEvent' },
parameters: { value: param },
},
},
});
const baselineEntry = (name) => ({
telemetry: {
[name]: {
state: 'enabled',
trigger: { period: { seconds: 86400 } },
parameters: { baseline: { template: 'counter', source: 'baseline', buckets: { '0+': { gte: 0 } } } },
},
},
});
it('accepts a period data param that specifies a source', () => {
const settings = periodEntry({ template: 'data', source: 'someStream', dataKey: 'loginState' });
expect(validate(settings), formatErrors(validate.errors)).to.equal(true);
});
it('rejects a period data param that omits its source', () => {
const settings = periodEntry({ template: 'data', dataKey: 'loginState' });
expect(validate(settings)).to.equal(false);
});
it('accepts an immediate data param that omits its source', () => {
const settings = immediateEntry({ template: 'data', dataKey: 'loginState' });
expect(validate(settings), formatErrors(validate.errors)).to.equal(true);
});
it('accepts both immediate trigger spellings', () => {
for (const type of IMMEDIATE_TRIGGER_TYPES) {
const settings = immediateEntry({ template: 'data', dataKey: 'loginState' }, type);
expect(validate(settings), formatErrors(validate.errors)).to.equal(true);
}
});
it('rejects an unknown immediate trigger spelling', () => {
const settings = immediateEntry({ template: 'data', dataKey: 'loginState' }, 'immediate_v3');
expect(validate(settings)).to.equal(false);
});
it('accepts an eventHub_baseline_* pixel whose baseline counter has no matching detector source', () => {
const settings = baselineEntry('eventHub_baseline_day');
expect(validate(settings), formatErrors(validate.errors)).to.equal(true);
});
});