summaryrefslogtreecommitdiffstats
path: root/dom/media/IdpSandbox.sys.mjs
blob: 8b94abf7dd996c2d399e7441597596a75ada19b6 (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
/* 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/. */

import { NetUtil } from "resource://gre/modules/NetUtil.sys.mjs";

/** This little class ensures that redirects maintain an https:// origin */
function RedirectHttpsOnly() {}

RedirectHttpsOnly.prototype = {
  asyncOnChannelRedirect(oldChannel, newChannel, flags, callback) {
    if (newChannel.URI.scheme !== "https") {
      callback.onRedirectVerifyCallback(Cr.NS_ERROR_ABORT);
    } else {
      callback.onRedirectVerifyCallback(Cr.NS_OK);
    }
  },

  getInterface(iid) {
    return this.QueryInterface(iid);
  },
  QueryInterface: ChromeUtils.generateQI(["nsIChannelEventSink"]),
};

/** This class loads a resource into a single string. ResourceLoader.load() is
 * the entry point. */
function ResourceLoader(res, rej) {
  this.resolve = res;
  this.reject = rej;
  this.data = "";
}

/** Loads the identified https:// URL. */
ResourceLoader.load = function (uri, doc) {
  return new Promise((resolve, reject) => {
    let listener = new ResourceLoader(resolve, reject);
    let ioChannel = NetUtil.newChannel({
      uri,
      loadingNode: doc,
      securityFlags: Ci.nsILoadInfo.SEC_ALLOW_CROSS_ORIGIN_SEC_CONTEXT_IS_NULL,
      contentPolicyType: Ci.nsIContentPolicy.TYPE_INTERNAL_SCRIPT,
    });

    ioChannel.loadGroup = doc.documentLoadGroup.QueryInterface(Ci.nsILoadGroup);
    ioChannel.notificationCallbacks = new RedirectHttpsOnly();
    ioChannel.asyncOpen(listener);
  });
};

ResourceLoader.prototype = {
  onDataAvailable(request, input, offset, count) {
    let stream = Cc["@mozilla.org/scriptableinputstream;1"].createInstance(
      Ci.nsIScriptableInputStream
    );
    stream.init(input);
    this.data += stream.read(count);
  },

  onStartRequest(request) {},

  onStopRequest(request, status) {
    if (Components.isSuccessCode(status)) {
      var statusCode = request.QueryInterface(Ci.nsIHttpChannel).responseStatus;
      if (statusCode === 200) {
        this.resolve({ request, data: this.data });
      } else {
        this.reject(new Error("Non-200 response from server: " + statusCode));
      }
    } else {
      this.reject(new Error("Load failed: " + status));
    }
  },

  getInterface(iid) {
    return this.QueryInterface(iid);
  },
  QueryInterface: ChromeUtils.generateQI(["nsIStreamListener"]),
};

/**
 * A simple implementation of the WorkerLocation interface.
 */
function createLocationFromURI(uri) {
  return {
    href: uri.spec,
    protocol: uri.scheme + ":",
    host: uri.host + (uri.port >= 0 ? ":" + uri.port : ""),
    port: uri.port,
    hostname: uri.host,
    pathname: uri.pathQueryRef.replace(/[#\?].*/, ""),
    search: uri.pathQueryRef.replace(/^[^\?]*/, "").replace(/#.*/, ""),
    hash: uri.hasRef ? "#" + uri.ref : "",
    origin: uri.prePath,
    toString() {
      return uri.spec;
    },
  };
}

/**
 * A javascript sandbox for running an IdP.
 *
 * @param domain (string) the domain of the IdP
 * @param protocol (string?) the protocol of the IdP [default: 'default']
 * @param win (obj) the current window
 * @throws if the domain or protocol aren't valid
 */
export function IdpSandbox(domain, protocol, win) {
  this.source = IdpSandbox.createIdpUri(domain, protocol || "default");
  this.active = null;
  this.sandbox = null;
  this.window = win;
}

IdpSandbox.checkDomain = function (domain) {
  if (!domain || typeof domain !== "string") {
    throw new Error(
      "Invalid domain for identity provider: " +
        "must be a non-zero length string"
    );
  }
};

/**
 * Checks that the IdP protocol is superficially sane.  In particular, we don't
 * want someone adding relative paths (e.g., '../../myuri'), which could be used
 * to move outside of /.well-known/ and into space that they control.
 */
IdpSandbox.checkProtocol = function (protocol) {
  let message = "Invalid protocol for identity provider: ";
  if (!protocol || typeof protocol !== "string") {
    throw new Error(message + "must be a non-zero length string");
  }
  if (decodeURIComponent(protocol).match(/[\/\\]/)) {
    throw new Error(message + "must not include '/' or '\\'");
  }
};

/**
 * Turns a domain and protocol into a URI.  This does some aggressive checking
 * to make sure that we aren't being fooled somehow.  Throws on fooling.
 */
IdpSandbox.createIdpUri = function (domain, protocol) {
  IdpSandbox.checkDomain(domain);
  IdpSandbox.checkProtocol(protocol);

  let message = "Invalid IdP parameters: ";
  try {
    let wkIdp = "https://" + domain + "/.well-known/idp-proxy/" + protocol;
    let uri = Services.io.newURI(wkIdp);

    if (uri.hostPort !== domain) {
      throw new Error(message + "domain is invalid");
    }
    if (uri.pathQueryRef.indexOf("/.well-known/idp-proxy/") !== 0) {
      throw new Error(message + "must produce a /.well-known/idp-proxy/ URI");
    }

    return uri;
  } catch (e) {
    if (
      typeof e.result !== "undefined" &&
      e.result === Cr.NS_ERROR_MALFORMED_URI
    ) {
      throw new Error(message + "must produce a valid URI");
    }
    throw e;
  }
};

IdpSandbox.prototype = {
  isSame(domain, protocol) {
    return this.source.spec === IdpSandbox.createIdpUri(domain, protocol).spec;
  },

  start() {
    if (!this.active) {
      this.active = ResourceLoader.load(this.source, this.window.document).then(
        result => this._createSandbox(result)
      );
    }
    return this.active;
  },

  // Provides the sandbox with some useful facilities.  Initially, this is only
  // a minimal set; it is far easier to add more as the need arises, than to
  // take them back if we discover a mistake.
  _populateSandbox(uri) {
    this.sandbox.location = Cu.cloneInto(
      createLocationFromURI(uri),
      this.sandbox,
      { cloneFunctions: true }
    );
  },

  _createSandbox(result) {
    let principal = Services.scriptSecurityManager.getChannelResultPrincipal(
      result.request
    );

    this.sandbox = Cu.Sandbox(principal, {
      sandboxName: "IdP-" + this.source.host,
      wantComponents: false,
      wantExportHelpers: false,
      wantGlobalProperties: [
        "indexedDB",
        "XMLHttpRequest",
        "TextEncoder",
        "TextDecoder",
        "URL",
        "URLSearchParams",
        "atob",
        "btoa",
        "Blob",
        "crypto",
        "rtcIdentityProvider",
        "fetch",
      ],
    });
    let registrar = this.sandbox.rtcIdentityProvider;
    if (!Cu.isXrayWrapper(registrar)) {
      throw new Error("IdP setup failed");
    }

    // have to use the ultimate URI, not the starting one to avoid
    // that origin stealing from the one that redirected to it
    this._populateSandbox(result.request.URI);
    try {
      Cu.evalInSandbox(
        result.data,
        this.sandbox,
        "latest",
        result.request.URI.spec,
        1
      );
    } catch (e) {
      // These can be passed straight on, because they are explicitly labelled
      // as being IdP errors by the IdP and we drop line numbers as a result.
      if (e.name === "IdpError" || e.name === "IdpLoginError") {
        throw e;
      }
      this._logError(e);
      throw new Error("Error in IdP, check console for details");
    }

    if (!registrar.hasIdp) {
      throw new Error("IdP failed to call rtcIdentityProvider.register()");
    }
    return registrar;
  },

  // Capture all the details from the error and log them to the console.  This
  // can't rethrow anything else because that could leak information about the
  // internal workings of the IdP across origins.
  _logError(e) {
    let winID = this.window.windowGlobalChild.innerWindowId;
    let scriptError = Cc["@mozilla.org/scripterror;1"].createInstance(
      Ci.nsIScriptError
    );
    scriptError.initWithWindowID(
      e.message,
      e.fileName,
      null,
      e.lineNumber,
      e.columnNumber,
      Ci.nsIScriptError.errorFlag,
      "content javascript",
      winID
    );
    Services.console.logMessage(scriptError);
  },

  stop() {
    if (this.sandbox) {
      Cu.nukeSandbox(this.sandbox);
    }
    this.sandbox = null;
    this.active = null;
  },

  toString() {
    return this.source.spec;
  },
};