π A self-hostable personal dashboard built for you. Includes status-checking, widgets, themes, icon packs, a UI editor and tons more!
Vue awesomedashboarddockerhomelabhomepagemitnodejsorganizationproductivitypwaself-hostedstartpagevue
π§ͺ Tests for OIDC token checking (#2217)
Alicia Sykes7a5b20f750a8
diff --git a/tests/unit/api-auth-header.test.js b/tests/unit/api-auth-header.test.jsnew file mode 100644index 00000000..c3e91a27--- /dev/null+++ b/tests/unit/api-auth-header.test.js@@ -0,0 +1,59 @@+import { describe, it, expect, beforeEach } from 'vitest';+import getApiAuthHeader, { getApiAuthState } from '@/utils/auth/getApiAuthHeader';+import { localStorageKeys } from '@/utils/config/defaults';++const part = (value) => Buffer.from(JSON.stringify(value)).toString('base64url');+const jwt = (claims) => `${part({ alg: 'RS256' })}.${part(claims)}.sig`;++describe('getApiAuthHeader', () => {+ beforeEach(() => {+ localStorage.getItem.mockReset();+ });++ it('returns a bearer header for a usable JWT', () => {+ const token = jwt({ exp: Math.floor(Date.now() / 1000) + 60 });+ localStorage.getItem.mockReturnValue(token);++ expect(getApiAuthHeader()).toEqual({ Authorization: `Bearer ${token}` });+ expect(getApiAuthState()).toMatchObject({ ok: true, reason: 'valid' });+ });++ it('classifies expired tokens', () => {+ localStorage.getItem.mockReturnValue(jwt({ exp: Math.floor(Date.now() / 1000) - 60 }));++ expect(getApiAuthHeader()).toBeNull();+ expect(getApiAuthState()).toEqual({ ok: false, reason: 'expired' });+ });++ it('classifies encrypted compact tokens as JWE', () => {+ localStorage.getItem.mockReturnValue('a.b.c.d.e');++ expect(getApiAuthState()).toEqual({ ok: false, reason: 'encrypted-jwe' });+ });++ it('classifies undecodable JWT payloads as malformed', () => {+ localStorage.getItem.mockReturnValue('a.not-json.c');++ expect(getApiAuthState()).toEqual({ ok: false, reason: 'malformed' });+ });++ it('classifies a null JSON payload as malformed without throwing', () => {+ localStorage.getItem.mockReturnValue(jwt(null));++ expect(() => getApiAuthState()).not.toThrow();+ expect(getApiAuthState()).toEqual({ ok: false, reason: 'malformed' });+ });++ it('classifies a missing token and reads the id_token key', () => {+ localStorage.getItem.mockReturnValue(null);++ expect(getApiAuthState()).toEqual({ ok: false, reason: 'missing' });+ expect(localStorage.getItem).toHaveBeenCalledWith(localStorageKeys.ID_TOKEN);+ });++ it('classifies unreadable storage', () => {+ localStorage.getItem.mockImplementation(() => { throw new Error('denied'); });++ expect(getApiAuthState()).toEqual({ ok: false, reason: 'storage' });+ });+});diff --git a/tests/unit/request-auth.test.js b/tests/unit/request-auth.test.jsnew file mode 100644index 00000000..baa9b5ce--- /dev/null+++ b/tests/unit/request-auth.test.js@@ -0,0 +1,144 @@+import {+ describe, it, expect, beforeEach, afterEach, vi,+} from 'vitest';++const part = (value) => Buffer.from(JSON.stringify(value)).toString('base64url');+const jwt = (claims) => `${part({ alg: 'RS256' })}.${part(claims)}.sig`;+const goodToken = () => jwt({ exp: Math.floor(Date.now() / 1000) + 60 });+const expiredToken = () => jwt({ exp: Math.floor(Date.now() / 1000) - 60 });++async function loadRequest({+ oidc = false,+ keycloak = false,+ renew = vi.fn(),+ basic = { headers: { Authorization: 'Basic abc' } },+} = {}) {+ vi.resetModules();+ vi.doMock('@/utils/auth/Auth', () => ({ makeBasicAuthHeaders: vi.fn(() => basic) }));+ vi.doMock('@/utils/auth/OidcAuth', () => ({+ isOidcEnabled: vi.fn(() => oidc),+ getOidcAuth: vi.fn(() => ({ renewForApiRequest: renew })),+ }));+ vi.doMock('@/utils/auth/KeycloakAuth', () => ({+ isKeycloakEnabled: vi.fn(() => keycloak),+ getKeycloakAuth: vi.fn(() => ({ renewForApiRequest: renew })),+ }));+ vi.doMock('@/utils/logging/CoolConsole', () => ({+ statusMsg: vi.fn(),+ statusErrorMsg: vi.fn(),+ }));+ return (await import('@/utils/request')).default;+}++describe('request auth headers', () => {+ beforeEach(() => {+ vi.restoreAllMocks();+ localStorage.getItem.mockReset();+ global.fetch = vi.fn(() => Promise.resolve(new Response('{"ok":true}', { status: 200 })));+ });++ afterEach(() => {+ vi.doUnmock('@/utils/auth/Auth');+ vi.doUnmock('@/utils/auth/OidcAuth');+ vi.doUnmock('@/utils/auth/KeycloakAuth');+ vi.doUnmock('@/utils/logging/CoolConsole');+ });++ it('keeps Basic fallback for non-SSO local requests', async () => {+ localStorage.getItem.mockReturnValue(null);+ const request = await loadRequest();++ await request.get('/status-check');++ expect(fetch).toHaveBeenCalledWith('/status-check', expect.objectContaining({+ headers: { Authorization: 'Basic abc' },+ }));+ });++ it('does not fall back to Basic when OIDC is enabled and bearer is unusable', async () => {+ localStorage.getItem.mockReturnValue(expiredToken());+ const request = await loadRequest({ oidc: true });++ await request.get('/status-check');++ expect(fetch).toHaveBeenCalledWith('/status-check', expect.objectContaining({+ headers: {},+ }));+ });++ it('sends bearer for SSO when a usable token exists', async () => {+ const token = goodToken();+ localStorage.getItem.mockReturnValue(token);+ const request = await loadRequest({ oidc: true });++ await request.get('/status-check');++ expect(fetch).toHaveBeenCalledWith('/status-check', expect.objectContaining({+ headers: { Authorization: `Bearer ${token}` },+ }));+ });++ it('renews once and retries a local SSO request after 401', async () => {+ let token = expiredToken();+ const fresh = goodToken();+ localStorage.getItem.mockImplementation(() => token);+ fetch+ .mockResolvedValueOnce(new Response('Unauthorized', { status: 401 }))+ .mockResolvedValueOnce(new Response('{"ok":true}', { status: 200 }));+ const renew = vi.fn(async () => {+ token = fresh;+ return true;+ });+ const request = await loadRequest({ oidc: true, renew });++ await request.get('/status-check');++ expect(renew).toHaveBeenCalledTimes(1);+ expect(fetch).toHaveBeenNthCalledWith(1, '/status-check', expect.objectContaining({+ headers: {},+ }));+ expect(fetch).toHaveBeenNthCalledWith(2, '/status-check', expect.objectContaining({+ headers: { Authorization: `Bearer ${fresh}` },+ }));+ });++ it('does not renew again when the retried request still returns 401', async () => {+ localStorage.getItem.mockImplementation(() => expiredToken());+ fetch+ .mockResolvedValueOnce(new Response('Unauthorized', { status: 401 }))+ .mockResolvedValueOnce(new Response('Unauthorized', { status: 401 }));+ const renew = vi.fn(async () => true);+ const request = await loadRequest({ oidc: true, renew });++ await expect(request.get('/status-check')).rejects.toThrow();++ expect(renew).toHaveBeenCalledTimes(1);+ expect(fetch).toHaveBeenCalledTimes(2);+ });++ it('does not retry when renewal fails', async () => {+ localStorage.getItem.mockImplementation(() => expiredToken());+ fetch.mockResolvedValueOnce(new Response('Unauthorized', { status: 401 }));+ const renew = vi.fn(async () => false);+ const request = await loadRequest({ oidc: true, renew });++ await expect(request.get('/status-check')).rejects.toThrow();++ expect(renew).toHaveBeenCalledTimes(1);+ expect(fetch).toHaveBeenCalledTimes(1);+ });++ it('never attaches a bearer or renews for external requests', async () => {+ localStorage.getItem.mockReturnValue(goodToken());+ const renew = vi.fn();+ fetch.mockResolvedValueOnce(new Response('Unauthorized', { status: 401 }));+ const request = await loadRequest({ oidc: true, renew });++ await expect(request.get('https://api.example.com/data')).rejects.toThrow();++ expect(renew).not.toHaveBeenCalled();+ expect(fetch).toHaveBeenCalledWith('https://api.example.com/data', expect.objectContaining({+ headers: {},+ }));+ });+});