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
|
/* -*- js-indent-level: 2; indent-tabs-mode: nil -*- */
/* vim: set ft=javascript ts=2 et sw=2 tw=80: */
/* 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";
const Cu = Components.utils;
const Ci = Components.interfaces;
const Cc = Components.classes;
const Cr = Components.results;
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
Cu.import("resource://gre/modules/Services.jsm");
Cu.import("resource://gre/modules/identity/LogUtils.jsm");
Cu.import("resource://gre/modules/identity/Sandbox.jsm");
this.EXPORTED_SYMBOLS = ["IdentityProvider"];
const FALLBACK_PROVIDER = "browserid.org";
XPCOMUtils.defineLazyModuleGetter(this,
"jwcrypto",
"resource://gre/modules/identity/jwcrypto.jsm");
function log(...aMessageArgs) {
Logger.log.apply(Logger, ["IDP"].concat(aMessageArgs));
}
function reportError(...aMessageArgs) {
Logger.reportError.apply(Logger, ["IDP"].concat(aMessageArgs));
}
function IdentityProviderService() {
XPCOMUtils.defineLazyModuleGetter(this,
"_store",
"resource://gre/modules/identity/IdentityStore.jsm",
"IdentityStore");
this.reset();
}
IdentityProviderService.prototype = {
QueryInterface: XPCOMUtils.generateQI([Ci.nsISupports, Ci.nsIObserver]),
_sandboxConfigured: false,
observe: function observe(aSubject, aTopic, aData) {
switch (aTopic) {
case "quit-application-granted":
Services.obs.removeObserver(this, "quit-application-granted");
this.shutdown();
break;
}
},
reset: function IDP_reset() {
// Clear the provisioning flows. Provision flows contain an
// identity, idpParams (how to reach the IdP to provision and
// authenticate), a callback (a completion callback for when things
// are done), and a provisioningFrame (which is the provisioning
// sandbox). Additionally, two callbacks will be attached:
// beginProvisioningCallback and genKeyPairCallback.
this._provisionFlows = {};
// Clear the authentication flows. Authentication flows attach
// to provision flows. In the process of provisioning an id, it
// may be necessary to authenticate with an IdP. The authentication
// flow maintains the state of that authentication process.
this._authenticationFlows = {};
},
getProvisionFlow: function getProvisionFlow(aProvId, aErrBack) {
let provFlow = this._provisionFlows[aProvId];
if (provFlow) {
return provFlow;
}
let err = "No provisioning flow found with id " + aProvId;
log("ERROR:", err);
if (typeof aErrBack === 'function') {
aErrBack(err);
}
return undefined;
},
shutdown: function RP_shutdown() {
this.reset();
if (this._sandboxConfigured) {
// Tear down message manager listening on the hidden window
Cu.import("resource://gre/modules/DOMIdentity.jsm");
DOMIdentity._configureMessages(Services.appShell.hiddenDOMWindow, false);
this._sandboxConfigured = false;
}
Services.obs.removeObserver(this, "quit-application-granted");
},
get securityLevel() {
return 1;
},
get certDuration() {
switch (this.securityLevel) {
default:
return 3600;
}
},
/**
* Provision an Identity
*
* @param aIdentity
* (string) the email we're logging in with
*
* @param aIDPParams
* (object) parameters of the IdP
*
* @param aCallback
* (function) callback to invoke on completion
* with first-positional parameter the error.
*/
_provisionIdentity: function _provisionIdentity(aIdentity, aIDPParams, aProvId, aCallback) {
let provPath = aIDPParams.idpParams.provisioning;
let url = Services.io.newURI("https://" + aIDPParams.domain, null, null).resolve(provPath);
log("_provisionIdentity: identity:", aIdentity, "url:", url);
// If aProvId is not null, then we already have a flow
// with a sandbox. Otherwise, get a sandbox and create a
// new provision flow.
if (aProvId) {
// Re-use an existing sandbox
log("_provisionIdentity: re-using sandbox in provisioning flow with id:", aProvId);
this._provisionFlows[aProvId].provisioningSandbox.reload();
} else {
this._createProvisioningSandbox(url, function createdSandbox(aSandbox) {
// create a provisioning flow, using the sandbox id, and
// stash callback associated with this provisioning workflow.
let provId = aSandbox.id;
this._provisionFlows[provId] = {
identity: aIdentity,
idpParams: aIDPParams,
securityLevel: this.securityLevel,
provisioningSandbox: aSandbox,
callback: function doCallback(aErr) {
aCallback(aErr, provId);
},
};
log("_provisionIdentity: Created sandbox and provisioning flow with id:", provId);
// XXX bug 769862 - provisioning flow should timeout after N seconds
}.bind(this));
}
},
// DOM Methods
/**
* the provisioning iframe sandbox has called navigator.id.beginProvisioning()
*
* @param aCaller
* (object) the iframe sandbox caller with all callbacks and
* other information. Callbacks include:
* - doBeginProvisioningCallback(id, duration_s)
* - doGenKeyPairCallback(pk)
*/
beginProvisioning: function beginProvisioning(aCaller) {
log("beginProvisioning:", aCaller.id);
// Expect a flow for this caller already to be underway.
let provFlow = this.getProvisionFlow(aCaller.id, aCaller.doError);
// keep the caller object around
provFlow.caller = aCaller;
let identity = provFlow.identity;
let frame = provFlow.provisioningFrame;
// Determine recommended length of cert.
let duration = this.certDuration;
// Make a record that we have begun provisioning. This is required
// for genKeyPair.
provFlow.didBeginProvisioning = true;
// Let the sandbox know to invoke the callback to beginProvisioning with
// the identity and cert length.
return aCaller.doBeginProvisioningCallback(identity, duration);
},
/**
* the provisioning iframe sandbox has called
* navigator.id.raiseProvisioningFailure()
*
* @param aProvId
* (int) the identifier of the provisioning flow tied to that sandbox
* @param aReason
*/
raiseProvisioningFailure: function raiseProvisioningFailure(aProvId, aReason) {
reportError("Provisioning failure", aReason);
// look up the provisioning caller and its callback
let provFlow = this.getProvisionFlow(aProvId);
// Sandbox is deleted in _cleanUpProvisionFlow in case we re-use it.
// This may be either a "soft" or "hard" fail. If it's a
// soft fail, we'll flow through setAuthenticationFlow, where
// the provision flow data will be copied into a new auth
// flow. If it's a hard fail, then the callback will be
// responsible for cleaning up the now defunct provision flow.
// invoke the callback with an error.
provFlow.callback(aReason);
},
/**
* When navigator.id.genKeyPair is called from provisioning iframe sandbox.
* Generates a keypair for the current user being provisioned.
*
* @param aProvId
* (int) the identifier of the provisioning caller tied to that sandbox
*
* It is an error to call genKeypair without receiving the callback for
* the beginProvisioning() call first.
*/
genKeyPair: function genKeyPair(aProvId) {
// Look up the provisioning caller and make sure it's valid.
let provFlow = this.getProvisionFlow(aProvId);
if (!provFlow.didBeginProvisioning) {
let errStr = "ERROR: genKeyPair called before beginProvisioning";
log(errStr);
provFlow.callback(errStr);
return;
}
// Ok generate a keypair
jwcrypto.generateKeyPair(jwcrypto.ALGORITHMS.DS160, function gkpCb(err, kp) {
log("in gkp callback");
if (err) {
log("ERROR: genKeyPair:", err);
provFlow.callback(err);
return;
}
provFlow.kp = kp;
// Serialize the publicKey of the keypair and send it back to the
// sandbox.
log("genKeyPair: generated keypair for provisioning flow with id:", aProvId);
provFlow.caller.doGenKeyPairCallback(provFlow.kp.serializedPublicKey);
}.bind(this));
},
/**
* When navigator.id.registerCertificate is called from provisioning iframe
* sandbox.
*
* Sets the certificate for the user for which a certificate was requested
* via a preceding call to beginProvisioning (and genKeypair).
*
* @param aProvId
* (integer) the identifier of the provisioning caller tied to that
* sandbox
*
* @param aCert
* (String) A JWT representing the signed certificate for the user
* being provisioned, provided by the IdP.
*/
registerCertificate: function registerCertificate(aProvId, aCert) {
log("registerCertificate:", aProvId, aCert);
// look up provisioning caller, make sure it's valid.
let provFlow = this.getProvisionFlow(aProvId);
if (!provFlow.caller) {
reportError("registerCertificate", "No provision flow or caller");
return;
}
if (!provFlow.kp) {
let errStr = "Cannot register a certificate without a keypair";
reportError("registerCertificate", errStr);
provFlow.callback(errStr);
return;
}
// store the keypair and certificate just provided in IDStore.
this._store.addIdentity(provFlow.identity, provFlow.kp, aCert);
// Great success!
provFlow.callback(null);
// Clean up the flow.
this._cleanUpProvisionFlow(aProvId);
},
/**
* Begin the authentication process with an IdP
*
* @param aProvId
* (int) the identifier of the provisioning flow which failed
*
* @param aCallback
* (function) to invoke upon completion, with
* first-positional-param error.
*/
_doAuthentication: function _doAuthentication(aProvId, aIDPParams) {
log("_doAuthentication: provId:", aProvId, "idpParams:", aIDPParams);
// create an authentication caller and its identifier AuthId
// stash aIdentity, idpparams, and callback in it.
// extract authentication URL from idpParams
let authPath = aIDPParams.idpParams.authentication;
let authURI = Services.io.newURI("https://" + aIDPParams.domain, null, null).resolve(authPath);
// beginAuthenticationFlow causes the "identity-auth" topic to be
// observed. Since it's sending a notification to the DOM, there's
// no callback. We wait for the DOM to trigger the next phase of
// provisioning.
this._beginAuthenticationFlow(aProvId, authURI);
// either we bind the AuthID to the sandbox ourselves, or UX does that,
// in which case we need to tell UX the AuthId.
// Currently, the UX creates the UI and gets the AuthId from the window
// and sets is with setAuthenticationFlow
},
/**
* The authentication frame has called navigator.id.beginAuthentication
*
* IMPORTANT: the aCaller is *always* non-null, even if this is called from
* a regular content page. We have to make sure, on every DOM call, that
* aCaller is an expected authentication-flow identifier. If not, we throw
* an error or something.
*
* @param aCaller
* (object) the authentication caller
*
*/
beginAuthentication: function beginAuthentication(aCaller) {
log("beginAuthentication: caller id:", aCaller.id);
// Begin the authentication flow after having concluded a provisioning
// flow. The aCaller that the DOM gives us will have the same ID as
// the provisioning flow we just concluded. (see setAuthenticationFlow)
let authFlow = this._authenticationFlows[aCaller.id];
if (!authFlow) {
return aCaller.doError("beginAuthentication: no flow for caller id", aCaller.id);
}
authFlow.caller = aCaller;
let identity = this._provisionFlows[authFlow.provId].identity;
// tell the UI to start the authentication process
log("beginAuthentication: authFlow:", aCaller.id, "identity:", identity);
return authFlow.caller.doBeginAuthenticationCallback(identity);
},
/**
* The auth frame has called navigator.id.completeAuthentication
*
* @param aAuthId
* (int) the identifier of the authentication caller tied to that sandbox
*
*/
completeAuthentication: function completeAuthentication(aAuthId) {
log("completeAuthentication:", aAuthId);
// look up the AuthId caller, and get its callback.
let authFlow = this._authenticationFlows[aAuthId];
if (!authFlow) {
reportError("completeAuthentication", "No auth flow with id", aAuthId);
return;
}
let provId = authFlow.provId;
// delete caller
delete authFlow['caller'];
delete this._authenticationFlows[aAuthId];
let provFlow = this.getProvisionFlow(provId);
provFlow.didAuthentication = true;
let subject = {
rpId: provFlow.rpId,
identity: provFlow.identity,
};
Services.obs.notifyObservers({ wrappedJSObject: subject }, "identity-auth-complete", aAuthId);
},
/**
* The auth frame has called navigator.id.cancelAuthentication
*
* @param aAuthId
* (int) the identifier of the authentication caller
*
*/
cancelAuthentication: function cancelAuthentication(aAuthId) {
log("cancelAuthentication:", aAuthId);
// look up the AuthId caller, and get its callback.
let authFlow = this._authenticationFlows[aAuthId];
if (!authFlow) {
reportError("cancelAuthentication", "No auth flow with id:", aAuthId);
return;
}
let provId = authFlow.provId;
// delete caller
delete authFlow['caller'];
delete this._authenticationFlows[aAuthId];
let provFlow = this.getProvisionFlow(provId);
provFlow.didAuthentication = true;
Services.obs.notifyObservers(null, "identity-auth-complete", aAuthId);
// invoke callback with ERROR.
let errStr = "Authentication canceled by IDP";
log("ERROR: cancelAuthentication:", errStr);
provFlow.callback(errStr);
},
/**
* Called by the UI to set the ID and caller for the authentication flow after it gets its ID
*/
setAuthenticationFlow: function(aAuthId, aProvId) {
// this is the transition point between the two flows,
// provision and authenticate. We tell the auth flow which
// provisioning flow it is started from.
log("setAuthenticationFlow: authId:", aAuthId, "provId:", aProvId);
this._authenticationFlows[aAuthId] = { provId: aProvId };
this._provisionFlows[aProvId].authId = aAuthId;
},
/**
* Load the provisioning URL in a hidden frame to start the provisioning
* process.
*/
_createProvisioningSandbox: function _createProvisioningSandbox(aURL, aCallback) {
log("_createProvisioningSandbox:", aURL);
if (!this._sandboxConfigured) {
// Configure message manager listening on the hidden window
Cu.import("resource://gre/modules/DOMIdentity.jsm");
DOMIdentity._configureMessages(Services.appShell.hiddenDOMWindow, true);
this._sandboxConfigured = true;
}
new Sandbox(aURL, aCallback);
},
/**
* Load the authentication UI to start the authentication process.
*/
_beginAuthenticationFlow: function _beginAuthenticationFlow(aProvId, aURL) {
log("_beginAuthenticationFlow:", aProvId, aURL);
let propBag = {provId: aProvId};
Services.obs.notifyObservers({wrappedJSObject:propBag}, "identity-auth", aURL);
},
/**
* Clean up a provision flow and the authentication flow and sandbox
* that may be attached to it.
*/
_cleanUpProvisionFlow: function _cleanUpProvisionFlow(aProvId) {
log('_cleanUpProvisionFlow:', aProvId);
let prov = this._provisionFlows[aProvId];
// Clean up the sandbox, if there is one.
if (prov.provisioningSandbox) {
let sandbox = this._provisionFlows[aProvId]['provisioningSandbox'];
if (sandbox.free) {
log('_cleanUpProvisionFlow: freeing sandbox');
sandbox.free();
}
delete this._provisionFlows[aProvId]['provisioningSandbox'];
}
// Clean up a related authentication flow, if there is one.
if (this._authenticationFlows[prov.authId]) {
delete this._authenticationFlows[prov.authId];
}
// Finally delete the provision flow
delete this._provisionFlows[aProvId];
}
};
this.IdentityProvider = new IdentityProviderService();
|