summaryrefslogtreecommitdiffstats
path: root/dom/security/test/csp/worker_helper.js
blob: 6c329fd5f107f3945ed8c9f96295336c1d902a57 (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
/**
 * Any copyright is dedicated to the Public Domain.
 * http://creativecommons.org/publicdomain/zero/1.0/
 */

var _tests = [];
function addTest(test) {
  _tests.push(test);
}

function addAsyncTest(fn) {
  _tests.push(() => fn().catch(ok.bind(null, false)));
}

function runNextTest() {
  if (!_tests.length) {
    SimpleTest.finish();
    return;
  }
  const fn = _tests.shift();
  try {
    fn();
  } catch (ex) {
    info(
      "Test function " +
        (fn.name ? "'" + fn.name + "' " : "") +
        "threw an exception: " +
        ex
    );
  }
}

/**
 * Helper to perform an XHR then blob response to create worker
 */
function doXHRGetBlob(uri) {
  return new Promise(resolve => {
    const xhr = new XMLHttpRequest();
    xhr.open("GET", uri);
    xhr.responseType = "blob";
    xhr.addEventListener("load", function() {
      is(
        xhr.status,
        200,
        "doXHRGetBlob load uri='" + uri + "' status=" + xhr.status
      );
      resolve(xhr.response);
    });
    xhr.send();
  });
}

function removeObserver(observer) {
  SpecialPowers.removeObserver(observer, "specialpowers-http-notify-request");
  SpecialPowers.removeObserver(observer, "csp-on-violate-policy");
}

/**
 * Helper to perform an assert to check if the request should be blocked or
 * allowed by CSP
 */
function assertCSPBlock(url, shouldBlock) {
  return new Promise((resolve, reject) => {
    let observer = {
      observe(subject, topic, data) {
        if (topic === "specialpowers-http-notify-request") {
          if (data == url) {
            is(shouldBlock, false, "Should allow request uri='" + url);
            removeObserver(observer);
            resolve();
          }
        }

        if (topic === "csp-on-violate-policy") {
          let asciiSpec = SpecialPowers.getPrivilegedProps(
            SpecialPowers.do_QueryInterface(subject, "nsIURI"),
            "asciiSpec"
          );
          if (asciiSpec == url) {
            is(shouldBlock, true, "Should block request uri='" + url);
            removeObserver(observer);
            resolve();
          }
        }
      },
    };

    SpecialPowers.addObserver(observer, "csp-on-violate-policy");
    SpecialPowers.addObserver(observer, "specialpowers-http-notify-request");
  });
}