Add Passkeys Support
Closes gh-13305
This commit is contained in:
2
javascript/.gitignore
vendored
Normal file
2
javascript/.gitignore
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
node_modules/
|
||||
dist/
|
||||
3
javascript/.prettierrc
Normal file
3
javascript/.prettierrc
Normal file
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"printWidth": 120
|
||||
}
|
||||
30
javascript/eslint.config.js
Normal file
30
javascript/eslint.config.js
Normal file
@@ -0,0 +1,30 @@
|
||||
import globals from "globals";
|
||||
import eslintConfigPrettier from "eslint-plugin-prettier/recommended";
|
||||
|
||||
export default [
|
||||
{
|
||||
ignores: ["build/**/*"],
|
||||
},
|
||||
{
|
||||
files: ["lib/**/*.js"],
|
||||
languageOptions: {
|
||||
sourceType: "module",
|
||||
globals: {
|
||||
...globals.browser,
|
||||
gobalThis: "readonly",
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
files: ["test/**/*.js"],
|
||||
languageOptions: {
|
||||
globals: {
|
||||
...globals.browser,
|
||||
...globals.mocha,
|
||||
...globals.chai,
|
||||
...globals.nodeBuiltin,
|
||||
},
|
||||
},
|
||||
},
|
||||
eslintConfigPrettier,
|
||||
];
|
||||
43
javascript/lib/abort-controller.js
Normal file
43
javascript/lib/abort-controller.js
Normal file
@@ -0,0 +1,43 @@
|
||||
/*
|
||||
* 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";
|
||||
|
||||
const holder = {
|
||||
controller: new AbortController(),
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns a new AbortSignal to be used in the options for the registration and authentication ceremonies.
|
||||
* Aborts the existing AbortController if it exists, cancelling any existing ceremony.
|
||||
*
|
||||
* The authentication ceremony, when triggered with conditional mediation, shows a non-modal
|
||||
* interaction. If the user does not interact with the non-modal dialog, the existing ceremony MUST
|
||||
* be cancelled before initiating a new one, hence the need for a singleton AbortController.
|
||||
*
|
||||
* @returns {AbortSignal} a new, non-aborted AbortSignal
|
||||
*/
|
||||
function newSignal() {
|
||||
if (!!holder.controller) {
|
||||
holder.controller.abort("Initiating new WebAuthN ceremony, cancelling current ceremony");
|
||||
}
|
||||
holder.controller = new AbortController();
|
||||
return holder.controller.signal;
|
||||
}
|
||||
|
||||
export default {
|
||||
newSignal,
|
||||
};
|
||||
33
javascript/lib/base64url.js
Normal file
33
javascript/lib/base64url.js
Normal file
@@ -0,0 +1,33 @@
|
||||
/*
|
||||
* 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";
|
||||
|
||||
export default {
|
||||
encode: function (buffer) {
|
||||
const base64 = window.btoa(String.fromCharCode(...new Uint8Array(buffer)));
|
||||
return base64.replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
|
||||
},
|
||||
decode: function (base64url) {
|
||||
const base64 = base64url.replace(/-/g, "+").replace(/_/g, "/");
|
||||
const binStr = window.atob(base64);
|
||||
const bin = new Uint8Array(binStr.length);
|
||||
for (let i = 0; i < binStr.length; i++) {
|
||||
bin[i] = binStr.charCodeAt(i);
|
||||
}
|
||||
return bin.buffer;
|
||||
},
|
||||
};
|
||||
33
javascript/lib/http.js
Normal file
33
javascript/lib/http.js
Normal file
@@ -0,0 +1,33 @@
|
||||
/*
|
||||
* 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";
|
||||
|
||||
async function post(url, headers, body) {
|
||||
const options = {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
...headers,
|
||||
},
|
||||
};
|
||||
if (body) {
|
||||
options.body = JSON.stringify(body);
|
||||
}
|
||||
return fetch(url, options);
|
||||
}
|
||||
|
||||
export default { post };
|
||||
24
javascript/lib/index.js
Normal file
24
javascript/lib/index.js
Normal file
@@ -0,0 +1,24 @@
|
||||
/*
|
||||
* 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 { setupLogin } from "./webauthn-login.js";
|
||||
import { setupRegistration } from "./webauthn-registration.js";
|
||||
|
||||
// Make "setup" available in the window domain, so it can be run with "setupLogin()"
|
||||
window.setupLogin = setupLogin;
|
||||
window.setupRegistration = setupRegistration;
|
||||
194
javascript/lib/webauthn-core.js
Normal file
194
javascript/lib/webauthn-core.js
Normal file
@@ -0,0 +1,194 @@
|
||||
/*
|
||||
* 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 base64url from "./base64url.js";
|
||||
import http from "./http.js";
|
||||
import abortController from "./abort-controller.js";
|
||||
|
||||
async function isConditionalMediationAvailable() {
|
||||
return !!(
|
||||
window.PublicKeyCredential &&
|
||||
window.PublicKeyCredential.isConditionalMediationAvailable &&
|
||||
(await window.PublicKeyCredential.isConditionalMediationAvailable())
|
||||
);
|
||||
}
|
||||
|
||||
async function authenticate(headers, contextPath, useConditionalMediation) {
|
||||
let options;
|
||||
try {
|
||||
const optionsResponse = await http.post(`${contextPath}/webauthn/authenticate/options`, headers);
|
||||
if (!optionsResponse.ok) {
|
||||
throw new Error(`HTTP ${optionsResponse.status}`);
|
||||
}
|
||||
options = await optionsResponse.json();
|
||||
} catch (err) {
|
||||
throw new Error(`Authentication failed. Could not fetch authentication options: ${err.message}`, { cause: err });
|
||||
}
|
||||
|
||||
// FIXME: Use https://www.w3.org/TR/webauthn-3/#sctn-parseRequestOptionsFromJSON
|
||||
const decodedOptions = {
|
||||
...options,
|
||||
challenge: base64url.decode(options.challenge),
|
||||
};
|
||||
|
||||
// Invoke the WebAuthn get() method.
|
||||
const credentialOptions = {
|
||||
publicKey: decodedOptions,
|
||||
signal: abortController.newSignal(),
|
||||
};
|
||||
if (useConditionalMediation) {
|
||||
// Request a conditional UI
|
||||
credentialOptions.mediation = "conditional";
|
||||
}
|
||||
|
||||
let cred;
|
||||
try {
|
||||
cred = await navigator.credentials.get(credentialOptions);
|
||||
} catch (err) {
|
||||
throw new Error(`Authentication failed. Call to navigator.credentials.get failed: ${err.message}`, { cause: err });
|
||||
}
|
||||
|
||||
const { response, type: credType } = cred;
|
||||
let userHandle;
|
||||
if (response.userHandle) {
|
||||
userHandle = base64url.encode(response.userHandle);
|
||||
}
|
||||
const body = {
|
||||
id: cred.id,
|
||||
rawId: base64url.encode(cred.rawId),
|
||||
response: {
|
||||
authenticatorData: base64url.encode(response.authenticatorData),
|
||||
clientDataJSON: base64url.encode(response.clientDataJSON),
|
||||
signature: base64url.encode(response.signature),
|
||||
userHandle,
|
||||
},
|
||||
credType,
|
||||
clientExtensionResults: cred.getClientExtensionResults(),
|
||||
authenticatorAttachment: cred.authenticatorAttachment,
|
||||
};
|
||||
|
||||
let authenticationResponse;
|
||||
try {
|
||||
const authenticationCallResponse = await http.post(`${contextPath}/login/webauthn`, headers, body);
|
||||
if (!authenticationCallResponse.ok) {
|
||||
throw new Error(`HTTP ${authenticationCallResponse.status}`);
|
||||
}
|
||||
authenticationResponse = await authenticationCallResponse.json();
|
||||
// if (authenticationResponse && authenticationResponse.authenticated) {
|
||||
} catch (err) {
|
||||
throw new Error(`Authentication failed. Could not process the authentication request: ${err.message}`, {
|
||||
cause: err,
|
||||
});
|
||||
}
|
||||
|
||||
if (!(authenticationResponse && authenticationResponse.authenticated && authenticationResponse.redirectUrl)) {
|
||||
throw new Error(
|
||||
`Authentication failed. Expected {"authenticated": true, "redirectUrl": "..."}, server responded with: ${JSON.stringify(authenticationResponse)}`,
|
||||
);
|
||||
}
|
||||
|
||||
return authenticationResponse.redirectUrl;
|
||||
}
|
||||
|
||||
async function register(headers, contextPath, label) {
|
||||
if (!label) {
|
||||
throw new Error("Error: Passkey Label is required");
|
||||
}
|
||||
|
||||
let options;
|
||||
try {
|
||||
const optionsResponse = await http.post(`${contextPath}/webauthn/register/options`, headers);
|
||||
if (!optionsResponse.ok) {
|
||||
throw new Error(`Server responded with HTTP ${optionsResponse.status}`);
|
||||
}
|
||||
options = await optionsResponse.json();
|
||||
} catch (e) {
|
||||
throw new Error(`Registration failed. Could not fetch registration options: ${e.message}`, { cause: e });
|
||||
}
|
||||
|
||||
// FIXME: Use https://www.w3.org/TR/webauthn-3/#sctn-parseCreationOptionsFromJSON
|
||||
const decodedExcludeCredentials = !options.excludeCredentials
|
||||
? []
|
||||
: options.excludeCredentials.map((cred) => ({
|
||||
...cred,
|
||||
id: base64url.decode(cred.id),
|
||||
}));
|
||||
|
||||
const decodedOptions = {
|
||||
...options,
|
||||
user: {
|
||||
...options.user,
|
||||
id: base64url.decode(options.user.id),
|
||||
},
|
||||
challenge: base64url.decode(options.challenge),
|
||||
excludeCredentials: decodedExcludeCredentials,
|
||||
};
|
||||
|
||||
let credentialsContainer;
|
||||
try {
|
||||
credentialsContainer = await navigator.credentials.create({
|
||||
publicKey: decodedOptions,
|
||||
signal: abortController.newSignal(),
|
||||
});
|
||||
} catch (e) {
|
||||
throw new Error(`Registration failed. Call to navigator.credentials.create failed: ${e.message}`, { cause: e });
|
||||
}
|
||||
|
||||
// FIXME: Let response be credential.response. If response is not an instance of AuthenticatorAttestationResponse, abort the ceremony with a user-visible error. https://www.w3.org/TR/webauthn-3/#sctn-registering-a-new-credential
|
||||
const { response } = credentialsContainer;
|
||||
const credential = {
|
||||
id: credentialsContainer.id,
|
||||
rawId: base64url.encode(credentialsContainer.rawId),
|
||||
response: {
|
||||
attestationObject: base64url.encode(response.attestationObject),
|
||||
clientDataJSON: base64url.encode(response.clientDataJSON),
|
||||
transports: response.getTransports ? response.getTransports() : [],
|
||||
},
|
||||
type: credentialsContainer.type,
|
||||
clientExtensionResults: credentialsContainer.getClientExtensionResults(),
|
||||
authenticatorAttachment: credentialsContainer.authenticatorAttachment,
|
||||
};
|
||||
|
||||
const registrationRequest = {
|
||||
publicKey: {
|
||||
credential: credential,
|
||||
label: label,
|
||||
},
|
||||
};
|
||||
|
||||
let verificationJSON;
|
||||
try {
|
||||
const verificationResp = await http.post(`${contextPath}/webauthn/register`, headers, registrationRequest);
|
||||
if (!verificationResp.ok) {
|
||||
throw new Error(`HTTP ${verificationResp.status}`);
|
||||
}
|
||||
verificationJSON = await verificationResp.json();
|
||||
} catch (e) {
|
||||
throw new Error(`Registration failed. Could not process the registration request: ${e.message}`, { cause: e });
|
||||
}
|
||||
|
||||
if (!(verificationJSON && verificationJSON.success)) {
|
||||
throw new Error(`Registration failed. Server responded with: ${JSON.stringify(verificationJSON)}`);
|
||||
}
|
||||
}
|
||||
|
||||
export default {
|
||||
authenticate,
|
||||
register,
|
||||
isConditionalMediationAvailable,
|
||||
};
|
||||
47
javascript/lib/webauthn-login.js
Normal file
47
javascript/lib/webauthn-login.js
Normal file
@@ -0,0 +1,47 @@
|
||||
/*
|
||||
* 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 webauthn from "./webauthn-core.js";
|
||||
|
||||
async function authenticateOrError(headers, contextPath, useConditionalMediation) {
|
||||
try {
|
||||
const redirectUrl = await webauthn.authenticate(headers, contextPath, useConditionalMediation);
|
||||
window.location.href = redirectUrl;
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
window.location.href = `${contextPath}/login?error`;
|
||||
}
|
||||
}
|
||||
|
||||
async function conditionalMediation(headers, contextPath) {
|
||||
const available = await webauthn.isConditionalMediationAvailable();
|
||||
if (available) {
|
||||
await authenticateOrError(headers, contextPath, true);
|
||||
}
|
||||
return available;
|
||||
}
|
||||
|
||||
export async function setupLogin(headers, contextPath, signinButton) {
|
||||
signinButton.addEventListener("click", async () => {
|
||||
await authenticateOrError(headers, contextPath, false);
|
||||
});
|
||||
|
||||
// FIXME: conditional mediation triggers browser crashes
|
||||
// See: https://github.com/rwinch/spring-security-webauthn/issues/73
|
||||
// await conditionalMediation(headers, contextPath);
|
||||
}
|
||||
108
javascript/lib/webauthn-registration.js
Normal file
108
javascript/lib/webauthn-registration.js
Normal file
@@ -0,0 +1,108 @@
|
||||
/*
|
||||
* 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 webauthn from "./webauthn-core.js";
|
||||
|
||||
function setVisibility(element, value) {
|
||||
if (!element) {
|
||||
return;
|
||||
}
|
||||
element.style.display = value ? "block" : "none";
|
||||
}
|
||||
|
||||
function setError(ui, msg) {
|
||||
resetPopups(ui);
|
||||
const error = ui.getError();
|
||||
if (!error) {
|
||||
return;
|
||||
}
|
||||
error.textContent = msg;
|
||||
setVisibility(error, true);
|
||||
}
|
||||
|
||||
function setSuccess(ui) {
|
||||
resetPopups(ui);
|
||||
const success = ui.getSuccess();
|
||||
if (!success) {
|
||||
return;
|
||||
}
|
||||
setVisibility(success, true);
|
||||
}
|
||||
|
||||
function resetPopups(ui) {
|
||||
const success = ui.getSuccess();
|
||||
const error = ui.getError();
|
||||
setVisibility(success, false);
|
||||
setVisibility(error, false);
|
||||
}
|
||||
|
||||
async function submitDeleteForm(contextPath, form, headers) {
|
||||
const options = {
|
||||
method: "DELETE",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
...headers,
|
||||
},
|
||||
};
|
||||
await fetch(form.action, options);
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param headers headers added to the credentials creation POST request, typically CSRF
|
||||
* @param contextPath the contextPath from which the app is served
|
||||
* @param ui contains getRegisterButton(), getSuccess(), getError(), getLabelInput(), getDeleteForms()
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
export async function setupRegistration(headers, contextPath, ui) {
|
||||
resetPopups(ui);
|
||||
|
||||
if (!window.PublicKeyCredential) {
|
||||
setError(ui, "WebAuthn is not supported");
|
||||
return;
|
||||
}
|
||||
|
||||
const queryString = new URLSearchParams(window.location.search);
|
||||
if (queryString.has("success")) {
|
||||
setSuccess(ui);
|
||||
}
|
||||
|
||||
ui.getRegisterButton().addEventListener("click", async () => {
|
||||
resetPopups(ui);
|
||||
const label = ui.getLabelInput().value;
|
||||
try {
|
||||
await webauthn.register(headers, contextPath, label);
|
||||
window.location.href = `${contextPath}/webauthn/register?success`;
|
||||
} catch (err) {
|
||||
setError(ui, err.message);
|
||||
console.error(err);
|
||||
}
|
||||
});
|
||||
|
||||
ui.getDeleteForms().forEach((form) =>
|
||||
form.addEventListener("submit", async function (e) {
|
||||
e.preventDefault();
|
||||
try {
|
||||
await submitDeleteForm(contextPath, form, headers);
|
||||
window.location.href = `${contextPath}/webauthn/register?success`;
|
||||
} catch (err) {
|
||||
setError(ui, err.message);
|
||||
}
|
||||
}),
|
||||
);
|
||||
}
|
||||
5465
javascript/package-lock.json
generated
Normal file
5465
javascript/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
51
javascript/package.json
Normal file
51
javascript/package.json
Normal file
@@ -0,0 +1,51 @@
|
||||
{
|
||||
"name": "@springprojects/spring-security-webauthn",
|
||||
"version": "1.0.0-alpha.9",
|
||||
"description": "WebAuthN JS library for Spring Security",
|
||||
"license": "ASL-2.0",
|
||||
"author": "????",
|
||||
"contributors": [
|
||||
"Rob Winch <rwinch@users.noreply.github.com>",
|
||||
"Daniel Garnier-Moiroux <git@garnier.wf>"
|
||||
],
|
||||
"repository": "github:spring-projects/spring-security",
|
||||
"bugs": {
|
||||
"url": "https://github.com/spring-projects/spring-security/issues"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20.0.0"
|
||||
},
|
||||
"scripts": {
|
||||
"test": "mocha",
|
||||
"check": "npm test && npm run lint",
|
||||
"test:watch": "mocha --watch --parallel",
|
||||
"assemble": "esbuild lib/index.js --bundle --outfile=build/dist/spring-security-webauthn.js",
|
||||
"build": "npm run check && npm run assemble",
|
||||
"lint": "eslint",
|
||||
"format": "npm run lint -- --fix"
|
||||
},
|
||||
"main": "lib/index.js",
|
||||
"files": [
|
||||
"lib"
|
||||
],
|
||||
"keywords": [
|
||||
"Spring Security",
|
||||
"WebAuthn",
|
||||
"passkeys"
|
||||
],
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^9.6.0",
|
||||
"@types/sinon": "^17.0.3",
|
||||
"chai": "~4.3",
|
||||
"esbuild": "^0.23.0",
|
||||
"eslint": "^9.6.0",
|
||||
"eslint-config-prettier": "^9.1.0",
|
||||
"eslint-plugin-prettier": "^5.1.3",
|
||||
"globals": "^15.8.0",
|
||||
"mocha": "~10.2",
|
||||
"prettier": "^3.3.2",
|
||||
"prettier-eslint": "~15.0",
|
||||
"sinon": "^18.0.0"
|
||||
},
|
||||
"type": "module"
|
||||
}
|
||||
49
javascript/spring-security-javascript.gradle
Normal file
49
javascript/spring-security-javascript.gradle
Normal file
@@ -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.
|
||||
*/
|
||||
|
||||
plugins {
|
||||
id 'base'
|
||||
id 'com.github.node-gradle.node' version '7.1.0'
|
||||
}
|
||||
|
||||
node {
|
||||
download = true
|
||||
version = '20.17.0'
|
||||
}
|
||||
|
||||
tasks.named('check') {
|
||||
dependsOn 'npm_run_check'
|
||||
}
|
||||
|
||||
tasks.register('dist', Zip) {
|
||||
dependsOn 'npm_run_assemble'
|
||||
from 'build/dist/spring-security.js'
|
||||
into 'org/springframework/security'
|
||||
}
|
||||
|
||||
configurations {
|
||||
javascript {
|
||||
canBeConsumed = true
|
||||
canBeResolved = false
|
||||
}
|
||||
}
|
||||
|
||||
artifacts {
|
||||
javascript(project.layout.buildDirectory.dir('dist')) {
|
||||
builtBy(npm_run_assemble)
|
||||
}
|
||||
}
|
||||
49
javascript/test/abort-controller.test.js
Normal file
49
javascript/test/abort-controller.test.js
Normal file
@@ -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");
|
||||
});
|
||||
});
|
||||
});
|
||||
76
javascript/test/base64.test.js
Normal file
76
javascript/test/base64.test.js
Normal file
@@ -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);
|
||||
});
|
||||
});
|
||||
22
javascript/test/bootstrap.js
vendored
Normal file
22
javascript/test/bootstrap.js
vendored
Normal file
@@ -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;
|
||||
65
javascript/test/http.test.js
Normal file
65
javascript/test/http.test.js
Normal file
@@ -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}`,
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
697
javascript/test/webauthn-core.test.js
Normal file
697
javascript/test/webauthn-core.test.js
Normal file
@@ -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");
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
106
javascript/test/webauthn-login.test.js
Normal file
106
javascript/test/webauthn-login.test.js
Normal file
@@ -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")),
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
279
javascript/test/webauthn-registration.test.js
Normal file
279
javascript/test/webauthn-registration.test.js
Normal file
@@ -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