summaryrefslogtreecommitdiffstats
path: root/dom/webauthn/tests/browser/head.js
blob: d6cbd561335f3021967d92227be31fe7e9f83542 (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
/* 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";

let exports = this;

const scripts = [
  "pkijs/common.js",
  "pkijs/asn1.js",
  "pkijs/x509_schema.js",
  "pkijs/x509_simpl.js",
  "browser/cbor.js",
  "browser/u2futil.js",
];

for (let script of scripts) {
  Services.scriptloader.loadSubScript(
    `chrome://mochitests/content/browser/dom/webauthn/tests/${script}`,
    this
  );
}

function add_virtual_authenticator(autoremove = true) {
  let webauthnService = Cc["@mozilla.org/webauthn/service;1"].getService(
    Ci.nsIWebAuthnService
  );
  let id = webauthnService.addVirtualAuthenticator(
    "ctap2_1",
    "internal",
    true,
    true,
    true,
    true
  );
  if (autoremove) {
    registerCleanupFunction(() => {
      webauthnService.removeVirtualAuthenticator(id);
    });
  }
  return id;
}

async function addCredential(authenticatorId, rpId) {
  let keyPair = await crypto.subtle.generateKey(
    {
      name: "ECDSA",
      namedCurve: "P-256",
    },
    true,
    ["sign"]
  );

  let credId = new Uint8Array(32);
  crypto.getRandomValues(credId);
  credId = bytesToBase64UrlSafe(credId);

  let privateKey = await crypto.subtle
    .exportKey("pkcs8", keyPair.privateKey)
    .then(privateKey => bytesToBase64UrlSafe(privateKey));

  let webauthnService = Cc["@mozilla.org/webauthn/service;1"].getService(
    Ci.nsIWebAuthnService
  );

  webauthnService.addCredential(
    authenticatorId,
    credId,
    true, // resident key
    rpId,
    privateKey,
    "VGVzdCBVc2Vy", // "Test User"
    0 // sign count
  );

  return credId;
}

async function removeCredential(authenticatorId, credId) {
  let webauthnService = Cc["@mozilla.org/webauthn/service;1"].getService(
    Ci.nsIWebAuthnService
  );

  webauthnService.removeCredential(authenticatorId, credId);
}

function memcmp(x, y) {
  let xb = new Uint8Array(x);
  let yb = new Uint8Array(y);

  if (x.byteLength != y.byteLength) {
    return false;
  }

  for (let i = 0; i < xb.byteLength; ++i) {
    if (xb[i] != yb[i]) {
      return false;
    }
  }

  return true;
}

function arrivingHereIsBad(aResult) {
  ok(false, "Bad result! Received a: " + aResult);
}

function expectError(aType) {
  let expected = `${aType}Error`;
  return function (aResult) {
    is(
      aResult.slice(0, expected.length),
      expected,
      `Expecting a ${aType}Error`
    );
  };
}

/* eslint-disable no-shadow */
function promiseWebAuthnMakeCredential(
  tab,
  attestation = "none",
  residentKey = "discouraged",
  extensions = {}
) {
  return ContentTask.spawn(
    tab.linkedBrowser,
    [attestation, residentKey, extensions],
    ([attestation, residentKey, extensions]) => {
      const cose_alg_ECDSA_w_SHA256 = -7;

      let challenge = content.crypto.getRandomValues(new Uint8Array(16));

      let pubKeyCredParams = [
        {
          type: "public-key",
          alg: cose_alg_ECDSA_w_SHA256,
        },
      ];

      let publicKey = {
        rp: { id: content.document.domain, name: "none" },
        user: {
          id: new Uint8Array(),
          name: "none",
          displayName: "none",
        },
        pubKeyCredParams,
        authenticatorSelection: {
          authenticatorAttachment: "cross-platform",
          residentKey,
        },
        extensions,
        attestation,
        challenge,
      };

      return content.navigator.credentials
        .create({ publicKey })
        .then(credential => {
          return {
            clientDataJSON: credential.response.clientDataJSON,
            attObj: credential.response.attestationObject,
            rawId: credential.rawId,
          };
        });
    }
  );
}

function promiseWebAuthnGetAssertion(tab, key_handle = null, extensions = {}) {
  return ContentTask.spawn(
    tab.linkedBrowser,
    [key_handle, extensions],
    ([key_handle, extensions]) => {
      let challenge = content.crypto.getRandomValues(new Uint8Array(16));
      if (key_handle == null) {
        key_handle = content.crypto.getRandomValues(new Uint8Array(16));
      }

      let credential = {
        id: key_handle,
        type: "public-key",
        transports: ["usb"],
      };

      let publicKey = {
        challenge,
        extensions,
        rpId: content.document.domain,
        allowCredentials: [credential],
      };

      return content.navigator.credentials
        .get({ publicKey })
        .then(assertion => {
          return {
            authenticatorData: assertion.response.authenticatorData,
            clientDataJSON: assertion.response.clientDataJSON,
            extensions: assertion.getClientExtensionResults(),
            signature: assertion.response.signature,
          };
        });
    }
  );
}

function promiseWebAuthnGetAssertionDiscoverable(
  tab,
  mediation = "optional",
  extensions = {}
) {
  return ContentTask.spawn(
    tab.linkedBrowser,
    [extensions, mediation],
    ([extensions, mediation]) => {
      let challenge = content.crypto.getRandomValues(new Uint8Array(16));

      let publicKey = {
        challenge,
        extensions,
        rpId: content.document.domain,
        allowCredentials: [],
      };

      return content.navigator.credentials.get({ publicKey, mediation });
    }
  );
}

function checkRpIdHash(rpIdHash, hostname) {
  return crypto.subtle
    .digest("SHA-256", string2buffer(hostname))
    .then(calculatedRpIdHash => {
      let calcHashStr = bytesToBase64UrlSafe(
        new Uint8Array(calculatedRpIdHash)
      );
      let providedHashStr = bytesToBase64UrlSafe(new Uint8Array(rpIdHash));

      if (calcHashStr != providedHashStr) {
        throw new Error("Calculated RP ID hash doesn't match.");
      }
    });
}

function promiseNotification(id) {
  return new Promise(resolve => {
    PopupNotifications.panel.addEventListener("popupshown", function shown() {
      let notification = PopupNotifications.getNotification(id);
      if (notification) {
        ok(true, `${id} prompt visible`);
        PopupNotifications.panel.removeEventListener("popupshown", shown);
        resolve();
      }
    });
  });
}
/* eslint-enable no-shadow */