From 9b532e672055191b88014a23f0005adf450bc5f3 Mon Sep 17 00:00:00 2001 From: Robin Date: Thu, 16 Jan 2025 16:54:24 -0500 Subject: [PATCH] Test the JWT service errors --- src/livekit/openIDSFU.test.ts | 69 +++++++++++++++++++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 src/livekit/openIDSFU.test.ts diff --git a/src/livekit/openIDSFU.test.ts b/src/livekit/openIDSFU.test.ts new file mode 100644 index 000000000..0e947c2eb --- /dev/null +++ b/src/livekit/openIDSFU.test.ts @@ -0,0 +1,69 @@ +/* +Copyright 2025 New Vector Ltd. + +SPDX-License-Identifier: AGPL-3.0-only +Please see LICENSE in the repository root for full details. +*/ + +import { expect, type MockInstance, test, vi } from "vitest"; +import { type IOpenIDToken } from "matrix-js-sdk/src/client"; +import { type LivekitFocus } from "matrix-js-sdk/src/matrixrtc"; + +import { getSFUConfigWithOpenID, type OpenIDClientParts } from "./openIDSFU"; +import { + AuthConnectionFailedError, + AuthConnectionRejectedError, +} from "../RichError"; + +async function withFetchSpy( + continuation: (fetchSpy: MockInstance) => Promise, +): Promise { + const fetchSpy = vi.spyOn(globalThis, "fetch"); + try { + await continuation(fetchSpy); + } finally { + fetchSpy.mockRestore(); + } +} + +const mockClient: OpenIDClientParts = { + getOpenIdToken: async () => Promise.resolve({} as IOpenIDToken), + getDeviceId: () => "Device ID", +}; +const mockFocus: LivekitFocus = { + type: "livekit", + livekit_alias: "LiveKit alias", + livekit_service_url: "LiveKit service URL", +}; + +test("getSFUConfigWithOpenID gets the JWT token", async () => { + await withFetchSpy(async (fetch) => { + fetch.mockResolvedValue({ + ok: true, + json: async () => + Promise.resolve({ jwt: "JWT token", url: "LiveKit URL" }), + } as Response); + expect(await getSFUConfigWithOpenID(mockClient, mockFocus)).toEqual({ + jwt: "JWT token", + url: "LiveKit URL", + }); + }); +}); + +test("getSFUConfigWithOpenID throws if connection fails", async () => { + await withFetchSpy(async (fetch) => { + fetch.mockRejectedValue(new Error("Connection failed")); + await expect(async () => + getSFUConfigWithOpenID(mockClient, mockFocus), + ).rejects.toThrowError(expect.any(AuthConnectionFailedError)); + }); +}); + +test("getSFUConfigWithOpenID throws if server returns error", async () => { + await withFetchSpy(async (fetch) => { + fetch.mockResolvedValue({ ok: false, status: 404 } as Response); + await expect(async () => + getSFUConfigWithOpenID(mockClient, mockFocus), + ).rejects.toThrowError(expect.any(AuthConnectionRejectedError)); + }); +});