Add Passkeys Support
Closes gh-13305
This commit is contained in:
@@ -0,0 +1,49 @@
|
||||
/*
|
||||
* Copyright 2002-2024 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
"use strict";
|
||||
|
||||
import "./bootstrap.js";
|
||||
import abortController from "../lib/abort-controller.js";
|
||||
import { expect } from "chai";
|
||||
|
||||
describe("abort-controller", () => {
|
||||
describe("newSignal", () => {
|
||||
it("returns an AbortSignal", () => {
|
||||
const signal = abortController.newSignal();
|
||||
|
||||
expect(signal).to.be.instanceof(AbortSignal);
|
||||
expect(signal.aborted).to.be.false;
|
||||
});
|
||||
|
||||
it("returns a new signal every time", () => {
|
||||
const initialSignal = abortController.newSignal();
|
||||
|
||||
const newSignal = abortController.newSignal();
|
||||
|
||||
expect(initialSignal).to.not.equal(newSignal);
|
||||
});
|
||||
|
||||
it("aborts the existing signal", () => {
|
||||
const signal = abortController.newSignal();
|
||||
|
||||
abortController.newSignal();
|
||||
|
||||
expect(signal.aborted).to.be.true;
|
||||
expect(signal.reason).to.equal("Initiating new WebAuthN ceremony, cancelling current ceremony");
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,76 @@
|
||||
/*
|
||||
* Copyright 2002-2024 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
"use strict";
|
||||
|
||||
import { expect } from "chai";
|
||||
import base64url from "../lib/base64url.js";
|
||||
|
||||
describe("base64url", () => {
|
||||
before(() => {
|
||||
// Emulate the atob / btoa base64 encoding/decoding from the browser
|
||||
global.window = {
|
||||
btoa: (str) => Buffer.from(str, "binary").toString("base64"),
|
||||
atob: (b64) => Buffer.from(b64, "base64").toString("binary"),
|
||||
};
|
||||
});
|
||||
|
||||
after(() => {
|
||||
// Reset window object
|
||||
global.window = {};
|
||||
});
|
||||
|
||||
it("decodes", () => {
|
||||
// "Zm9vYmFy" is "foobar" in base 64, i.e. f:102 o:111 o:111 b:98 a:97 r:114
|
||||
const decoded = base64url.decode("Zm9vYmFy");
|
||||
|
||||
expect(new Uint8Array(decoded)).to.be.deep.equal(new Uint8Array([102, 111, 111, 98, 97, 114]));
|
||||
});
|
||||
|
||||
it("decodes special characters", () => {
|
||||
// Wrap the decode function for easy testing
|
||||
const decode = (str) => {
|
||||
const decoded = new Uint8Array(base64url.decode(str));
|
||||
return Array.from(decoded);
|
||||
};
|
||||
|
||||
// "Pz8/" is "???" in base64, i.e. ?:63 three times
|
||||
expect(decode("Pz8/")).to.be.deep.equal(decode("Pz8_"));
|
||||
expect(decode("Pz8_")).to.be.deep.equal([63, 63, 63]);
|
||||
// "Pj4+" is ">>>" in base64, ie >:62 three times
|
||||
expect(decode("Pj4+")).to.be.deep.equal(decode("Pj4-"));
|
||||
expect(decode("Pj4-")).to.be.deep.equal([62, 62, 62]);
|
||||
});
|
||||
|
||||
it("encodes", () => {
|
||||
const encoded = base64url.encode(Buffer.from("foobar"));
|
||||
|
||||
expect(encoded).to.be.equal("Zm9vYmFy");
|
||||
});
|
||||
|
||||
it("encodes special +/ characters", () => {
|
||||
const encode = (str) => base64url.encode(Buffer.from(str));
|
||||
|
||||
expect(encode("???")).to.be.equal("Pz8_");
|
||||
expect(encode(">>>")).to.be.equal("Pj4-");
|
||||
});
|
||||
|
||||
it("is stable", () => {
|
||||
const base = "tyRDnKxdj7uWOT5jrchXu54lo6nf3bWOUvMQnGOXk7g";
|
||||
|
||||
expect(base64url.encode(base64url.decode(base))).to.be.equal(base);
|
||||
});
|
||||
});
|
||||
Vendored
+22
@@ -0,0 +1,22 @@
|
||||
/*
|
||||
* Copyright 2002-2024 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import chai from "chai";
|
||||
|
||||
// Show full diffs when there is an equality difference an assertion.
|
||||
// By default, chai truncates at 40 characters, making it difficult to
|
||||
// compare e.g. error messages
|
||||
chai.config.truncateThreshold = 0;
|
||||
@@ -0,0 +1,65 @@
|
||||
/*
|
||||
* Copyright 2002-2024 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
"use strict";
|
||||
|
||||
import http from "../lib/http.js";
|
||||
import { expect } from "chai";
|
||||
import { fake, assert } from "sinon";
|
||||
|
||||
describe("http", () => {
|
||||
beforeEach(() => {
|
||||
global.fetch = fake.resolves({ ok: true });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
delete global.fetch;
|
||||
});
|
||||
|
||||
describe("post", () => {
|
||||
it("calls fetch with headers", async () => {
|
||||
const url = "https://example.com/some/path";
|
||||
const headers = { "x-custom": "some-value" };
|
||||
|
||||
const resp = await http.post(url, headers);
|
||||
|
||||
expect(resp.ok).to.be.true;
|
||||
assert.calledOnceWithExactly(global.fetch, url, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
...headers,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("sends the body as a JSON string", async () => {
|
||||
const body = { foo: "bar", baz: 42 };
|
||||
const url = "https://example.com/some/path";
|
||||
|
||||
const resp = await http.post(url, {}, body);
|
||||
|
||||
expect(resp.ok).to.be.true;
|
||||
assert.calledOnceWithExactly(global.fetch, url, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: `{"foo":"bar","baz":42}`,
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,697 @@
|
||||
/*
|
||||
* Copyright 2002-2024 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
"use strict";
|
||||
|
||||
import "./bootstrap.js";
|
||||
import { expect } from "chai";
|
||||
import { assert, fake, match, stub } from "sinon";
|
||||
import http from "../lib/http.js";
|
||||
import webauthn from "../lib/webauthn-core.js";
|
||||
import base64url from "../lib/base64url.js";
|
||||
|
||||
describe("webauthn-core", () => {
|
||||
beforeEach(() => {
|
||||
global.window = {
|
||||
btoa: (str) => Buffer.from(str, "binary").toString("base64"),
|
||||
atob: (b64) => Buffer.from(b64, "base64").toString("binary"),
|
||||
};
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
delete global.window;
|
||||
});
|
||||
|
||||
describe("isConditionalMediationAvailable", () => {
|
||||
afterEach(() => {
|
||||
delete global.window.PublicKeyCredential;
|
||||
});
|
||||
|
||||
it("is available", async () => {
|
||||
global.window = {
|
||||
PublicKeyCredential: {
|
||||
isConditionalMediationAvailable: fake.resolves(true),
|
||||
},
|
||||
};
|
||||
|
||||
const result = await webauthn.isConditionalMediationAvailable();
|
||||
|
||||
expect(result).to.be.true;
|
||||
});
|
||||
|
||||
describe("is not available", async () => {
|
||||
it("PublicKeyCredential does not exist", async () => {
|
||||
global.window = {};
|
||||
const result = await webauthn.isConditionalMediationAvailable();
|
||||
expect(result).to.be.false;
|
||||
});
|
||||
it("PublicKeyCredential.isConditionalMediationAvailable undefined", async () => {
|
||||
global.window = {
|
||||
PublicKeyCredential: {},
|
||||
};
|
||||
const result = await webauthn.isConditionalMediationAvailable();
|
||||
expect(result).to.be.false;
|
||||
});
|
||||
it("PublicKeyCredential.isConditionalMediationAvailable false", async () => {
|
||||
global.window = {
|
||||
PublicKeyCredential: {
|
||||
isConditionalMediationAvailable: fake.resolves(false),
|
||||
},
|
||||
};
|
||||
const result = await webauthn.isConditionalMediationAvailable();
|
||||
expect(result).to.be.false;
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("authenticate", () => {
|
||||
let httpPostStub;
|
||||
const contextPath = "/some/path";
|
||||
|
||||
const credentialsGetOptions = {
|
||||
challenge: "nRbOrtNKTfJ1JaxfUDKs8j3B-JFqyGQw8DO4u6eV3JA",
|
||||
timeout: 300000,
|
||||
rpId: "localhost",
|
||||
allowCredentials: [],
|
||||
userVerification: "preferred",
|
||||
extensions: {},
|
||||
};
|
||||
|
||||
// This is kind of a self-fulfilling prophecy type of test: we produce array buffers by calling
|
||||
// base64url.decode ; they will then be re-encoded to the same string in the production code.
|
||||
// The ArrayBuffer API is not super friendly.
|
||||
beforeEach(() => {
|
||||
httpPostStub = stub(http, "post");
|
||||
httpPostStub.withArgs(contextPath + "/webauthn/authenticate/options", match.any).resolves({
|
||||
ok: true,
|
||||
status: 200,
|
||||
json: fake.resolves(credentialsGetOptions),
|
||||
});
|
||||
httpPostStub.withArgs(`${contextPath}/login/webauthn`, match.any, match.any).resolves({
|
||||
ok: true,
|
||||
status: 200,
|
||||
json: fake.resolves({
|
||||
authenticated: true,
|
||||
redirectUrl: "/success",
|
||||
}),
|
||||
});
|
||||
|
||||
const validAuthenticatorResponse = {
|
||||
id: "UgghgP5QKozwsSUK1twCj8mpgZs",
|
||||
rawId: base64url.decode("UgghgP5QKozwsSUK1twCj8mpgZs"),
|
||||
response: {
|
||||
authenticatorData: base64url.decode("y9GqwTRaMpzVDbXq1dyEAXVOxrou08k22ggRC45MKNgdAAAAAA"),
|
||||
clientDataJSON: base64url.decode(
|
||||
"eyJ0eXBlIjoid2ViYXV0aG4uZ2V0IiwiY2hhbGxlbmdlIjoiUTdlR0NkNUw2cG9fa01meWNIQnBWRlR5dmd3RklCV0QxZWg5OUktRFhnWSIsIm9yaWdpbiI6Imh0dHBzOi8vZXhhbXBsZS5sb2NhbGhvc3Q6ODQ0MyJ9",
|
||||
),
|
||||
signature: base64url.decode(
|
||||
"MEUCIGT9PAWfU3lMicOXFMpHGcl033dY-sNSJvehlXvvoivyAiEA_D_yOsChERlXX2rFcK6Qx5BaAbx5qdU2hgYDVN6W770",
|
||||
),
|
||||
userHandle: base64url.decode("tyRDnKxdj7uWOT5jrchXu54lo6nf3bWOUvMQnGOXk7g"),
|
||||
},
|
||||
getClientExtensionResults: () => ({}),
|
||||
authenticatorAttachment: "platform",
|
||||
type: "public-key",
|
||||
};
|
||||
global.navigator = {
|
||||
credentials: {
|
||||
get: fake.resolves(validAuthenticatorResponse),
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
http.post.restore();
|
||||
delete global.navigator;
|
||||
});
|
||||
|
||||
it("succeeds", async () => {
|
||||
const redirectUrl = await webauthn.authenticate({ "x-custom": "some-value" }, contextPath, false);
|
||||
|
||||
expect(redirectUrl).to.equal("/success");
|
||||
assert.calledWith(
|
||||
httpPostStub.lastCall,
|
||||
`${contextPath}/login/webauthn`,
|
||||
{ "x-custom": "some-value" },
|
||||
{
|
||||
id: "UgghgP5QKozwsSUK1twCj8mpgZs",
|
||||
rawId: "UgghgP5QKozwsSUK1twCj8mpgZs",
|
||||
credType: "public-key",
|
||||
response: {
|
||||
authenticatorData: "y9GqwTRaMpzVDbXq1dyEAXVOxrou08k22ggRC45MKNgdAAAAAA",
|
||||
clientDataJSON:
|
||||
"eyJ0eXBlIjoid2ViYXV0aG4uZ2V0IiwiY2hhbGxlbmdlIjoiUTdlR0NkNUw2cG9fa01meWNIQnBWRlR5dmd3RklCV0QxZWg5OUktRFhnWSIsIm9yaWdpbiI6Imh0dHBzOi8vZXhhbXBsZS5sb2NhbGhvc3Q6ODQ0MyJ9",
|
||||
signature:
|
||||
"MEUCIGT9PAWfU3lMicOXFMpHGcl033dY-sNSJvehlXvvoivyAiEA_D_yOsChERlXX2rFcK6Qx5BaAbx5qdU2hgYDVN6W770",
|
||||
userHandle: "tyRDnKxdj7uWOT5jrchXu54lo6nf3bWOUvMQnGOXk7g",
|
||||
},
|
||||
clientExtensionResults: {},
|
||||
authenticatorAttachment: "platform",
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
it("calls the authenticator with the correct options", async () => {
|
||||
await webauthn.authenticate({}, contextPath, false);
|
||||
|
||||
assert.calledOnceWithMatch(global.navigator.credentials.get, {
|
||||
publicKey: {
|
||||
challenge: base64url.decode("nRbOrtNKTfJ1JaxfUDKs8j3B-JFqyGQw8DO4u6eV3JA"),
|
||||
timeout: 300000,
|
||||
rpId: "localhost",
|
||||
allowCredentials: [],
|
||||
userVerification: "preferred",
|
||||
extensions: {},
|
||||
},
|
||||
signal: match.any,
|
||||
});
|
||||
});
|
||||
|
||||
describe("authentication failures", () => {
|
||||
it("when authentication options call", async () => {
|
||||
httpPostStub
|
||||
.withArgs(`${contextPath}/webauthn/authenticate/options`, match.any)
|
||||
.rejects(new Error("Connection refused"));
|
||||
|
||||
try {
|
||||
await webauthn.authenticate({}, contextPath, false);
|
||||
} catch (err) {
|
||||
expect(err).to.be.an("error");
|
||||
expect(err.message).to.equal(
|
||||
"Authentication failed. Could not fetch authentication options: Connection refused",
|
||||
);
|
||||
return;
|
||||
}
|
||||
expect.fail("authenticate should throw");
|
||||
});
|
||||
|
||||
it("when authentication options call returns does not return HTTP 200 OK", async () => {
|
||||
httpPostStub.withArgs(`${contextPath}/webauthn/authenticate/options`, match.any).resolves({
|
||||
ok: false,
|
||||
status: 400,
|
||||
});
|
||||
|
||||
try {
|
||||
await webauthn.authenticate({}, contextPath, false);
|
||||
} catch (err) {
|
||||
expect(err).to.be.an("error");
|
||||
expect(err.message).to.equal("Authentication failed. Could not fetch authentication options: HTTP 400");
|
||||
return;
|
||||
}
|
||||
expect.fail("authenticate should throw");
|
||||
});
|
||||
|
||||
it("when authentication options are not valid json", async () => {
|
||||
httpPostStub.withArgs(`${contextPath}/webauthn/authenticate/options`, match.any).resolves({
|
||||
ok: true,
|
||||
status: 200,
|
||||
json: fake.rejects(new Error("Not valid JSON")),
|
||||
});
|
||||
|
||||
try {
|
||||
await webauthn.authenticate({}, contextPath, false);
|
||||
} catch (err) {
|
||||
expect(err).to.be.an("error");
|
||||
expect(err.message).to.equal("Authentication failed. Could not fetch authentication options: Not valid JSON");
|
||||
return;
|
||||
}
|
||||
expect.fail("authenticate should throw");
|
||||
});
|
||||
|
||||
it("when navigator.credentials.get fails", async () => {
|
||||
global.navigator.credentials.get = fake.rejects(new Error("Operation was aborted"));
|
||||
try {
|
||||
await webauthn.authenticate({}, contextPath, false);
|
||||
} catch (err) {
|
||||
expect(err).to.be.an("error");
|
||||
expect(err.message).to.equal(
|
||||
"Authentication failed. Call to navigator.credentials.get failed: Operation was aborted",
|
||||
);
|
||||
return;
|
||||
}
|
||||
expect.fail("authenticate should throw");
|
||||
});
|
||||
|
||||
it("when authentication call fails", async () => {
|
||||
httpPostStub
|
||||
.withArgs(`${contextPath}/login/webauthn`, match.any, match.any)
|
||||
.rejects(new Error("Connection refused"));
|
||||
try {
|
||||
await webauthn.authenticate({}, contextPath, false);
|
||||
} catch (err) {
|
||||
expect(err).to.be.an("error");
|
||||
expect(err.message).to.equal(
|
||||
"Authentication failed. Could not process the authentication request: Connection refused",
|
||||
);
|
||||
return;
|
||||
}
|
||||
expect.fail("authenticate should throw");
|
||||
});
|
||||
|
||||
it("when authentication call does not return HTTP 200 OK", async () => {
|
||||
httpPostStub.withArgs(`${contextPath}/login/webauthn`, match.any, match.any).resolves({
|
||||
ok: false,
|
||||
status: 400,
|
||||
});
|
||||
try {
|
||||
await webauthn.authenticate({}, contextPath, false);
|
||||
} catch (err) {
|
||||
expect(err).to.be.an("error");
|
||||
expect(err.message).to.equal("Authentication failed. Could not process the authentication request: HTTP 400");
|
||||
return;
|
||||
}
|
||||
expect.fail("authenticate should throw");
|
||||
});
|
||||
|
||||
it("when authentication call does not return JSON", async () => {
|
||||
httpPostStub.withArgs(`${contextPath}/login/webauthn`, match.any, match.any).resolves({
|
||||
ok: true,
|
||||
status: 200,
|
||||
json: fake.rejects(new Error("Not valid JSON")),
|
||||
});
|
||||
try {
|
||||
await webauthn.authenticate({}, contextPath, false);
|
||||
} catch (err) {
|
||||
expect(err).to.be.an("error");
|
||||
expect(err.message).to.equal(
|
||||
"Authentication failed. Could not process the authentication request: Not valid JSON",
|
||||
);
|
||||
return;
|
||||
}
|
||||
expect.fail("authenticate should throw");
|
||||
});
|
||||
|
||||
it("when authentication call returns null", async () => {
|
||||
httpPostStub.withArgs(`${contextPath}/login/webauthn`, match.any, match.any).resolves({
|
||||
ok: true,
|
||||
status: 200,
|
||||
json: fake.resolves(null),
|
||||
});
|
||||
try {
|
||||
await webauthn.authenticate({}, contextPath, false);
|
||||
} catch (err) {
|
||||
expect(err).to.be.an("error");
|
||||
expect(err.message).to.equal(
|
||||
'Authentication failed. Expected {"authenticated": true, "redirectUrl": "..."}, server responded with: null',
|
||||
);
|
||||
return;
|
||||
}
|
||||
expect.fail("authenticate should throw");
|
||||
});
|
||||
|
||||
it('when authentication call returns {"authenticated":false}', async () => {
|
||||
httpPostStub.withArgs(`${contextPath}/login/webauthn`, match.any, match.any).resolves({
|
||||
ok: true,
|
||||
status: 200,
|
||||
json: fake.resolves({
|
||||
authenticated: false,
|
||||
}),
|
||||
});
|
||||
try {
|
||||
await webauthn.authenticate({}, contextPath, false);
|
||||
} catch (err) {
|
||||
expect(err).to.be.an("error");
|
||||
expect(err.message).to.equal(
|
||||
'Authentication failed. Expected {"authenticated": true, "redirectUrl": "..."}, server responded with: {"authenticated":false}',
|
||||
);
|
||||
return;
|
||||
}
|
||||
expect.fail("authenticate should throw");
|
||||
});
|
||||
|
||||
it("when authentication call returns no redirectUrl", async () => {
|
||||
httpPostStub.withArgs(`${contextPath}/login/webauthn`, match.any, match.any).resolves({
|
||||
ok: true,
|
||||
status: 200,
|
||||
json: fake.resolves({
|
||||
authenticated: true,
|
||||
}),
|
||||
});
|
||||
try {
|
||||
await webauthn.authenticate({}, contextPath, false);
|
||||
} catch (err) {
|
||||
expect(err).to.be.an("error");
|
||||
expect(err.message).to.equal(
|
||||
'Authentication failed. Expected {"authenticated": true, "redirectUrl": "..."}, server responded with: {"authenticated":true}',
|
||||
);
|
||||
return;
|
||||
}
|
||||
expect.fail("authenticate should throw");
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("register", () => {
|
||||
let httpPostStub;
|
||||
const contextPath = "/some/path";
|
||||
|
||||
beforeEach(() => {
|
||||
const credentialsCreateOptions = {
|
||||
rp: {
|
||||
name: "Spring Security Relying Party",
|
||||
id: "example.localhost",
|
||||
},
|
||||
user: {
|
||||
name: "user",
|
||||
id: "eatPy60xmXG_58JrIiIBa5wq8Y76c7MD6mnY5vW8yP8",
|
||||
displayName: "user",
|
||||
},
|
||||
challenge: "s0hBOfkSaVLXdsbyD8jii6t2IjUd-eiTP1Cmeuo1qUo",
|
||||
pubKeyCredParams: [
|
||||
{
|
||||
type: "public-key",
|
||||
alg: -8,
|
||||
},
|
||||
{
|
||||
type: "public-key",
|
||||
alg: -7,
|
||||
},
|
||||
{
|
||||
type: "public-key",
|
||||
alg: -257,
|
||||
},
|
||||
],
|
||||
timeout: 300000,
|
||||
excludeCredentials: [
|
||||
{
|
||||
id: "nOsjw8eaaqSwVdTBBYE1FqfGdHs",
|
||||
type: "public-key",
|
||||
transports: [],
|
||||
},
|
||||
],
|
||||
authenticatorSelection: {
|
||||
residentKey: "required",
|
||||
userVerification: "preferred",
|
||||
},
|
||||
attestation: "direct",
|
||||
extensions: { credProps: true },
|
||||
};
|
||||
const validAuthenticatorResponse = {
|
||||
authenticatorAttachment: "platform",
|
||||
id: "9wAuex_025BgEQrs7fOypo5SGBA",
|
||||
rawId: base64url.decode("9wAuex_025BgEQrs7fOypo5SGBA"),
|
||||
response: {
|
||||
attestationObject: base64url.decode(
|
||||
"o2NmbXRkbm9uZWdhdHRTdG10oGhhdXRoRGF0YViYy9GqwTRaMpzVDbXq1dyEAXVOxrou08k22ggRC45MKNhdAAAAAPv8MAcVTk7MjAtuAgVX170AFPcALnsf9NuQYBEK7O3zsqaOUhgQpQECAyYgASFYIMB9pM2BeSeEG83fAKFVSLKIfvDBBVoyGgMoiGxE-6WgIlggazAojM5sduQy2M7rz1do55nVaNLGXh8k4xBHz-Oy91E",
|
||||
),
|
||||
getAuthenticatorData: () =>
|
||||
base64url.decode(
|
||||
"y9GqwTRaMpzVDbXq1dyEAXVOxrou08k22ggRC45MKNhdAAAAAPv8MAcVTk7MjAtuAgVX170AFPcALnsf9NuQYBEK7O3zsqaOUhgQpQECAyYgASFYIMB9pM2BeSeEG83fAKFVSLKIfvDBBVoyGgMoiGxE-6WgIlggazAojM5sduQy2M7rz1do55nVaNLGXh8k4xBHz-Oy91E",
|
||||
),
|
||||
clientDataJSON: base64url.decode(
|
||||
"eyJ0eXBlIjoid2ViYXV0aG4uY3JlYXRlIiwiY2hhbGxlbmdlIjoiUVdwd3lUcXJpYVlqbVdnOWFvZ0FxUlRKNVFYMFBGV2JWR2xNeGNsVjZhcyIsIm9yaWdpbiI6Imh0dHBzOi8vZXhhbXBsZS5sb2NhbGhvc3Q6ODQ0MyJ9",
|
||||
),
|
||||
getPublicKey: () =>
|
||||
base64url.decode(
|
||||
"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEwH2kzYF5J4Qbzd8AoVVIsoh-8MEFWjIaAyiIbET7paBrMCiMzmx25DLYzuvPV2jnmdVo0sZeHyTjEEfP47L3UQ",
|
||||
),
|
||||
getPublicKeyAlgorithm: () => -7,
|
||||
getTransports: () => ["internal"],
|
||||
},
|
||||
type: "public-key",
|
||||
getClientExtensionResults: () => ({}),
|
||||
};
|
||||
global.navigator = {
|
||||
credentials: {
|
||||
create: fake.resolves(validAuthenticatorResponse),
|
||||
},
|
||||
};
|
||||
httpPostStub = stub(http, "post");
|
||||
httpPostStub.withArgs(contextPath + "/webauthn/register/options", match.any).resolves({
|
||||
ok: true,
|
||||
status: 200,
|
||||
json: fake.resolves(credentialsCreateOptions),
|
||||
});
|
||||
httpPostStub.withArgs(`${contextPath}/webauthn/register`, match.any, match.any).resolves({
|
||||
ok: true,
|
||||
json: fake.resolves({
|
||||
success: true,
|
||||
}),
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
httpPostStub.restore();
|
||||
delete global.navigator;
|
||||
});
|
||||
|
||||
it("succeeds", async () => {
|
||||
const contextPath = "/some/path";
|
||||
const headers = { _csrf: "csrf-value" };
|
||||
|
||||
await webauthn.register(headers, contextPath, "my passkey");
|
||||
assert.calledWithExactly(
|
||||
httpPostStub.lastCall,
|
||||
`${contextPath}/webauthn/register`,
|
||||
headers,
|
||||
match({
|
||||
publicKey: {
|
||||
credential: {
|
||||
id: "9wAuex_025BgEQrs7fOypo5SGBA",
|
||||
rawId: "9wAuex_025BgEQrs7fOypo5SGBA",
|
||||
response: {
|
||||
attestationObject:
|
||||
"o2NmbXRkbm9uZWdhdHRTdG10oGhhdXRoRGF0YViYy9GqwTRaMpzVDbXq1dyEAXVOxrou08k22ggRC45MKNhdAAAAAPv8MAcVTk7MjAtuAgVX170AFPcALnsf9NuQYBEK7O3zsqaOUhgQpQECAyYgASFYIMB9pM2BeSeEG83fAKFVSLKIfvDBBVoyGgMoiGxE-6WgIlggazAojM5sduQy2M7rz1do55nVaNLGXh8k4xBHz-Oy91E",
|
||||
clientDataJSON:
|
||||
"eyJ0eXBlIjoid2ViYXV0aG4uY3JlYXRlIiwiY2hhbGxlbmdlIjoiUVdwd3lUcXJpYVlqbVdnOWFvZ0FxUlRKNVFYMFBGV2JWR2xNeGNsVjZhcyIsIm9yaWdpbiI6Imh0dHBzOi8vZXhhbXBsZS5sb2NhbGhvc3Q6ODQ0MyJ9",
|
||||
transports: ["internal"],
|
||||
},
|
||||
type: "public-key",
|
||||
clientExtensionResults: {},
|
||||
authenticatorAttachment: "platform",
|
||||
},
|
||||
label: "my passkey",
|
||||
},
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("calls the authenticator with the correct options", async () => {
|
||||
await webauthn.register({}, contextPath, "my passkey");
|
||||
|
||||
assert.calledOnceWithExactly(
|
||||
global.navigator.credentials.create,
|
||||
match({
|
||||
publicKey: {
|
||||
rp: {
|
||||
name: "Spring Security Relying Party",
|
||||
id: "example.localhost",
|
||||
},
|
||||
user: {
|
||||
name: "user",
|
||||
id: base64url.decode("eatPy60xmXG_58JrIiIBa5wq8Y76c7MD6mnY5vW8yP8"),
|
||||
displayName: "user",
|
||||
},
|
||||
challenge: base64url.decode("s0hBOfkSaVLXdsbyD8jii6t2IjUd-eiTP1Cmeuo1qUo"),
|
||||
pubKeyCredParams: [
|
||||
{
|
||||
type: "public-key",
|
||||
alg: -8,
|
||||
},
|
||||
{
|
||||
type: "public-key",
|
||||
alg: -7,
|
||||
},
|
||||
{
|
||||
type: "public-key",
|
||||
alg: -257,
|
||||
},
|
||||
],
|
||||
timeout: 300000,
|
||||
excludeCredentials: [
|
||||
{
|
||||
id: base64url.decode("nOsjw8eaaqSwVdTBBYE1FqfGdHs"),
|
||||
type: "public-key",
|
||||
transports: [],
|
||||
},
|
||||
],
|
||||
authenticatorSelection: {
|
||||
residentKey: "required",
|
||||
userVerification: "preferred",
|
||||
},
|
||||
attestation: "direct",
|
||||
extensions: { credProps: true },
|
||||
},
|
||||
signal: match.any,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
describe("registration failures", () => {
|
||||
it("when label is missing", async () => {
|
||||
try {
|
||||
await webauthn.register({}, "/", "");
|
||||
} catch (err) {
|
||||
expect(err).to.be.an("error");
|
||||
expect(err.message).to.equal("Error: Passkey Label is required");
|
||||
return;
|
||||
}
|
||||
expect.fail("register should throw");
|
||||
});
|
||||
|
||||
it("when cannot get the registration options", async () => {
|
||||
httpPostStub.withArgs(match.any, match.any).rejects(new Error("Server threw an error"));
|
||||
try {
|
||||
await webauthn.register({}, "/", "my passkey");
|
||||
} catch (err) {
|
||||
expect(err).to.be.an("error");
|
||||
expect(err.message).to.equal(
|
||||
"Registration failed. Could not fetch registration options: Server threw an error",
|
||||
);
|
||||
return;
|
||||
}
|
||||
expect.fail("register should throw");
|
||||
});
|
||||
|
||||
it("when registration options call does not return HTTP 200 OK", async () => {
|
||||
httpPostStub.withArgs(match.any, match.any).resolves({
|
||||
ok: false,
|
||||
status: 400,
|
||||
});
|
||||
try {
|
||||
await webauthn.register({}, "/", "my passkey");
|
||||
} catch (err) {
|
||||
expect(err).to.be.an("error");
|
||||
expect(err.message).to.equal(
|
||||
"Registration failed. Could not fetch registration options: Server responded with HTTP 400",
|
||||
);
|
||||
return;
|
||||
}
|
||||
expect.fail("register should throw");
|
||||
});
|
||||
|
||||
it("when registration options are not valid JSON", async () => {
|
||||
httpPostStub.withArgs(match.any, match.any).resolves({
|
||||
ok: true,
|
||||
status: 200,
|
||||
json: fake.rejects(new Error("Not a JSON response")),
|
||||
});
|
||||
try {
|
||||
await webauthn.register({}, "/", "my passkey");
|
||||
} catch (err) {
|
||||
expect(err).to.be.an("error");
|
||||
expect(err.message).to.equal(
|
||||
"Registration failed. Could not fetch registration options: Not a JSON response",
|
||||
);
|
||||
return;
|
||||
}
|
||||
expect.fail("register should throw");
|
||||
});
|
||||
|
||||
it("when navigator.credentials.create fails", async () => {
|
||||
global.navigator = {
|
||||
credentials: {
|
||||
create: fake.rejects(new Error("authenticator threw an error")),
|
||||
},
|
||||
};
|
||||
try {
|
||||
await webauthn.register({}, contextPath, "my passkey");
|
||||
} catch (err) {
|
||||
expect(err).to.be.an("error");
|
||||
expect(err.message).to.equal(
|
||||
"Registration failed. Call to navigator.credentials.create failed: authenticator threw an error",
|
||||
);
|
||||
expect(err.cause).to.deep.equal(new Error("authenticator threw an error"));
|
||||
return;
|
||||
}
|
||||
expect.fail("register should throw");
|
||||
});
|
||||
|
||||
it("when registration call fails", async () => {
|
||||
httpPostStub
|
||||
.withArgs(`${contextPath}/webauthn/register`, match.any, match.any)
|
||||
.rejects(new Error("Connection refused"));
|
||||
try {
|
||||
await webauthn.register({}, contextPath, "my passkey");
|
||||
} catch (err) {
|
||||
expect(err).to.be.an("error");
|
||||
expect(err.message).to.equal(
|
||||
"Registration failed. Could not process the registration request: Connection refused",
|
||||
);
|
||||
expect(err.cause).to.deep.equal(new Error("Connection refused"));
|
||||
return;
|
||||
}
|
||||
expect.fail("register should throw");
|
||||
});
|
||||
|
||||
it("when registration call does not return HTTP 200 OK", async () => {
|
||||
httpPostStub.withArgs(`${contextPath}/webauthn/register`, match.any, match.any).resolves({
|
||||
ok: false,
|
||||
status: 400,
|
||||
});
|
||||
try {
|
||||
await webauthn.register({}, contextPath, "my passkey");
|
||||
} catch (err) {
|
||||
expect(err).to.be.an("error");
|
||||
expect(err.message).to.equal("Registration failed. Could not process the registration request: HTTP 400");
|
||||
return;
|
||||
}
|
||||
expect.fail("register should throw");
|
||||
});
|
||||
|
||||
it("when registration call does not return JSON", async () => {
|
||||
httpPostStub.withArgs(`${contextPath}/webauthn/register`, match.any, match.any).resolves({
|
||||
ok: true,
|
||||
status: 200,
|
||||
json: fake.rejects(new Error("Not valid JSON")),
|
||||
});
|
||||
try {
|
||||
await webauthn.register({}, contextPath, "my passkey");
|
||||
} catch (err) {
|
||||
expect(err).to.be.an("error");
|
||||
expect(err.message).to.equal(
|
||||
"Registration failed. Could not process the registration request: Not valid JSON",
|
||||
);
|
||||
expect(err.cause).to.deep.equal(new Error("Not valid JSON"));
|
||||
return;
|
||||
}
|
||||
expect.fail("register should throw");
|
||||
});
|
||||
|
||||
it("when registration call returns null", async () => {
|
||||
httpPostStub.withArgs(`${contextPath}/webauthn/register`, match.any, match.any).resolves({
|
||||
ok: true,
|
||||
status: 200,
|
||||
json: fake.resolves(null),
|
||||
});
|
||||
try {
|
||||
await webauthn.register({}, contextPath, "my passkey");
|
||||
} catch (err) {
|
||||
expect(err).to.be.an("error");
|
||||
expect(err.message).to.equal("Registration failed. Server responded with: null");
|
||||
return;
|
||||
}
|
||||
expect.fail("register should throw");
|
||||
});
|
||||
|
||||
it('when registration call returns {"success":false}', async () => {
|
||||
httpPostStub.withArgs(`${contextPath}/webauthn/register`, match.any, match.any).resolves({
|
||||
ok: true,
|
||||
status: 200,
|
||||
json: fake.resolves({ success: false }),
|
||||
});
|
||||
try {
|
||||
await webauthn.register({}, contextPath, "my passkey");
|
||||
} catch (err) {
|
||||
expect(err).to.be.an("error");
|
||||
expect(err.message).to.equal('Registration failed. Server responded with: {"success":false}');
|
||||
return;
|
||||
}
|
||||
expect.fail("register should throw");
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,106 @@
|
||||
/*
|
||||
* Copyright 2002-2024 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
"use strict";
|
||||
|
||||
import "./bootstrap.js";
|
||||
import { expect } from "chai";
|
||||
import { setupLogin } from "../lib/webauthn-login.js";
|
||||
import webauthn from "../lib/webauthn-core.js";
|
||||
import { assert, fake, match, stub } from "sinon";
|
||||
|
||||
describe("webauthn-login", () => {
|
||||
describe("bootstrap", () => {
|
||||
let authenticateStub;
|
||||
let isConditionalMediationAvailableStub;
|
||||
let signinButton;
|
||||
|
||||
beforeEach(() => {
|
||||
isConditionalMediationAvailableStub = stub(webauthn, "isConditionalMediationAvailable").resolves(false);
|
||||
authenticateStub = stub(webauthn, "authenticate").resolves("/success");
|
||||
signinButton = {
|
||||
addEventListener: fake(),
|
||||
};
|
||||
|
||||
global.console = {
|
||||
error: stub(),
|
||||
};
|
||||
global.window = {
|
||||
location: {
|
||||
href: {},
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
authenticateStub.restore();
|
||||
isConditionalMediationAvailableStub.restore();
|
||||
});
|
||||
|
||||
it("sets up a click event listener on the signin button", async () => {
|
||||
await setupLogin({}, "/some/path", signinButton);
|
||||
|
||||
assert.calledOnceWithMatch(signinButton.addEventListener, "click", match.typeOf("function"));
|
||||
});
|
||||
|
||||
// FIXME: conditional mediation triggers browser crashes
|
||||
// See: https://github.com/rwinch/spring-security-webauthn/issues/73
|
||||
xit("uses conditional mediation when available", async () => {
|
||||
isConditionalMediationAvailableStub.resolves(true);
|
||||
|
||||
const headers = { "x-header": "value" };
|
||||
const contextPath = "/some/path";
|
||||
|
||||
await setupLogin(headers, contextPath, signinButton);
|
||||
|
||||
assert.calledOnceWithExactly(authenticateStub, headers, contextPath, true);
|
||||
expect(global.window.location.href).to.equal("/success");
|
||||
});
|
||||
|
||||
it("does not call authenticate when conditional mediation is not available", async () => {
|
||||
await setupLogin({}, "/", signinButton);
|
||||
|
||||
assert.notCalled(authenticateStub);
|
||||
});
|
||||
|
||||
it("calls authenticate when the signin button is clicked", async () => {
|
||||
const headers = { "x-header": "value" };
|
||||
const contextPath = "/some/path";
|
||||
|
||||
await setupLogin(headers, contextPath, signinButton);
|
||||
|
||||
// Call the event listener
|
||||
await signinButton.addEventListener.firstCall.lastArg();
|
||||
|
||||
assert.calledOnceWithExactly(authenticateStub, headers, contextPath, false);
|
||||
expect(global.window.location.href).to.equal("/success");
|
||||
});
|
||||
|
||||
it("handles authentication errors", async () => {
|
||||
authenticateStub.rejects(new Error("Authentication failed"));
|
||||
await setupLogin({}, "/some/path", signinButton);
|
||||
|
||||
// Call the event listener
|
||||
await signinButton.addEventListener.firstCall.lastArg();
|
||||
|
||||
expect(global.window.location.href).to.equal(`/some/path/login?error`);
|
||||
assert.calledOnceWithMatch(
|
||||
global.console.error,
|
||||
match.instanceOf(Error).and(match.has("message", "Authentication failed")),
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,279 @@
|
||||
/*
|
||||
* Copyright 2002-2024 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
"use strict";
|
||||
|
||||
import "./bootstrap.js";
|
||||
import { expect, util, Assertion } from "chai";
|
||||
import { setupRegistration } from "../lib/webauthn-registration.js";
|
||||
import webauthn from "../lib/webauthn-core.js";
|
||||
import { assert, fake, match, stub } from "sinon";
|
||||
|
||||
describe("webauthn-registration", () => {
|
||||
before(() => {
|
||||
Assertion.addProperty("visible", function () {
|
||||
const obj = util.flag(this, "object");
|
||||
new Assertion(obj).to.have.nested.property("style.display", "block");
|
||||
});
|
||||
Assertion.addProperty("hidden", function () {
|
||||
const obj = util.flag(this, "object");
|
||||
new Assertion(obj).to.have.nested.property("style.display", "none");
|
||||
});
|
||||
});
|
||||
|
||||
describe("bootstrap", () => {
|
||||
let registerStub;
|
||||
let registerButton;
|
||||
let labelField;
|
||||
let errorPopup;
|
||||
let successPopup;
|
||||
let deleteForms;
|
||||
let ui;
|
||||
|
||||
beforeEach(() => {
|
||||
registerStub = stub(webauthn, "register").resolves(undefined);
|
||||
errorPopup = {
|
||||
style: {
|
||||
display: undefined,
|
||||
},
|
||||
textContent: undefined,
|
||||
};
|
||||
successPopup = {
|
||||
style: {
|
||||
display: undefined,
|
||||
},
|
||||
textContent: undefined,
|
||||
};
|
||||
registerButton = {
|
||||
addEventListener: fake(),
|
||||
};
|
||||
labelField = {
|
||||
value: undefined,
|
||||
};
|
||||
deleteForms = [];
|
||||
ui = {
|
||||
getSuccess: function () {
|
||||
return successPopup;
|
||||
},
|
||||
getError: function () {
|
||||
return errorPopup;
|
||||
},
|
||||
getRegisterButton: function () {
|
||||
return registerButton;
|
||||
},
|
||||
getLabelInput: function () {
|
||||
return labelField;
|
||||
},
|
||||
getDeleteForms: function () {
|
||||
return deleteForms;
|
||||
},
|
||||
};
|
||||
global.window = {
|
||||
location: {
|
||||
href: {},
|
||||
},
|
||||
};
|
||||
global.console = {
|
||||
error: stub(),
|
||||
};
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
registerStub.restore();
|
||||
delete global.window;
|
||||
});
|
||||
|
||||
describe("when webauthn is not supported", () => {
|
||||
beforeEach(() => {
|
||||
delete global.window.PublicKeyCredential;
|
||||
});
|
||||
|
||||
it("does not set up a click event listener", async () => {
|
||||
await setupRegistration({}, "/", ui);
|
||||
|
||||
assert.notCalled(registerButton.addEventListener);
|
||||
});
|
||||
|
||||
it("shows an error popup", async () => {
|
||||
await setupRegistration({}, "/", ui);
|
||||
|
||||
expect(errorPopup).to.be.visible;
|
||||
expect(errorPopup.textContent).to.equal("WebAuthn is not supported");
|
||||
expect(successPopup).to.be.hidden;
|
||||
});
|
||||
});
|
||||
|
||||
describe("when webauthn is supported", () => {
|
||||
beforeEach(() => {
|
||||
global.window.PublicKeyCredential = fake();
|
||||
});
|
||||
|
||||
it("hides the popups", async () => {
|
||||
await setupRegistration({}, "/", ui);
|
||||
|
||||
expect(successPopup).to.be.hidden;
|
||||
expect(errorPopup).to.be.hidden;
|
||||
});
|
||||
|
||||
it("sets up a click event listener on the register button", async () => {
|
||||
await setupRegistration({}, "/some/path", ui);
|
||||
|
||||
assert.calledOnceWithMatch(registerButton.addEventListener, "click", match.typeOf("function"));
|
||||
});
|
||||
|
||||
describe(`when the query string contains "success"`, () => {
|
||||
beforeEach(() => {
|
||||
global.window.location.search = "?success&continue=true";
|
||||
});
|
||||
|
||||
it("shows the success popup", async () => {
|
||||
await setupRegistration({}, "/", ui);
|
||||
|
||||
expect(successPopup).to.be.visible;
|
||||
expect(errorPopup).to.be.hidden;
|
||||
});
|
||||
});
|
||||
|
||||
describe("when the register button is clicked", () => {
|
||||
const headers = { "x-header": "value" };
|
||||
const contextPath = "/some/path";
|
||||
|
||||
beforeEach(async () => {
|
||||
await setupRegistration(headers, contextPath, ui);
|
||||
});
|
||||
|
||||
it("hides all the popups", async () => {
|
||||
successPopup.textContent = "dummy-content";
|
||||
successPopup.style.display = "block";
|
||||
errorPopup.textContent = "dummy-content";
|
||||
errorPopup.style.display = "block";
|
||||
|
||||
await registerButton.addEventListener.firstCall.lastArg();
|
||||
|
||||
expect(successPopup).to.be.hidden;
|
||||
expect(errorPopup).to.be.hidden;
|
||||
});
|
||||
|
||||
it("calls register", async () => {
|
||||
labelField.value = "passkey name";
|
||||
|
||||
await registerButton.addEventListener.firstCall.lastArg();
|
||||
|
||||
assert.calledOnceWithExactly(registerStub, headers, contextPath, labelField.value);
|
||||
});
|
||||
|
||||
it("navigates to success page", async () => {
|
||||
labelField.value = "passkey name";
|
||||
|
||||
await registerButton.addEventListener.firstCall.lastArg();
|
||||
|
||||
expect(global.window.location.href).to.equal(`${contextPath}/webauthn/register?success`);
|
||||
});
|
||||
|
||||
it("handles errors", async () => {
|
||||
registerStub.rejects(new Error("The registration failed"));
|
||||
|
||||
await registerButton.addEventListener.firstCall.lastArg();
|
||||
|
||||
expect(errorPopup.textContent).to.equal("The registration failed");
|
||||
expect(errorPopup).to.be.visible;
|
||||
expect(successPopup).to.be.hidden;
|
||||
assert.calledOnceWithMatch(
|
||||
global.console.error,
|
||||
match.instanceOf(Error).and(match.has("message", "The registration failed")),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("delete", () => {
|
||||
beforeEach(() => {
|
||||
global.fetch = fake.resolves({ ok: true });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
delete global.fetch;
|
||||
});
|
||||
|
||||
it("no errors when no forms", async () => {
|
||||
await setupRegistration({}, "/some/path", ui);
|
||||
});
|
||||
|
||||
it("sets up forms for fetch", async () => {
|
||||
const deleteFormOne = {
|
||||
addEventListener: fake(),
|
||||
};
|
||||
const deleteFormTwo = {
|
||||
addEventListener: fake(),
|
||||
};
|
||||
deleteForms = [deleteFormOne, deleteFormTwo];
|
||||
|
||||
await setupRegistration({}, "", ui);
|
||||
|
||||
assert.calledOnceWithMatch(deleteFormOne.addEventListener, "submit", match.typeOf("function"));
|
||||
assert.calledOnceWithMatch(deleteFormTwo.addEventListener, "submit", match.typeOf("function"));
|
||||
});
|
||||
|
||||
describe("when the delete button is clicked", () => {
|
||||
it("calls POST to the form action", async () => {
|
||||
const contextPath = "/some/path";
|
||||
const deleteForm = {
|
||||
addEventListener: fake(),
|
||||
action: `${contextPath}/webauthn/1234`,
|
||||
};
|
||||
deleteForms = [deleteForm];
|
||||
const headers = {
|
||||
"X-CSRF-TOKEN": "token",
|
||||
};
|
||||
|
||||
await setupRegistration(headers, contextPath, ui);
|
||||
|
||||
const clickEvent = {
|
||||
preventDefault: fake(),
|
||||
};
|
||||
await deleteForm.addEventListener.firstCall.lastArg(clickEvent);
|
||||
assert.calledOnce(clickEvent.preventDefault);
|
||||
assert.calledOnceWithExactly(global.fetch, `/some/path/webauthn/1234`, {
|
||||
method: "DELETE",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
...headers,
|
||||
},
|
||||
});
|
||||
expect(global.window.location.href).to.equal(`/some/path/webauthn/register?success`);
|
||||
});
|
||||
});
|
||||
|
||||
it("handles errors", async () => {
|
||||
global.fetch = fake.rejects("Server threw an error");
|
||||
global.window.location.href = "/initial/location";
|
||||
const deleteForm = {
|
||||
addEventListener: fake(),
|
||||
};
|
||||
deleteForms = [deleteForm];
|
||||
|
||||
await setupRegistration({}, "", ui);
|
||||
const clickEvent = { preventDefault: fake() };
|
||||
await deleteForm.addEventListener.firstCall.lastArg(clickEvent);
|
||||
|
||||
expect(errorPopup).to.be.visible;
|
||||
expect(errorPopup.textContent).to.equal("Server threw an error");
|
||||
// URL does not change
|
||||
expect(global.window.location.href).to.equal("/initial/location");
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user