162 lines
9.0 KiB
JavaScript
162 lines
9.0 KiB
JavaScript
import assert from 'node:assert/strict';
|
|
import { webcrypto } from 'node:crypto';
|
|
import fs from 'node:fs';
|
|
import { createRequire } from 'node:module';
|
|
import test from 'node:test';
|
|
import vm from 'node:vm';
|
|
|
|
const require = createRequire(import.meta.url);
|
|
const ts = require(process.env.KEFU_SSO_TYPESCRIPT || 'typescript');
|
|
|
|
function loadTs(relative, dependencies = {}) {
|
|
dependencies = { '#/locales/t': { t: key => key }, ...dependencies };
|
|
const source = fs.readFileSync(new URL(relative, import.meta.url), 'utf8');
|
|
const result = ts.transpileModule(source, { compilerOptions: { target: ts.ScriptTarget.ES2022,
|
|
module: ts.ModuleKind.CommonJS, esModuleInterop: true }, reportDiagnostics: true });
|
|
assert.deepEqual(result.diagnostics, []);
|
|
const module = { exports: {} };
|
|
vm.runInNewContext(result.outputText, { module, exports: module.exports,
|
|
require(name) { assert.ok(name in dependencies, `Unexpected import ${name}`); return dependencies[name]; },
|
|
URL, URLSearchParams, TextEncoder, Uint8Array, btoa, crypto: webcrypto, console });
|
|
return module.exports;
|
|
}
|
|
|
|
const sso = loadTs('../src/utils/group-sso.ts');
|
|
const config = { enabled: true, client_id: 'kefu', entry: 'http://127.0.0.1:5173',
|
|
authorize_url: 'http://127.0.0.1:5173/sso/authorize',
|
|
redirect_uri: 'http://127.0.0.1:5666/auth/group-login' };
|
|
const origin = 'http://127.0.0.1:5666';
|
|
const now = 1_000_000;
|
|
const code = 'C'.repeat(43);
|
|
|
|
function storage() {
|
|
const values = new Map();
|
|
return { getItem: key => values.get(key) ?? null, setItem: (key, value) => values.set(key, value),
|
|
removeItem: key => values.delete(key), values };
|
|
}
|
|
|
|
async function transaction() {
|
|
const state = storage();
|
|
const target = new URL(await sso.beginGroupLogin(config, origin, state, webcrypto, now));
|
|
const pending = JSON.parse(state.getItem(sso.GROUP_TRANSACTION_KEY));
|
|
return { state, target, pending, href: `${config.redirect_uri}?code=${code}&state=${pending.state}` };
|
|
}
|
|
|
|
test('authorization uses random state, S256 PKCE and a fixed client/callback', async () => {
|
|
const { state, target, pending, href } = await transaction();
|
|
assert.match(pending.state, /^[A-Za-z0-9_-]{43}$/);
|
|
assert.match(pending.verifier, /^[A-Za-z0-9_-]{43}$/);
|
|
assert.notEqual(pending.state, pending.verifier);
|
|
assert.deepEqual(Object.keys(pending).sort(), ['created', 'state', 'verifier']);
|
|
assert.equal(target.origin, 'http://127.0.0.1:5173');
|
|
assert.equal(target.pathname, '/sso/authorize');
|
|
assert.deepEqual([...target.searchParams.keys()].sort(),
|
|
['client_id', 'redirect_uri', 'state', 'code_challenge', 'code_challenge_method'].sort());
|
|
assert.equal(target.searchParams.get('client_id'), 'kefu');
|
|
assert.equal(target.searchParams.get('redirect_uri'), config.redirect_uri);
|
|
assert.equal(target.searchParams.get('code_challenge_method'), 'S256');
|
|
const digest = Buffer.from(await webcrypto.subtle.digest('SHA-256', new TextEncoder().encode(pending.verifier))).toString('base64url');
|
|
assert.equal(target.searchParams.get('code_challenge'), digest);
|
|
assert.equal(sso.consumeGroupCallback(href, state, now).code_verifier, pending.verifier);
|
|
assert.equal(state.getItem(sso.GROUP_TRANSACTION_KEY), null);
|
|
assert.throws(() => sso.consumeGroupCallback(href, state, now));
|
|
});
|
|
|
|
test('state mismatch, expiry, duplicates, fragments and browser profiles consume and reject', async () => {
|
|
for (const mutation of [
|
|
href => href.replace(/state=.*/, `state=${'z'.repeat(43)}`),
|
|
href => `${href}&state=duplicate`, href => `${href}&code=duplicate`,
|
|
href => `${href}&profile=admin`, href => `${href}&redirect_uri=https://evil.example`,
|
|
href => `${href}#fragment`, href => href.replace(`code=${code}`, 'code=x'),
|
|
]) {
|
|
const { state, href } = await transaction();
|
|
assert.throws(() => sso.consumeGroupCallback(mutation(href), state, now));
|
|
assert.equal(state.getItem(sso.GROUP_TRANSACTION_KEY), null);
|
|
}
|
|
for (const time of [now - 1, now + 5 * 60 * 1000 + 1]) {
|
|
const { state, href } = await transaction();
|
|
assert.throws(() => sso.consumeGroupCallback(href, state, time));
|
|
assert.equal(state.getItem(sso.GROUP_TRANSACTION_KEY), null);
|
|
}
|
|
});
|
|
|
|
test('entry/callback validation rejects insecure and attacker controlled configuration', () => {
|
|
for (const entry of ['http://public.example', 'https://u:p@example.com', 'https://example.com/?x=1',
|
|
'https://example.com/#x', 'https://example.com/\\evil', 'https://example.com/%0a',
|
|
'https://example.com/\nx', 'javascript:alert(1)', 'https://example.com/a/../b']) {
|
|
assert.throws(() => sso.validateGroupConfig({ ...config, entry, authorize_url: `${entry}/sso/authorize` }, origin));
|
|
}
|
|
for (const change of [{ client_id: 'hospital' }, { enabled: false },
|
|
{ authorize_url: 'https://evil.example/sso/authorize' }, { redirect_uri: 'https://evil.example/auth/group-login' },
|
|
{ redirect_uri: `${origin}/other` }]) {
|
|
assert.throws(() => sso.validateGroupConfig({ ...config, ...change }, origin));
|
|
}
|
|
});
|
|
|
|
test('starting another login clears the old transaction', async () => {
|
|
const { state, pending } = await transaction();
|
|
await sso.beginGroupLogin(config, origin, state, webcrypto, now);
|
|
const next = JSON.parse(state.getItem(sso.GROUP_TRANSACTION_KEY));
|
|
assert.notEqual(next.state, pending.state);
|
|
assert.notEqual(next.verifier, pending.verifier);
|
|
await assert.rejects(sso.beginGroupLogin({ enabled: false }, origin, state, webcrypto, now));
|
|
assert.equal(state.getItem(sso.GROUP_TRANSACTION_KEY), null);
|
|
});
|
|
|
|
function authHarness() {
|
|
const events = [];
|
|
const access = { accessToken: 'old-admin', accessCodes: ['user:write'], accessMenus: ['admin-menu'],
|
|
accessRoutes: ['admin-route'], isAccessChecked: true, loginExpired: false,
|
|
setAccessToken(value) { this.accessToken = value; events.push(`token:${value}`); },
|
|
setAccessCodes(value) { this.accessCodes = value; }, setLoginExpired(value) { this.loginExpired = value; } };
|
|
const user = { userInfo: { userId: '1', roles: ['user:write'] }, setUserInfo(value) { this.userInfo = value; } };
|
|
const persisted = { tabs: ['admin-users'], cachedUser: 'admin', lock: true };
|
|
const router = { async replace(path) { events.push(`route:${path}`); }, currentRoute: { value: { fullPath: '/admin' } } };
|
|
let loginUser = { userId: '7', username: 'zyt_a', realName: '源账号', roles: [], homePath: '/group/welcome' };
|
|
const api = { async getUserInfoApi() { events.push('me'); return loginUser; },
|
|
async groupExchangeApi() { return { accessToken: 'new-basic' }; },
|
|
async loginApi() { return { accessToken: 'local-user' }; }, async logoutApi() {} };
|
|
const store = loadTs('../src/store/auth.ts', {
|
|
vue: { ref: value => ({ value }) }, 'vue-router': { useRouter: () => router },
|
|
'@vben/constants': { LOGIN_PATH: '/auth/login' }, '@vben/preferences': { preferences: { app: { defaultHomePath: '/model/stats' } } },
|
|
'@vben/stores': { useAccessStore: () => access, useUserStore: () => user,
|
|
resetAllStores() { events.push('reset-stores'); Object.assign(access, { accessToken: null, accessCodes: [],
|
|
accessMenus: [], accessRoutes: [], isAccessChecked: false }); user.userInfo = null;
|
|
Object.assign(persisted, { tabs: [], cachedUser: null, lock: false }); } },
|
|
'ant-design-vue': { notification: { success() {} } }, pinia: { defineStore: (_id, setup) => setup },
|
|
'#/api': api, '#/locales': { $t: key => key }, '#/router': { resetRoutes() { events.push('reset-routes'); } },
|
|
}).useAuthStore();
|
|
return { store, access, user, persisted, events, api, setUser: value => { loginUser = value; } };
|
|
}
|
|
|
|
test('SSO from old admin clears dynamic routes, menus, tabs and persisted identity before token installation', async () => {
|
|
const h = authHarness();
|
|
await h.store.authGroupLogin({ code, code_verifier: 'V'.repeat(43) });
|
|
assert.equal(h.access.accessToken, 'new-basic');
|
|
assert.equal(h.access.accessCodes.length, 0);
|
|
assert.equal(h.access.accessMenus.length, 0);
|
|
assert.equal(h.access.accessRoutes.length, 0);
|
|
assert.equal(h.access.isAccessChecked, false);
|
|
assert.equal(h.persisted.tabs.length, 0);
|
|
assert.equal(h.persisted.cachedUser, null);
|
|
assert.equal(h.persisted.lock, false);
|
|
assert.deepEqual(h.events, ['reset-routes', 'reset-stores', 'token:new-basic', 'me', 'route:/group/welcome']);
|
|
});
|
|
|
|
test('password login shares authoritative initialization and preserves forced password landing', async () => {
|
|
const h = authHarness();
|
|
h.setUser({ userId: '2', roles: ['model:read'], homePath: '/profile/password' });
|
|
await h.store.authLogin({ username: 'local', password: 'Fixture@2026' });
|
|
assert.equal(h.access.accessToken, 'local-user');
|
|
assert.deepEqual(h.access.accessCodes, ['model:read']);
|
|
assert.equal(h.events.at(-1), 'route:/profile/password');
|
|
});
|
|
|
|
test('failure to load current local identity clears the new token and authorization', async () => {
|
|
const h = authHarness();
|
|
h.api.getUserInfoApi = async () => { throw new Error('revoked'); };
|
|
await assert.rejects(h.store.authGroupLogin({ code, code_verifier: 'V'.repeat(43) }));
|
|
assert.equal(h.access.accessToken, null);
|
|
assert.equal(h.access.accessCodes.length, 0);
|
|
});
|