feat(audit): 收口领域写接口权限审计
This commit is contained in:
@@ -47,6 +47,44 @@ test('API requests use the resolved base path', async () => {
|
||||
}
|
||||
});
|
||||
|
||||
test('API requests include current auth user headers when a session exists', async () => {
|
||||
const originalFetch = globalThis.fetch;
|
||||
const originalSessionStorage = Object.getOwnPropertyDescriptor(globalThis, 'sessionStorage');
|
||||
const headers: HeadersInit[] = [];
|
||||
|
||||
Object.defineProperty(globalThis, 'sessionStorage', {
|
||||
configurable: true,
|
||||
value: {
|
||||
getItem: (key: string) => key === 'ftb_auth_session'
|
||||
? JSON.stringify({ id: 'm-8', name: '超级管理员', username: 'admin', roleId: 'role-admin', email: 'admin@example.com' })
|
||||
: null,
|
||||
},
|
||||
});
|
||||
|
||||
globalThis.fetch = (async (_input: RequestInfo | URL, init?: RequestInit) => {
|
||||
headers.push(init?.headers ?? {});
|
||||
return new Response(JSON.stringify({ ok: true }), {
|
||||
status: 200,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
});
|
||||
}) as typeof fetch;
|
||||
|
||||
try {
|
||||
__resetApiAvailabilityForTests();
|
||||
await api.post('/products', { name: 'FTB' });
|
||||
assert.equal((headers[1] as Record<string, string>)['x-ftb-user-id'], 'm-8');
|
||||
assert.equal((headers[1] as Record<string, string>)['x-ftb-user-role-id'], 'role-admin');
|
||||
assert.equal((headers[1] as Record<string, string>)['x-ftb-user-name'], encodeURIComponent('超级管理员'));
|
||||
} finally {
|
||||
globalThis.fetch = originalFetch;
|
||||
if (originalSessionStorage) {
|
||||
Object.defineProperty(globalThis, 'sessionStorage', originalSessionStorage);
|
||||
} else {
|
||||
delete (globalThis as any).sessionStorage;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('API availability probe retries after a transient failure', async () => {
|
||||
const originalFetch = globalThis.fetch;
|
||||
const apiBase = resolveApiBase();
|
||||
|
||||
@@ -13,6 +13,8 @@ export function resolveApiBase(env: ApiEnv = process.env) {
|
||||
}
|
||||
|
||||
const API_BASE = resolveApiBase();
|
||||
const AUTH_SESSION_KEY = 'ftb_auth_session';
|
||||
const AUTH_PERSIST_KEY = 'ftb_auth_persist';
|
||||
|
||||
function isLocalOnlyApiUrl(value: string) {
|
||||
try {
|
||||
@@ -67,7 +69,7 @@ async function request<T>(path: string, options?: RequestInit): Promise<T> {
|
||||
const available = await checkApi();
|
||||
if (!available) throw new Error('API 不可用');
|
||||
const res = await fetch(`${API_BASE}${path}`, {
|
||||
headers: { 'Content-Type': 'application/json', ...options?.headers },
|
||||
headers: { 'Content-Type': 'application/json', ...resolveAuthHeaders(), ...options?.headers },
|
||||
...options,
|
||||
}).catch(() => null);
|
||||
if (!res) {
|
||||
@@ -97,7 +99,7 @@ export const api = {
|
||||
try {
|
||||
const res = await fetch(`${API_BASE}${path}`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
headers: { 'Content-Type': 'application/json', ...resolveAuthHeaders() },
|
||||
body: JSON.stringify(data),
|
||||
signal: controller.signal,
|
||||
});
|
||||
@@ -116,3 +118,36 @@ export function __resetApiAvailabilityForTests() {
|
||||
apiAvailable = null;
|
||||
probePromise = null;
|
||||
}
|
||||
|
||||
function resolveAuthHeaders(): Record<string, string> {
|
||||
const user = readStoredAuthUser();
|
||||
if (!user?.id) return {};
|
||||
return {
|
||||
'x-ftb-user-id': user.id,
|
||||
...(user.roleId ? { 'x-ftb-user-role-id': user.roleId } : {}),
|
||||
...(user.name ? { 'x-ftb-user-name': encodeURIComponent(user.name) } : {}),
|
||||
...(user.username ? { 'x-ftb-user-username': user.username } : {}),
|
||||
...(user.email ? { 'x-ftb-user-email': user.email } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function readStoredAuthUser(): { id?: string; roleId?: string; name?: string; username?: string; email?: string } | null {
|
||||
if (typeof sessionStorage === 'undefined') return null;
|
||||
const raw = safeStorageGet(sessionStorage, AUTH_SESSION_KEY)
|
||||
?? (typeof localStorage === 'undefined' ? null : safeStorageGet(localStorage, AUTH_PERSIST_KEY));
|
||||
if (!raw) return null;
|
||||
try {
|
||||
const value = JSON.parse(raw);
|
||||
return value && typeof value === 'object' ? value : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function safeStorageGet(storage: Pick<Storage, 'getItem'>, key: string): string | null {
|
||||
try {
|
||||
return storage.getItem(key);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user