summaryrefslogtreecommitdiffstats
path: root/toolkit/components/extensions/test/xpcshell/test_ext_userScripts_exports.js
blob: d6aa7a038c42b02bf32db49dd6db1db558651ee3 (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
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
"use strict";

const { createAppInfo } = AddonTestUtils;

AddonTestUtils.init(this);

createAppInfo("xpcshell@tests.mozilla.org", "XPCShell", "1", "49");

const server = createHttpServer();
server.registerDirectory("/data/", do_get_file("data"));

const BASE_URL = `http://localhost:${server.identity.primaryPort}/data`;

// A small utility function used to test the expected behaviors of the userScripts API method
// wrapper.
async function test_userScript_APIMethod({
  apiScript,
  userScript,
  userScriptMetadata,
  testFn,
  runtimeMessageListener,
}) {
  async function backgroundScript(
    userScriptFn,
    scriptMetadata,
    messageListener
  ) {
    await browser.userScripts.register({
      js: [
        {
          code: `(${userScriptFn})();`,
        },
      ],
      runAt: "document_end",
      matches: ["http://localhost/*/file_sample.html"],
      scriptMetadata,
    });

    if (messageListener) {
      browser.runtime.onMessage.addListener(messageListener);
    }

    browser.test.sendMessage("background-ready");
  }

  function notifyFinish(failureReason) {
    browser.test.assertEq(
      undefined,
      failureReason,
      "should be completed without errors"
    );
    browser.test.sendMessage("test_userScript_APIMethod:done");
  }

  function assertTrue(val, message) {
    browser.test.assertTrue(val, message);
    if (!val) {
      browser.test.sendMessage("test_userScript_APIMethod:done");
      throw message;
    }
  }

  let extension = ExtensionTestUtils.loadExtension({
    manifest: {
      permissions: ["http://localhost/*/file_sample.html"],
      user_scripts: {
        api_script: "api-script.js",
      },
    },
    // Defines a background script that receives all the needed test parameters.
    background: `
        const metadata = ${JSON.stringify(userScriptMetadata)};
        (${backgroundScript})(${userScript}, metadata, ${runtimeMessageListener})
     `,
    files: {
      "api-script.js": `(${apiScript})({
        assertTrue: ${assertTrue},
        notifyFinish: ${notifyFinish}
      })`,
    },
  });

  // Load a page in a content process, register the user script and then load a
  // new page in the existing content process.
  let url = `${BASE_URL}/file_sample.html`;
  let contentPage = await ExtensionTestUtils.loadContentPage(`about:blank`);

  await extension.startup();
  await extension.awaitMessage("background-ready");
  await contentPage.loadURL(url);

  // Run any additional test-specific assertions.
  if (testFn) {
    await testFn({ extension, contentPage, url });
  }

  await extension.awaitMessage("test_userScript_APIMethod:done");

  await extension.unload();
  await contentPage.close();
}

add_task(async function test_apiScript_exports_simple_sync_method() {
  function apiScript(sharedTestAPIMethods) {
    browser.userScripts.onBeforeScript.addListener(script => {
      const scriptMetadata = script.metadata;

      script.defineGlobals({
        ...sharedTestAPIMethods,
        testAPIMethod(
          stringParam,
          numberParam,
          boolParam,
          nullParam,
          undefinedParam,
          arrayParam
        ) {
          browser.test.assertEq(
            "test-user-script-exported-apis",
            scriptMetadata.name,
            "Got the expected value for a string scriptMetadata property"
          );
          browser.test.assertEq(
            null,
            scriptMetadata.nullProperty,
            "Got the expected value for a null scriptMetadata property"
          );
          browser.test.assertTrue(
            scriptMetadata.arrayProperty &&
              scriptMetadata.arrayProperty.length === 1 &&
              scriptMetadata.arrayProperty[0] === "el1",
            "Got the expected value for an array scriptMetadata property"
          );
          browser.test.assertTrue(
            scriptMetadata.objectProperty &&
              scriptMetadata.objectProperty.nestedProp === "nestedValue",
            "Got the expected value for an object scriptMetadata property"
          );

          browser.test.assertEq(
            "param1",
            stringParam,
            "Got the expected string parameter value"
          );
          browser.test.assertEq(
            123,
            numberParam,
            "Got the expected number parameter value"
          );
          browser.test.assertEq(
            true,
            boolParam,
            "Got the expected boolean parameter value"
          );
          browser.test.assertEq(
            null,
            nullParam,
            "Got the expected null parameter value"
          );
          browser.test.assertEq(
            undefined,
            undefinedParam,
            "Got the expected undefined parameter value"
          );

          browser.test.assertEq(
            3,
            arrayParam.length,
            "Got the expected length on the array param"
          );
          browser.test.assertTrue(
            arrayParam.includes(1),
            "Got the expected result when calling arrayParam.includes"
          );

          return "returned_value";
        },
      });
    });
  }

  function userScript() {
    const { assertTrue, notifyFinish, testAPIMethod } = this;

    // Redefine the includes method on the Array prototype, to explicitly verify that the method
    // redefined in the userScript is not used when accessing arrayParam.includes from the API script.
    // eslint-disable-next-line no-extend-native
    Array.prototype.includes = () => {
      throw new Error("Unexpected prototype leakage");
    };
    const arrayParam = new Array(1, 2, 3); // eslint-disable-line no-array-constructor
    const result = testAPIMethod(
      "param1",
      123,
      true,
      null,
      undefined,
      arrayParam
    );

    assertTrue(
      result === "returned_value",
      `userScript got an unexpected result value: ${result}`
    );

    notifyFinish();
  }

  const userScriptMetadata = {
    name: "test-user-script-exported-apis",
    arrayProperty: ["el1"],
    objectProperty: { nestedProp: "nestedValue" },
    nullProperty: null,
  };

  await test_userScript_APIMethod({
    userScript,
    apiScript,
    userScriptMetadata,
  });
});

add_task(async function test_apiScript_async_method() {
  function apiScript(sharedTestAPIMethods) {
    browser.userScripts.onBeforeScript.addListener(script => {
      script.defineGlobals({
        ...sharedTestAPIMethods,
        testAPIMethod(param, cb, cb2) {
          browser.test.assertEq(
            "function",
            typeof cb,
            "Got a callback function parameter"
          );
          browser.test.assertTrue(
            cb === cb2,
            "Got the same cloned function for the same function parameter"
          );

          browser.runtime.sendMessage(param).then(bgPageRes => {
            const cbResult = cb(script.export(bgPageRes));
            browser.test.sendMessage("user-script-callback-return", cbResult);
          });

          return "resolved_value";
        },
      });
    });
  }

  async function userScript() {
    // Redefine Promise to verify that it doesn't break the WebExtensions internals
    // that are going to use them.
    const { Promise } = this;
    Promise.resolve = function () {
      throw new Error("Promise.resolve poisoning");
    };
    this.Promise = function () {
      throw new Error("Promise constructor poisoning");
    };

    const { assertTrue, notifyFinish, testAPIMethod } = this;

    const cb = cbParam => {
      return `callback param: ${JSON.stringify(cbParam)}`;
    };
    const cb2 = cb;
    const asyncAPIResult = await testAPIMethod("param3", cb, cb2);

    assertTrue(
      asyncAPIResult === "resolved_value",
      `userScript got an unexpected resolved value: ${asyncAPIResult}`
    );

    notifyFinish();
  }

  async function runtimeMessageListener(param) {
    if (param !== "param3") {
      browser.test.fail(`Got an unexpected message: ${param}`);
    }

    return { bgPageReply: true };
  }

  await test_userScript_APIMethod({
    userScript,
    apiScript,
    runtimeMessageListener,
    async testFn({ extension }) {
      const res = await extension.awaitMessage("user-script-callback-return");
      equal(
        res,
        `callback param: ${JSON.stringify({ bgPageReply: true })}`,
        "Got the expected userScript callback return value"
      );
    },
  });
});

add_task(async function test_apiScript_method_with_webpage_objects_params() {
  function apiScript(sharedTestAPIMethods) {
    browser.userScripts.onBeforeScript.addListener(script => {
      script.defineGlobals({
        ...sharedTestAPIMethods,
        testAPIMethod(windowParam, documentParam) {
          browser.test.assertEq(
            window,
            windowParam,
            "Got a reference to the native window as first param"
          );
          browser.test.assertEq(
            window.document,
            documentParam,
            "Got a reference to the native document as second param"
          );

          // Return an uncloneable webpage object, which checks that if the returned object is from a principal
          // that is subsumed by the userScript sandbox principal, it is returned without being cloned.
          return windowParam;
        },
      });
    });
  }

  async function userScript() {
    const { assertTrue, notifyFinish, testAPIMethod } = this;

    const result = testAPIMethod(window, document);

    // We expect the returned value to be the uncloneable window object.
    assertTrue(
      result === window,
      `userScript got an unexpected returned value: ${result}`
    );
    notifyFinish();
  }

  await test_userScript_APIMethod({
    userScript,
    apiScript,
  });
});

add_task(async function test_apiScript_method_got_param_with_methods() {
  function apiScript(sharedTestAPIMethods) {
    browser.userScripts.onBeforeScript.addListener(script => {
      const scriptGlobal = script.global;
      const ScriptFunction = scriptGlobal.Function;

      script.defineGlobals({
        ...sharedTestAPIMethods,
        testAPIMethod(objWithMethods) {
          browser.test.assertEq(
            "objPropertyValue",
            objWithMethods && objWithMethods.objProperty,
            "Got the expected property on the object passed as a parameter"
          );
          browser.test.assertEq(
            undefined,
            objWithMethods?.objMethod,
            "XrayWrapper should deny access to a callable property"
          );

          browser.test.assertTrue(
            objWithMethods &&
              objWithMethods.wrappedJSObject &&
              objWithMethods.wrappedJSObject.objMethod instanceof
                ScriptFunction.wrappedJSObject,
            "The callable property is accessible on the wrappedJSObject"
          );

          browser.test.assertEq(
            "objMethodResult: p1",
            objWithMethods &&
              objWithMethods.wrappedJSObject &&
              objWithMethods.wrappedJSObject.objMethod("p1"),
            "Got the expected result when calling the method on the wrappedJSObject"
          );
          return true;
        },
      });
    });
  }

  async function userScript() {
    const { assertTrue, notifyFinish, testAPIMethod } = this;

    let result = testAPIMethod({
      objProperty: "objPropertyValue",
      objMethod(param) {
        return `objMethodResult: ${param}`;
      },
    });

    assertTrue(
      result === true,
      `userScript got an unexpected returned value: ${result}`
    );
    notifyFinish();
  }

  await test_userScript_APIMethod({
    userScript,
    apiScript,
  });
});

add_task(async function test_apiScript_method_throws_errors() {
  function apiScript({ notifyFinish }) {
    let proxyTrapsCount = 0;

    browser.userScripts.onBeforeScript.addListener(script => {
      const scriptGlobals = {
        Error: script.global.Error,
        TypeError: script.global.TypeError,
        Proxy: script.global.Proxy,
      };

      script.defineGlobals({
        notifyFinish,
        testAPIMethod(errorTestName, returnRejectedPromise) {
          let err;

          switch (errorTestName) {
            case "apiScriptError":
              err = new Error(`${errorTestName} message`);
              break;
            case "apiScriptThrowsPlainString":
              err = `${errorTestName} message`;
              break;
            case "apiScriptThrowsNull":
              err = null;
              break;
            case "userScriptError":
              err = new scriptGlobals.Error(`${errorTestName} message`);
              break;
            case "userScriptTypeError":
              err = new scriptGlobals.TypeError(`${errorTestName} message`);
              break;
            case "userScriptProxyObject":
              let proxyTarget = script.export({
                name: "ProxyObject",
                message: "ProxyObject message",
              });
              let proxyHandlers = script.export({
                get(target, prop) {
                  proxyTrapsCount++;
                  switch (prop) {
                    case "name":
                      return "ProxyObjectGetName";
                    case "message":
                      return "ProxyObjectGetMessage";
                  }
                  return undefined;
                },
                getPrototypeOf() {
                  proxyTrapsCount++;
                  return scriptGlobals.TypeError;
                },
              });
              err = new scriptGlobals.Proxy(proxyTarget, proxyHandlers);
              break;
            default:
              browser.test.fail(`Unknown ${errorTestName} error testname`);
              return undefined;
          }

          if (returnRejectedPromise) {
            return Promise.reject(err);
          }

          throw err;
        },
        assertNoProxyTrapTriggered() {
          browser.test.assertEq(
            0,
            proxyTrapsCount,
            "Proxy traps should not be triggered"
          );
        },
        resetProxyTrapCounter() {
          proxyTrapsCount = 0;
        },
        sendResults(results) {
          browser.test.sendMessage("test-results", results);
        },
      });
    });
  }

  async function userScript() {
    const {
      assertNoProxyTrapTriggered,
      notifyFinish,
      resetProxyTrapCounter,
      sendResults,
      testAPIMethod,
    } = this;

    let apiThrowResults = {};
    let apiThrowTestCases = [
      "apiScriptError",
      "apiScriptThrowsPlainString",
      "apiScriptThrowsNull",
      "userScriptError",
      "userScriptTypeError",
      "userScriptProxyObject",
    ];
    for (let errorTestName of apiThrowTestCases) {
      try {
        testAPIMethod(errorTestName);
      } catch (err) {
        // We expect that no proxy traps have been triggered by the WebExtensions internals.
        if (errorTestName === "userScriptProxyObject") {
          assertNoProxyTrapTriggered();
        }

        if (err instanceof Error) {
          apiThrowResults[errorTestName] = {
            name: err.name,
            message: err.message,
          };
        } else {
          apiThrowResults[errorTestName] = {
            name: err && err.name,
            message: err && err.message,
            typeOf: typeof err,
            value: err,
          };
        }
      }
    }

    sendResults(apiThrowResults);

    resetProxyTrapCounter();

    let apiRejectsResults = {};
    for (let errorTestName of apiThrowTestCases) {
      try {
        await testAPIMethod(errorTestName, true);
      } catch (err) {
        // We expect that no proxy traps have been triggered by the WebExtensions internals.
        if (errorTestName === "userScriptProxyObject") {
          assertNoProxyTrapTriggered();
        }

        if (err instanceof Error) {
          apiRejectsResults[errorTestName] = {
            name: err.name,
            message: err.message,
          };
        } else {
          apiRejectsResults[errorTestName] = {
            name: err && err.name,
            message: err && err.message,
            typeOf: typeof err,
            value: err,
          };
        }
      }
    }

    sendResults(apiRejectsResults);

    notifyFinish();
  }

  await test_userScript_APIMethod({
    userScript,
    apiScript,
    async testFn({ extension }) {
      const expectedResults = {
        // Any error not explicitly raised as a userScript objects or error instance is
        // expected to be turned into a generic error message.
        apiScriptError: {
          name: "Error",
          message: "An unexpected apiScript error occurred",
        },

        // When the api script throws a primitive value, we expect to receive it unmodified on
        // the userScript side.
        apiScriptThrowsPlainString: {
          typeOf: "string",
          value: "apiScriptThrowsPlainString message",
          name: undefined,
          message: undefined,
        },
        apiScriptThrowsNull: {
          typeOf: "object",
          value: null,
          name: undefined,
          message: undefined,
        },

        // Error messages that the apiScript has explicitly created as userScript's Error
        // global instances are expected to be passing through unmodified.
        userScriptError: { name: "Error", message: "userScriptError message" },
        userScriptTypeError: {
          name: "TypeError",
          message: "userScriptTypeError message",
        },

        // Error raised from the apiScript as userScript proxy objects are expected to
        // be passing through unmodified.
        userScriptProxyObject: {
          typeOf: "object",
          name: "ProxyObjectGetName",
          message: "ProxyObjectGetMessage",
        },
      };

      info(
        "Checking results from errors raised from an apiScript exported function"
      );

      const apiThrowResults = await extension.awaitMessage("test-results");

      for (let [key, expected] of Object.entries(expectedResults)) {
        Assert.deepEqual(
          apiThrowResults[key],
          expected,
          `Got the expected error object for test case "${key}"`
        );
      }

      Assert.deepEqual(
        Object.keys(expectedResults).sort(),
        Object.keys(apiThrowResults).sort(),
        "the expected and actual test case names matches"
      );

      info(
        "Checking expected results from errors raised from an apiScript exported function"
      );

      // Verify expected results from rejected promises returned from an apiScript exported function.
      const apiThrowRejections = await extension.awaitMessage("test-results");

      for (let [key, expected] of Object.entries(expectedResults)) {
        Assert.deepEqual(
          apiThrowRejections[key],
          expected,
          `Got the expected rejected object for test case "${key}"`
        );
      }

      Assert.deepEqual(
        Object.keys(expectedResults).sort(),
        Object.keys(apiThrowRejections).sort(),
        "the expected and actual test case names matches"
      );
    },
  });
});

add_task(
  async function test_apiScript_method_ensure_xraywrapped_proxy_in_params() {
    function apiScript(sharedTestAPIMethods) {
      browser.userScripts.onBeforeScript.addListener(script => {
        script.defineGlobals({
          ...sharedTestAPIMethods,
          testAPIMethod(...args) {
            // Proxies are opaque when wrapped in Xrays, and the proto of an opaque object
            // is supposed to be Object.prototype.
            browser.test.assertEq(
              script.global.Object.prototype,
              Object.getPrototypeOf(args[0]),
              "Calling getPrototypeOf on the XrayWrapped proxy object doesn't run the proxy trap"
            );

            browser.test.assertTrue(
              Array.isArray(args[0]),
              "Got an array object for the XrayWrapped proxy object param"
            );
            browser.test.assertEq(
              undefined,
              args[0].length,
              "XrayWrappers deny access to the length property"
            );
            browser.test.assertEq(
              undefined,
              args[0][0],
              "Got the expected item in the array object"
            );
            return true;
          },
        });
      });
    }

    async function userScript() {
      const { assertTrue, notifyFinish, testAPIMethod } = this;

      let proxy = new Proxy(["expectedArrayValue"], {
        getPrototypeOf() {
          throw new Error("Proxy's getPrototypeOf trap");
        },
        get() {
          throw new Error("Proxy's get trap");
        },
      });

      let result = testAPIMethod(proxy);

      assertTrue(
        result,
        `userScript got an unexpected returned value: ${result}`
      );
      notifyFinish();
    }

    await test_userScript_APIMethod({
      userScript,
      apiScript,
    });
  }
);

add_task(async function test_apiScript_method_return_proxy_object() {
  function apiScript(sharedTestAPIMethods) {
    let proxyTrapsCount = 0;
    let scriptTrapsCount = 0;

    browser.userScripts.onBeforeScript.addListener(script => {
      script.defineGlobals({
        ...sharedTestAPIMethods,
        testAPIMethodError() {
          return new Proxy(["expectedArrayValue"], {
            getPrototypeOf(target) {
              proxyTrapsCount++;
              return Object.getPrototypeOf(target);
            },
          });
        },
        testAPIMethodOk() {
          return new script.global.Proxy(
            script.export(["expectedArrayValue"]),
            script.export({
              getPrototypeOf(target) {
                scriptTrapsCount++;
                return script.global.Object.getPrototypeOf(target);
              },
            })
          );
        },
        assertNoProxyTrapTriggered() {
          browser.test.assertEq(
            0,
            proxyTrapsCount,
            "Proxy traps should not be triggered"
          );
        },
        assertScriptProxyTrapsCount(expected) {
          browser.test.assertEq(
            expected,
            scriptTrapsCount,
            "Script Proxy traps should have been triggered"
          );
        },
      });
    });
  }

  async function userScript() {
    const {
      assertTrue,
      assertNoProxyTrapTriggered,
      assertScriptProxyTrapsCount,
      notifyFinish,
      testAPIMethodError,
      testAPIMethodOk,
    } = this;

    let error;
    try {
      let result = testAPIMethodError();
      notifyFinish(
        `Unexpected returned value while expecting error: ${result}`
      );
      return;
    } catch (err) {
      error = err;
    }

    assertTrue(
      error &&
        error.message.includes("Return value not accessible to the userScript"),
      `Got an unexpected error message: ${error}`
    );

    error = undefined;
    try {
      let result = testAPIMethodOk();
      assertScriptProxyTrapsCount(0);
      if (!(result instanceof Array)) {
        notifyFinish(`Got an unexpected result: ${result}`);
        return;
      }
      assertScriptProxyTrapsCount(1);
    } catch (err) {
      error = err;
    }

    assertTrue(!error, `Got an unexpected error: ${error}`);

    assertNoProxyTrapTriggered();

    notifyFinish();
  }

  await test_userScript_APIMethod({
    userScript,
    apiScript,
  });
});

add_task(async function test_apiScript_returns_functions() {
  function apiScript(sharedTestAPIMethods) {
    browser.userScripts.onBeforeScript.addListener(script => {
      script.defineGlobals({
        ...sharedTestAPIMethods,
        testAPIReturnsFunction() {
          // Return a function with provides the same kind of behavior
          // of the API methods exported as globals.
          return script.export(() => window);
        },
        testAPIReturnsObjWithMethod() {
          return script.export({
            getWindow() {
              return window;
            },
          });
        },
      });
    });
  }

  async function userScript() {
    const {
      assertTrue,
      notifyFinish,
      testAPIReturnsFunction,
      testAPIReturnsObjWithMethod,
    } = this;

    let resultFn = testAPIReturnsFunction();
    assertTrue(
      typeof resultFn === "function",
      `userScript got an unexpected returned value: ${typeof resultFn}`
    );

    let fnRes = resultFn();
    assertTrue(
      fnRes === window,
      `Got an unexpected value from the returned function: ${fnRes}`
    );

    let resultObj = testAPIReturnsObjWithMethod();
    let actualTypeof = resultObj && typeof resultObj.getWindow;
    assertTrue(
      actualTypeof === "function",
      `Returned object does not have the expected getWindow method: ${actualTypeof}`
    );

    let methodRes = resultObj.getWindow();
    assertTrue(
      methodRes === window,
      `Got an unexpected value from the returned method: ${methodRes}`
    );

    notifyFinish();
  }

  await test_userScript_APIMethod({
    userScript,
    apiScript,
  });
});

add_task(
  async function test_apiScript_method_clone_non_subsumed_returned_values() {
    function apiScript(sharedTestAPIMethods) {
      browser.userScripts.onBeforeScript.addListener(script => {
        script.defineGlobals({
          ...sharedTestAPIMethods,
          testAPIMethodReturnOk() {
            return script.export({
              objKey1: {
                nestedProp: "nestedvalue",
              },
              window,
            });
          },
          testAPIMethodExplicitlyClonedError() {
            let result = script.export({ apiScopeObject: undefined });

            browser.test.assertThrows(
              () => {
                result.apiScopeObject = { disallowedProp: "disallowedValue" };
              },
              /Not allowed to define cross-origin object as property on .* XrayWrapper/,
              "Assigning a property to a xRayWrapper is expected to throw"
            );

            // Let the exception to be raised, so that we check that the actual underlying
            // error message is not leaking in the userScript (replaced by the generic
            // "An unexpected apiScript error occurred" error message).
            result.apiScopeObject = { disallowedProp: "disallowedValue" };
          },
        });
      });
    }

    async function userScript() {
      const {
        assertTrue,
        notifyFinish,
        testAPIMethodReturnOk,
        testAPIMethodExplicitlyClonedError,
      } = this;

      let result = testAPIMethodReturnOk();

      assertTrue(
        result &&
          "objKey1" in result &&
          result.objKey1.nestedProp === "nestedvalue",
        `userScript got an unexpected returned value: ${result}`
      );

      assertTrue(
        result.window === window,
        `userScript should have access to the window property: ${result.window}`
      );

      let error;
      try {
        result = testAPIMethodExplicitlyClonedError();
        notifyFinish(
          `Unexpected returned value while expecting error: ${result}`
        );
        return;
      } catch (err) {
        error = err;
      }

      // We expect the generic "unexpected apiScript error occurred" to be raised to the
      // userScript code.
      assertTrue(
        error &&
          error.message.includes("An unexpected apiScript error occurred"),
        `Got an unexpected error message: ${error}`
      );

      notifyFinish();
    }

    await test_userScript_APIMethod({
      userScript,
      apiScript,
    });
  }
);

add_task(async function test_apiScript_method_export_primitive_types() {
  function apiScript(sharedTestAPIMethods) {
    browser.userScripts.onBeforeScript.addListener(script => {
      script.defineGlobals({
        ...sharedTestAPIMethods,
        testAPIMethod(typeToExport) {
          switch (typeToExport) {
            case "boolean":
              return script.export(true);
            case "number":
              return script.export(123);
            case "string":
              return script.export("a string");
            case "symbol":
              return script.export(Symbol("a symbol"));
          }
          return undefined;
        },
      });
    });
  }

  async function userScript() {
    const { assertTrue, notifyFinish, testAPIMethod } = this;

    let v = testAPIMethod("boolean");
    assertTrue(v === true, `Should export a boolean`);

    v = testAPIMethod("number");
    assertTrue(v === 123, `Should export a number`);

    v = testAPIMethod("string");
    assertTrue(v === "a string", `Should export a string`);

    v = testAPIMethod("symbol");
    assertTrue(typeof v === "symbol", `Should export a symbol`);

    notifyFinish();
  }

  await test_userScript_APIMethod({
    userScript,
    apiScript,
  });
});

add_task(
  async function test_apiScript_method_avoid_unnecessary_params_cloning() {
    function apiScript(sharedTestAPIMethods) {
      browser.userScripts.onBeforeScript.addListener(script => {
        script.defineGlobals({
          ...sharedTestAPIMethods,
          testAPIMethodReturnsParam(param) {
            return param;
          },
          testAPIMethodReturnsUnwrappedParam(param) {
            return param.wrappedJSObject;
          },
        });
      });
    }

    async function userScript() {
      const {
        assertTrue,
        notifyFinish,
        testAPIMethodReturnsParam,
        testAPIMethodReturnsUnwrappedParam,
      } = this;

      let obj = {};

      let result = testAPIMethodReturnsParam(obj);

      assertTrue(
        result === obj,
        `Expect returned value to be strictly equal to the API method parameter`
      );

      result = testAPIMethodReturnsUnwrappedParam(obj);

      assertTrue(
        result === obj,
        `Expect returned value to be strictly equal to the unwrapped API method parameter`
      );

      notifyFinish();
    }

    await test_userScript_APIMethod({
      userScript,
      apiScript,
    });
  }
);

add_task(async function test_apiScript_method_export_sparse_arrays() {
  function apiScript(sharedTestAPIMethods) {
    browser.userScripts.onBeforeScript.addListener(script => {
      script.defineGlobals({
        ...sharedTestAPIMethods,
        testAPIMethod() {
          const sparseArray = [];
          sparseArray[3] = "third-element";
          sparseArray[5] = "fifth-element";
          return script.export(sparseArray);
        },
      });
    });
  }

  async function userScript() {
    const { assertTrue, notifyFinish, testAPIMethod } = this;

    const result = testAPIMethod(window, document);

    // We expect the returned value to be the uncloneable window object.
    assertTrue(
      result && result.length === 6,
      `the returned value should be an array of the expected length: ${result}`
    );
    assertTrue(
      result[3] === "third-element",
      `the third array element should have the expected value: ${result[3]}`
    );
    assertTrue(
      result[5] === "fifth-element",
      `the fifth array element should have the expected value: ${result[5]}`
    );
    assertTrue(
      result[0] === undefined,
      `the first array element should have the expected value: ${result[0]}`
    );
    assertTrue(!("0" in result), "Holey array should still be holey");

    notifyFinish();
  }

  await test_userScript_APIMethod({
    userScript,
    apiScript,
  });
});