From 64fa5fc2366a6b6c3a4c45d31a29d82d1a795034 Mon Sep 17 00:00:00 2001 From: Andreas Coroiu Date: Thu, 7 Sep 2023 13:00:19 +0200 Subject: [PATCH] [PM-3660] Address PR feedback (#6157) * [PM-3660] chore: simplify object assignment * [PM-3660] fix: remove unused origin field * [PM-3660] feat: add Fido2Key tests * [PM-3660] chore: convert popOut to async func * [PM-3660] chore: refactor if-statements * [PM-3660] chore: simplify closePopOut * [PM-3660] fix: remove confusing comment * [PM-3660] chore: move guid utils away from platform utils * [PM-3660] chore: use null instead of undefined * [PM-3660] chore: use `switch` instead of `if` --- .../src/platform/browser/browser-api.ts | 4 + .../src/popup/services/popup-utils.service.ts | 109 +++++++------ libs/common/src/platform/misc/utils.ts | 98 ------------ libs/common/src/vault/api/fido2-key.api.ts | 2 - .../src/vault/models/data/fido2-key.data.ts | 2 - .../src/vault/models/domain/fido2-key.spec.ts | 147 ++++++++++++++++++ .../src/vault/models/domain/fido2-key.ts | 8 - .../src/vault/models/domain/login.spec.ts | 2 - .../src/vault/models/view/fido2-key.view.ts | 2 - .../src/vault/models/view/login.view.ts | 2 +- .../fido2/fido2-authenticator.service.spec.ts | 13 +- .../fido2/fido2-authenticator.service.ts | 13 +- .../fido2/fido2-client.service.spec.ts | 7 +- .../src/vault/services/fido2/guid-utils.ts | 95 +++++++++++ 14 files changed, 318 insertions(+), 186 deletions(-) create mode 100644 libs/common/src/vault/models/domain/fido2-key.spec.ts create mode 100644 libs/common/src/vault/services/fido2/guid-utils.ts diff --git a/apps/browser/src/platform/browser/browser-api.ts b/apps/browser/src/platform/browser/browser-api.ts index bdd49c9539d..e6263d4f27e 100644 --- a/apps/browser/src/platform/browser/browser-api.ts +++ b/apps/browser/src/platform/browser/browser-api.ts @@ -37,6 +37,10 @@ export class BrowserApi { ); } + static async removeWindow(windowId: number) { + await chrome.tabs.remove(windowId); + } + static async getTabFromCurrentWindowId(): Promise | null { return await BrowserApi.tabsQueryFirst({ active: true, diff --git a/apps/browser/src/popup/services/popup-utils.service.ts b/apps/browser/src/popup/services/popup-utils.service.ts index b7ea330cdfc..9d424586b20 100644 --- a/apps/browser/src/popup/services/popup-utils.service.ts +++ b/apps/browser/src/popup/services/popup-utils.service.ts @@ -55,69 +55,66 @@ export class PopupUtilsService { } } - popOut(win: Window, href: string = null, options: { center?: boolean } = {}): Promise { - return new Promise((resolve, reject) => { - if (href === null) { - href = win.location.href; - } + async popOut( + win: Window, + href: string = null, + options: { center?: boolean } = {} + ): Promise { + if (href === null) { + href = win.location.href; + } - if (typeof chrome !== "undefined" && chrome.windows && chrome.windows.create) { - if (href.indexOf("?uilocation=") > -1) { - href = href - .replace("uilocation=popup", "uilocation=popout") - .replace("uilocation=tab", "uilocation=popout") - .replace("uilocation=sidebar", "uilocation=popout"); - } else { - const hrefParts = href.split("#"); - href = - hrefParts[0] + "?uilocation=popout" + (hrefParts.length > 0 ? "#" + hrefParts[1] : ""); - } - - const bodyRect = document.querySelector("body").getBoundingClientRect(); - const width = Math.round(bodyRect.width ? bodyRect.width + 60 : 375); - const height = Math.round(bodyRect.height || 600); - const top = options.center ? Math.round((screen.height - height) / 2) : undefined; - const left = options.center ? Math.round((screen.width - width) / 2) : undefined; - chrome.windows.create( - { - url: href, - type: "popup", - width, - height, - top, - left, - }, - (window) => resolve({ type: "window", window }) - ); - - if (win && this.inPopup(win)) { - BrowserApi.closePopup(win); - } - } else if (typeof chrome !== "undefined" && chrome.tabs && chrome.tabs.create) { + if (chrome?.windows?.create != null) { + if (href.indexOf("?uilocation=") > -1) { href = href - .replace("uilocation=popup", "uilocation=tab") - .replace("uilocation=popout", "uilocation=tab") - .replace("uilocation=sidebar", "uilocation=tab"); - chrome.tabs.create( - { - url: href, - }, - (tab) => resolve({ type: "tab", tab }) - ); + .replace("uilocation=popup", "uilocation=popout") + .replace("uilocation=tab", "uilocation=popout") + .replace("uilocation=sidebar", "uilocation=popout"); } else { - reject(new Error("Cannot open tab or window")); + const hrefParts = href.split("#"); + href = + hrefParts[0] + "?uilocation=popout" + (hrefParts.length > 0 ? "#" + hrefParts[1] : ""); } - }); + + const bodyRect = document.querySelector("body").getBoundingClientRect(); + const width = Math.round(bodyRect.width ? bodyRect.width + 60 : 375); + const height = Math.round(bodyRect.height || 600); + const top = options.center ? Math.round((screen.height - height) / 2) : undefined; + const left = options.center ? Math.round((screen.width - width) / 2) : undefined; + const window = await BrowserApi.createWindow({ + url: href, + type: "popup", + width, + height, + top, + left, + }); + + if (win && this.inPopup(win)) { + BrowserApi.closePopup(win); + } + + return { type: "window", window }; + } else if (chrome?.tabs?.create != null) { + href = href + .replace("uilocation=popup", "uilocation=tab") + .replace("uilocation=popout", "uilocation=tab") + .replace("uilocation=sidebar", "uilocation=tab"); + + const tab = await BrowserApi.createNewTab(href); + return { type: "tab", tab }; + } else { + throw new Error("Cannot open tab or window"); + } } closePopOut(popout: Popout): Promise { - return new Promise((resolve) => { - if (popout.type === "window") { - chrome.windows.remove(popout.window.id, resolve); - } else { - chrome.tabs.remove(popout.tab.id, resolve); - } - }); + switch (popout.type) { + case "window": + return BrowserApi.removeWindow(popout.window.id); + case "tab": + return BrowserApi.removeTab(popout.tab.id); + } } /** diff --git a/libs/common/src/platform/misc/utils.ts b/libs/common/src/platform/misc/utils.ts index 2fb6f4f5a34..cd1b5fe33aa 100644 --- a/libs/common/src/platform/misc/utils.ts +++ b/libs/common/src/platform/misc/utils.ts @@ -37,9 +37,6 @@ export class Utils { ["google.com", new Set(["script.google.com"])], ]); - /** Used by guidToStandardFormat */ - private static byteToHex: string[] = []; - static init() { if (Utils.inited) { return; @@ -63,10 +60,6 @@ export class Utils { // If it's not browser or node then it must be a service worker Utils.global = self; } - - for (let i = 0; i < 256; ++i) { - Utils.byteToHex.push((i + 0x100).toString(16).substring(1)); - } } static fromB64ToArray(str: string): Uint8Array { @@ -584,97 +577,6 @@ export class Utils { return null; } - - /* - License for: guidToRawFormat, guidToStandardFormat - Source: https://github.com/uuidjs/uuid/ - The MIT License (MIT) - Copyright (c) 2010-2020 Robert Kieffer and other contributors - Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.*/ - - /** Convert standard format (XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX) UUID to raw 16 byte array. */ - static guidToRawFormat(guid: string) { - if (!Utils.isGuid(guid)) { - throw TypeError("GUID parameter is invalid"); - } - - let v; - const arr = new Uint8Array(16); - - // Parse ########-....-....-....-............ - arr[0] = (v = parseInt(guid.slice(0, 8), 16)) >>> 24; - arr[1] = (v >>> 16) & 0xff; - arr[2] = (v >>> 8) & 0xff; - arr[3] = v & 0xff; - - // Parse ........-####-....-....-............ - arr[4] = (v = parseInt(guid.slice(9, 13), 16)) >>> 8; - arr[5] = v & 0xff; - - // Parse ........-....-####-....-............ - arr[6] = (v = parseInt(guid.slice(14, 18), 16)) >>> 8; - arr[7] = v & 0xff; - - // Parse ........-....-....-####-............ - arr[8] = (v = parseInt(guid.slice(19, 23), 16)) >>> 8; - arr[9] = v & 0xff; - - // Parse ........-....-....-....-############ - // (Use "/" to avoid 32-bit truncation when bit-shifting high-order bytes) - arr[10] = ((v = parseInt(guid.slice(24, 36), 16)) / 0x10000000000) & 0xff; - arr[11] = (v / 0x100000000) & 0xff; - arr[12] = (v >>> 24) & 0xff; - arr[13] = (v >>> 16) & 0xff; - arr[14] = (v >>> 8) & 0xff; - arr[15] = v & 0xff; - - return arr; - } - - /** Convert raw 16 byte array to standard format (XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX) UUID. */ - static guidToStandardFormat(bufferSource: BufferSource) { - const arr = - bufferSource instanceof ArrayBuffer - ? new Uint8Array(bufferSource) - : new Uint8Array(bufferSource.buffer); - // Note: Be careful editing this code! It's been tuned for performance - // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434 - const guid = ( - Utils.byteToHex[arr[0]] + - Utils.byteToHex[arr[1]] + - Utils.byteToHex[arr[2]] + - Utils.byteToHex[arr[3]] + - "-" + - Utils.byteToHex[arr[4]] + - Utils.byteToHex[arr[5]] + - "-" + - Utils.byteToHex[arr[6]] + - Utils.byteToHex[arr[7]] + - "-" + - Utils.byteToHex[arr[8]] + - Utils.byteToHex[arr[9]] + - "-" + - Utils.byteToHex[arr[10]] + - Utils.byteToHex[arr[11]] + - Utils.byteToHex[arr[12]] + - Utils.byteToHex[arr[13]] + - Utils.byteToHex[arr[14]] + - Utils.byteToHex[arr[15]] - ).toLowerCase(); - - // Consistency check for valid UUID. If this throws, it's likely due to one - // of the following: - // - One or more input array values don't map to a hex octet (leading to - // "undefined" in the uuid) - // - Invalid input values for the RFC `version` or `variant` fields - if (!Utils.isGuid(guid)) { - throw TypeError("Converted GUID is invalid"); - } - - return guid; - } } Utils.init(); diff --git a/libs/common/src/vault/api/fido2-key.api.ts b/libs/common/src/vault/api/fido2-key.api.ts index c4c7c0f5d80..fe4c6ae6b33 100644 --- a/libs/common/src/vault/api/fido2-key.api.ts +++ b/libs/common/src/vault/api/fido2-key.api.ts @@ -9,8 +9,6 @@ export class Fido2KeyApi extends BaseResponse { rpId: string; userHandle: string; counter: string; - - // Extras rpName: string; userDisplayName: string; diff --git a/libs/common/src/vault/models/data/fido2-key.data.ts b/libs/common/src/vault/models/data/fido2-key.data.ts index 55a89eb0853..fa56635404e 100644 --- a/libs/common/src/vault/models/data/fido2-key.data.ts +++ b/libs/common/src/vault/models/data/fido2-key.data.ts @@ -9,8 +9,6 @@ export class Fido2KeyData { rpId: string; userHandle: string; counter: string; - - // Extras rpName: string; userDisplayName: string; diff --git a/libs/common/src/vault/models/domain/fido2-key.spec.ts b/libs/common/src/vault/models/domain/fido2-key.spec.ts new file mode 100644 index 00000000000..483f1d9f04c --- /dev/null +++ b/libs/common/src/vault/models/domain/fido2-key.spec.ts @@ -0,0 +1,147 @@ +import { mockEnc } from "../../../../spec"; +import { EncryptionType } from "../../../enums"; +import { EncString } from "../../../platform/models/domain/enc-string"; +import { Fido2KeyData } from "../data/fido2-key.data"; + +import { Fido2Key } from "./fido2-key"; + +describe("Fido2Key", () => { + describe("constructor", () => { + it("returns all fields null when given empty data parameter", () => { + const data = new Fido2KeyData(); + const fido2Key = new Fido2Key(data); + + expect(fido2Key).toEqual({ + nonDiscoverableId: null, + keyType: null, + keyAlgorithm: null, + keyCurve: null, + keyValue: null, + rpId: null, + userHandle: null, + rpName: null, + userDisplayName: null, + counter: null, + }); + }); + + it("returns all fields as EncStrings when given full Fido2KeyData", () => { + const data: Fido2KeyData = { + nonDiscoverableId: "nonDiscoverableId", + keyType: "public-key", + keyAlgorithm: "ECDSA", + keyCurve: "P-256", + keyValue: "keyValue", + rpId: "rpId", + userHandle: "userHandle", + counter: "counter", + rpName: "rpName", + userDisplayName: "userDisplayName", + }; + const fido2Key = new Fido2Key(data); + + expect(fido2Key).toEqual({ + nonDiscoverableId: { encryptedString: "nonDiscoverableId", encryptionType: 0 }, + keyType: { encryptedString: "public-key", encryptionType: 0 }, + keyAlgorithm: { encryptedString: "ECDSA", encryptionType: 0 }, + keyCurve: { encryptedString: "P-256", encryptionType: 0 }, + keyValue: { encryptedString: "keyValue", encryptionType: 0 }, + rpId: { encryptedString: "rpId", encryptionType: 0 }, + userHandle: { encryptedString: "userHandle", encryptionType: 0 }, + counter: { encryptedString: "counter", encryptionType: 0 }, + rpName: { encryptedString: "rpName", encryptionType: 0 }, + userDisplayName: { encryptedString: "userDisplayName", encryptionType: 0 }, + }); + }); + + it("should not populate fields when data parameter is not given", () => { + const fido2Key = new Fido2Key(); + + expect(fido2Key).toEqual({ + nonDiscoverableId: null, + }); + }); + }); + + describe("decrypt", () => { + it("decrypts and populates all fields when populated with EncStrings", async () => { + const fido2Key = new Fido2Key(); + fido2Key.nonDiscoverableId = mockEnc("nonDiscoverableId"); + fido2Key.keyType = mockEnc("keyType"); + fido2Key.keyAlgorithm = mockEnc("keyAlgorithm"); + fido2Key.keyCurve = mockEnc("keyCurve"); + fido2Key.keyValue = mockEnc("keyValue"); + fido2Key.rpId = mockEnc("rpId"); + fido2Key.userHandle = mockEnc("userHandle"); + fido2Key.counter = mockEnc("2"); + fido2Key.rpName = mockEnc("rpName"); + fido2Key.userDisplayName = mockEnc("userDisplayName"); + + const fido2KeyView = await fido2Key.decrypt(null); + + expect(fido2KeyView).toEqual({ + nonDiscoverableId: "nonDiscoverableId", + keyType: "keyType", + keyAlgorithm: "keyAlgorithm", + keyCurve: "keyCurve", + keyValue: "keyValue", + rpId: "rpId", + userHandle: "userHandle", + rpName: "rpName", + userDisplayName: "userDisplayName", + counter: 2, + }); + }); + }); + + describe("toFido2KeyData", () => { + it("encodes to data object when converted from Fido2KeyData and back", () => { + const data: Fido2KeyData = { + nonDiscoverableId: "nonDiscoverableId", + keyType: "public-key", + keyAlgorithm: "ECDSA", + keyCurve: "P-256", + keyValue: "keyValue", + rpId: "rpId", + userHandle: "userHandle", + counter: "counter", + rpName: "rpName", + userDisplayName: "userDisplayName", + }; + + const fido2Key = new Fido2Key(data); + const result = fido2Key.toFido2KeyData(); + + expect(result).toEqual(data); + }); + }); + + describe("fromJSON", () => { + it("recreates equivalent object when converted to JSON and back", () => { + const fido2Key = new Fido2Key(); + fido2Key.nonDiscoverableId = createEncryptedEncString("nonDiscoverableId"); + fido2Key.keyType = createEncryptedEncString("keyType"); + fido2Key.keyAlgorithm = createEncryptedEncString("keyAlgorithm"); + fido2Key.keyCurve = createEncryptedEncString("keyCurve"); + fido2Key.keyValue = createEncryptedEncString("keyValue"); + fido2Key.rpId = createEncryptedEncString("rpId"); + fido2Key.userHandle = createEncryptedEncString("userHandle"); + fido2Key.counter = createEncryptedEncString("2"); + fido2Key.rpName = createEncryptedEncString("rpName"); + fido2Key.userDisplayName = createEncryptedEncString("userDisplayName"); + + const json = JSON.stringify(fido2Key); + const result = Fido2Key.fromJSON(JSON.parse(json)); + + expect(result).toEqual(fido2Key); + }); + + it("returns null if input is null", () => { + expect(Fido2Key.fromJSON(null)).toBeNull(); + }); + }); +}); + +function createEncryptedEncString(s: string): EncString { + return new EncString(`${EncryptionType.AesCbc256_HmacSha256_B64}.${s}`); +} diff --git a/libs/common/src/vault/models/domain/fido2-key.ts b/libs/common/src/vault/models/domain/fido2-key.ts index 17ed24b26ff..dbec3785d24 100644 --- a/libs/common/src/vault/models/domain/fido2-key.ts +++ b/libs/common/src/vault/models/domain/fido2-key.ts @@ -15,11 +15,8 @@ export class Fido2Key extends Domain { rpId: EncString; userHandle: EncString; counter: EncString; - - // Extras rpName: EncString; userDisplayName: EncString; - origin: EncString; constructor(obj?: Fido2KeyData) { super(); @@ -41,7 +38,6 @@ export class Fido2Key extends Domain { counter: null, rpName: null, userDisplayName: null, - origin: null, }, [] ); @@ -60,7 +56,6 @@ export class Fido2Key extends Domain { userHandle: null, rpName: null, userDisplayName: null, - origin: null, }, orgId, encKey @@ -93,7 +88,6 @@ export class Fido2Key extends Domain { counter: null, rpName: null, userDisplayName: null, - origin: null, }); return i; } @@ -113,7 +107,6 @@ export class Fido2Key extends Domain { const counter = EncString.fromJSON(obj.counter); const rpName = EncString.fromJSON(obj.rpName); const userDisplayName = EncString.fromJSON(obj.userDisplayName); - const origin = EncString.fromJSON(obj.origin); return Object.assign(new Fido2Key(), obj, { nonDiscoverableId, @@ -126,7 +119,6 @@ export class Fido2Key extends Domain { counter, rpName, userDisplayName, - origin, }); } } diff --git a/libs/common/src/vault/models/domain/login.spec.ts b/libs/common/src/vault/models/domain/login.spec.ts index b02b0fc94f5..d4243441558 100644 --- a/libs/common/src/vault/models/domain/login.spec.ts +++ b/libs/common/src/vault/models/domain/login.spec.ts @@ -123,7 +123,6 @@ describe("Login DTO", () => { counter: "counter" as EncryptedString, rpName: "rpName" as EncryptedString, userDisplayName: "userDisplayName" as EncryptedString, - origin: "origin" as EncryptedString, }, }); @@ -144,7 +143,6 @@ describe("Login DTO", () => { counter: "counter_fromJSON", rpName: "rpName_fromJSON", userDisplayName: "userDisplayName_fromJSON", - origin: "origin_fromJSON", }, }); expect(actual).toBeInstanceOf(Login); diff --git a/libs/common/src/vault/models/view/fido2-key.view.ts b/libs/common/src/vault/models/view/fido2-key.view.ts index 4cf423b8e08..f3156d79e40 100644 --- a/libs/common/src/vault/models/view/fido2-key.view.ts +++ b/libs/common/src/vault/models/view/fido2-key.view.ts @@ -11,8 +11,6 @@ export class Fido2KeyView extends ItemView { rpId: string; userHandle: string; counter: number; - - // Extras rpName: string; userDisplayName: string; diff --git a/libs/common/src/vault/models/view/login.view.ts b/libs/common/src/vault/models/view/login.view.ts index 16fee107214..86284151a3f 100644 --- a/libs/common/src/vault/models/view/login.view.ts +++ b/libs/common/src/vault/models/view/login.view.ts @@ -84,7 +84,7 @@ export class LoginView extends ItemView { const fido2Key = obj.fido2Key == null ? null : Fido2KeyView.fromJSON(obj.fido2Key); return Object.assign(new LoginView(), obj, { - passwordRevisionDate: passwordRevisionDate, + passwordRevisionDate, uris, fido2Key, }); diff --git a/libs/common/src/vault/services/fido2/fido2-authenticator.service.spec.ts b/libs/common/src/vault/services/fido2/fido2-authenticator.service.spec.ts index a606006b951..4b04e5815bb 100644 --- a/libs/common/src/vault/services/fido2/fido2-authenticator.service.spec.ts +++ b/libs/common/src/vault/services/fido2/fido2-authenticator.service.spec.ts @@ -23,6 +23,7 @@ import { LoginView } from "../../models/view/login.view"; import { CBOR } from "./cbor"; import { AAGUID, Fido2AuthenticatorService } from "./fido2-authenticator.service"; import { Fido2Utils } from "./fido2-utils"; +import { guidToRawFormat } from "./guid-utils"; const RpId = "bitwarden.com"; @@ -112,7 +113,7 @@ describe("FidoAuthenticatorService", () => { params = await createParams({ excludeCredentialDescriptorList: [ { - id: Utils.guidToRawFormat(excludedCipher.login.fido2Key.nonDiscoverableId), + id: guidToRawFormat(excludedCipher.login.fido2Key.nonDiscoverableId), type: "public-key", }, ], @@ -186,7 +187,7 @@ describe("FidoAuthenticatorService", () => { excludedCipherView = createCipherView(); params = await createParams({ excludeCredentialDescriptorList: [ - { id: Utils.guidToRawFormat(excludedCipherView.id), type: "public-key" }, + { id: guidToRawFormat(excludedCipherView.id), type: "public-key" }, ], }); cipherService.get.mockImplementation(async (id) => @@ -633,7 +634,7 @@ describe("FidoAuthenticatorService", () => { credentialId = Utils.newGuid(); params = await createParams({ allowCredentialDescriptorList: [ - { id: Utils.guidToRawFormat(credentialId), type: "public-key" }, + { id: guidToRawFormat(credentialId), type: "public-key" }, ], rpId: RpId, }); @@ -709,7 +710,7 @@ describe("FidoAuthenticatorService", () => { ]; params = await createParams({ allowCredentialDescriptorList: credentialIds.map((credentialId) => ({ - id: Utils.guidToRawFormat(credentialId), + id: guidToRawFormat(credentialId), type: "public-key", })), rpId: RpId, @@ -789,7 +790,7 @@ describe("FidoAuthenticatorService", () => { selectedCredentialId = credentialIds[0]; params = await createParams({ allowCredentialDescriptorList: credentialIds.map((credentialId) => ({ - id: Utils.guidToRawFormat(credentialId), + id: guidToRawFormat(credentialId), type: "public-key", })), rpId: RpId, @@ -842,7 +843,7 @@ describe("FidoAuthenticatorService", () => { const flags = encAuthData.slice(32, 33); const counter = encAuthData.slice(33, 37); - expect(result.selectedCredential.id).toEqual(Utils.guidToRawFormat(selectedCredentialId)); + expect(result.selectedCredential.id).toEqual(guidToRawFormat(selectedCredentialId)); expect(result.selectedCredential.userHandle).toEqual( Fido2Utils.stringToBuffer(fido2Keys[0].userHandle) ); diff --git a/libs/common/src/vault/services/fido2/fido2-authenticator.service.ts b/libs/common/src/vault/services/fido2/fido2-authenticator.service.ts index 525826b7818..25fd9e29609 100644 --- a/libs/common/src/vault/services/fido2/fido2-authenticator.service.ts +++ b/libs/common/src/vault/services/fido2/fido2-authenticator.service.ts @@ -20,6 +20,7 @@ import { Fido2KeyView } from "../../models/view/fido2-key.view"; import { CBOR } from "./cbor"; import { joseToDer } from "./ecdsa-utils"; import { Fido2Utils } from "./fido2-utils"; +import { guidToRawFormat, guidToStandardFormat } from "./guid-utils"; // AAGUID: 6e8248d5-b479-40db-a3d8-11116f7e8349 export const AAGUID = new Uint8Array([ @@ -184,7 +185,7 @@ export class Fido2AuthenticatorService implements Fido2AuthenticatorServiceAbstr const authData = await generateAuthData({ rpId: params.rpEntity.id, - credentialId: Utils.guidToRawFormat(credentialId), + credentialId: guidToRawFormat(credentialId), counter: fido2Key.counter, userPresence: true, userVerification: userVerified, @@ -199,7 +200,7 @@ export class Fido2AuthenticatorService implements Fido2AuthenticatorServiceAbstr ); return { - credentialId: Utils.guidToRawFormat(credentialId), + credentialId: guidToRawFormat(credentialId), attestationObject, authData, publicKeyAlgorithm: -7, @@ -294,7 +295,7 @@ export class Fido2AuthenticatorService implements Fido2AuthenticatorServiceAbstr const authenticatorData = await generateAuthData({ rpId: selectedFido2Key.rpId, - credentialId: Utils.guidToRawFormat(selectedCredentialId), + credentialId: guidToRawFormat(selectedCredentialId), counter: selectedFido2Key.counter, userPresence: true, userVerification: userVerified, @@ -309,7 +310,7 @@ export class Fido2AuthenticatorService implements Fido2AuthenticatorServiceAbstr return { authenticatorData, selectedCredential: { - id: Utils.guidToRawFormat(selectedCredentialId), + id: guidToRawFormat(selectedCredentialId), userHandle: Fido2Utils.stringToBuffer(selectedFido2Key.userHandle), }, signature, @@ -333,7 +334,7 @@ export class Fido2AuthenticatorService implements Fido2AuthenticatorServiceAbstr for (const credential of credentials) { try { - ids.push(Utils.guidToStandardFormat(credential.id)); + ids.push(guidToStandardFormat(credential.id)); // eslint-disable-next-line no-empty } catch {} } @@ -364,7 +365,7 @@ export class Fido2AuthenticatorService implements Fido2AuthenticatorServiceAbstr for (const credential of credentials) { try { - ids.push(Utils.guidToStandardFormat(credential.id)); + ids.push(guidToStandardFormat(credential.id)); // eslint-disable-next-line no-empty } catch {} } diff --git a/libs/common/src/vault/services/fido2/fido2-client.service.spec.ts b/libs/common/src/vault/services/fido2/fido2-client.service.spec.ts index a22091625f2..8f8141df9c7 100644 --- a/libs/common/src/vault/services/fido2/fido2-client.service.spec.ts +++ b/libs/common/src/vault/services/fido2/fido2-client.service.spec.ts @@ -17,6 +17,7 @@ import { import { Fido2AuthenticatorService } from "./fido2-authenticator.service"; import { Fido2ClientService } from "./fido2-client.service"; import { Fido2Utils } from "./fido2-utils"; +import { guidToRawFormat } from "./guid-utils"; const RpId = "bitwarden.com"; @@ -235,7 +236,7 @@ describe("FidoAuthenticatorService", () => { function createAuthenticatorMakeResult(): Fido2AuthenticatorMakeCredentialResult { return { - credentialId: Utils.guidToRawFormat(Utils.newGuid()), + credentialId: guidToRawFormat(Utils.newGuid()), attestationObject: randomBytes(128), authData: randomBytes(64), publicKeyAlgorithm: -7, @@ -346,8 +347,8 @@ describe("FidoAuthenticatorService", () => { describe("assert non-discoverable credential", () => { it("should call authenticator.assertCredential", async () => { const allowedCredentialIds = [ - Fido2Utils.bufferToString(Utils.guidToRawFormat(Utils.newGuid())), - Fido2Utils.bufferToString(Utils.guidToRawFormat(Utils.newGuid())), + Fido2Utils.bufferToString(guidToRawFormat(Utils.newGuid())), + Fido2Utils.bufferToString(guidToRawFormat(Utils.newGuid())), Fido2Utils.bufferToString(Utils.fromByteStringToArray("not-a-guid")), ]; const params = createParams({ diff --git a/libs/common/src/vault/services/fido2/guid-utils.ts b/libs/common/src/vault/services/fido2/guid-utils.ts new file mode 100644 index 00000000000..66e6cbb1d7c --- /dev/null +++ b/libs/common/src/vault/services/fido2/guid-utils.ts @@ -0,0 +1,95 @@ +/* + License for: guidToRawFormat, guidToStandardFormat + Source: https://github.com/uuidjs/uuid/ + The MIT License (MIT) + Copyright (c) 2010-2020 Robert Kieffer and other contributors + Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.*/ + +import { Utils } from "../../../platform/misc/utils"; + +/** Private array used for optimization */ +const byteToHex = Array.from({ length: 256 }, (_, i) => (i + 0x100).toString(16).substring(1)); + +/** Convert standard format (XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX) UUID to raw 16 byte array. */ +export function guidToRawFormat(guid: string) { + if (!Utils.isGuid(guid)) { + throw TypeError("GUID parameter is invalid"); + } + + let v; + const arr = new Uint8Array(16); + + // Parse ########-....-....-....-............ + arr[0] = (v = parseInt(guid.slice(0, 8), 16)) >>> 24; + arr[1] = (v >>> 16) & 0xff; + arr[2] = (v >>> 8) & 0xff; + arr[3] = v & 0xff; + + // Parse ........-####-....-....-............ + arr[4] = (v = parseInt(guid.slice(9, 13), 16)) >>> 8; + arr[5] = v & 0xff; + + // Parse ........-....-####-....-............ + arr[6] = (v = parseInt(guid.slice(14, 18), 16)) >>> 8; + arr[7] = v & 0xff; + + // Parse ........-....-....-####-............ + arr[8] = (v = parseInt(guid.slice(19, 23), 16)) >>> 8; + arr[9] = v & 0xff; + + // Parse ........-....-....-....-############ + // (Use "/" to avoid 32-bit truncation when bit-shifting high-order bytes) + arr[10] = ((v = parseInt(guid.slice(24, 36), 16)) / 0x10000000000) & 0xff; + arr[11] = (v / 0x100000000) & 0xff; + arr[12] = (v >>> 24) & 0xff; + arr[13] = (v >>> 16) & 0xff; + arr[14] = (v >>> 8) & 0xff; + arr[15] = v & 0xff; + + return arr; +} + +/** Convert raw 16 byte array to standard format (XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX) UUID. */ +export function guidToStandardFormat(bufferSource: BufferSource) { + const arr = + bufferSource instanceof ArrayBuffer + ? new Uint8Array(bufferSource) + : new Uint8Array(bufferSource.buffer); + // Note: Be careful editing this code! It's been tuned for performance + // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434 + const guid = ( + byteToHex[arr[0]] + + byteToHex[arr[1]] + + byteToHex[arr[2]] + + byteToHex[arr[3]] + + "-" + + byteToHex[arr[4]] + + byteToHex[arr[5]] + + "-" + + byteToHex[arr[6]] + + byteToHex[arr[7]] + + "-" + + byteToHex[arr[8]] + + byteToHex[arr[9]] + + "-" + + byteToHex[arr[10]] + + byteToHex[arr[11]] + + byteToHex[arr[12]] + + byteToHex[arr[13]] + + byteToHex[arr[14]] + + byteToHex[arr[15]] + ).toLowerCase(); + + // Consistency check for valid UUID. If this throws, it's likely due to one + // of the following: + // - One or more input array values don't map to a hex octet (leading to + // "undefined" in the uuid) + // - Invalid input values for the RFC `version` or `variant` fields + if (!Utils.isGuid(guid)) { + throw TypeError("Converted GUID is invalid"); + } + + return guid; +}