forked from linkong/planet
269 lines
7.9 KiB
JavaScript
269 lines
7.9 KiB
JavaScript
import { expect, test } from "bun:test";
|
|
import {
|
|
ADMIN_AUTH_REFRESH_ENDPOINT,
|
|
ADMIN_AUTH_REQUIRED_CODE,
|
|
ADMIN_AUTH_STORAGE_KEY,
|
|
fetchAdminWriteJson,
|
|
isAdminAuthRequiredError,
|
|
readStoredAdminAuthState,
|
|
} from "./admin-write-auth.js";
|
|
|
|
function createMemoryStorage(initialState = null) {
|
|
const store = new Map();
|
|
if (initialState !== null) {
|
|
store.set(ADMIN_AUTH_STORAGE_KEY, JSON.stringify(initialState));
|
|
}
|
|
return {
|
|
getItem(key) {
|
|
return store.has(key) ? store.get(key) : null;
|
|
},
|
|
setItem(key, value) {
|
|
store.set(key, String(value));
|
|
},
|
|
removeItem(key) {
|
|
store.delete(key);
|
|
},
|
|
};
|
|
}
|
|
|
|
function jsonResponse(status, body) {
|
|
return new Response(JSON.stringify(body), {
|
|
status,
|
|
headers: { "Content-Type": "application/json" },
|
|
});
|
|
}
|
|
|
|
test("refreshes expired access token on 401, persists tokens, and retries write request", async () => {
|
|
const storage = createMemoryStorage({
|
|
version: 0,
|
|
state: {
|
|
token: "expired-access",
|
|
refreshToken: "valid-refresh-1",
|
|
user: { id: 1, role: "admin" },
|
|
},
|
|
});
|
|
const calls = [];
|
|
const fetchImpl = async (url, init = {}) => {
|
|
calls.push({ url, method: init.method, auth: init.headers?.Authorization });
|
|
if (url === ADMIN_AUTH_REFRESH_ENDPOINT) {
|
|
return jsonResponse(200, {
|
|
access_token: "fresh-access-2",
|
|
refresh_token: "fresh-refresh-2",
|
|
user: { id: 1, role: "admin", username: "ops" },
|
|
});
|
|
}
|
|
if (init.headers?.Authorization === "Bearer expired-access") {
|
|
return jsonResponse(401, { detail: "Token expired" });
|
|
}
|
|
if (init.headers?.Authorization === "Bearer fresh-access-2") {
|
|
return jsonResponse(200, { success: true, candidates: [{ latitude: 1.2, longitude: 3.4 }] });
|
|
}
|
|
return jsonResponse(401, { detail: "Unexpected auth header" });
|
|
};
|
|
|
|
const response = await fetchAdminWriteJson(
|
|
"/api/v1/visualization/compute-centers/cc-1/collect-location",
|
|
{ name: "AI-03" },
|
|
{ fetchImpl, storage },
|
|
);
|
|
|
|
expect(response.status).toBe(200);
|
|
expect(await response.json()).toEqual({
|
|
success: true,
|
|
candidates: [{ latitude: 1.2, longitude: 3.4 }],
|
|
});
|
|
expect(calls).toEqual([
|
|
{
|
|
url: "/api/v1/visualization/compute-centers/cc-1/collect-location",
|
|
method: "POST",
|
|
auth: "Bearer expired-access",
|
|
},
|
|
{
|
|
url: ADMIN_AUTH_REFRESH_ENDPOINT,
|
|
method: "POST",
|
|
auth: "Bearer valid-refresh-1",
|
|
},
|
|
{
|
|
url: "/api/v1/visualization/compute-centers/cc-1/collect-location",
|
|
method: "POST",
|
|
auth: "Bearer fresh-access-2",
|
|
},
|
|
]);
|
|
|
|
const persisted = readStoredAdminAuthState(storage);
|
|
expect(persisted.token).toBe("fresh-access-2");
|
|
expect(persisted.refreshToken).toBe("fresh-refresh-2");
|
|
expect(persisted.user).toEqual({ id: 1, role: "admin", username: "ops" });
|
|
});
|
|
|
|
test("proactively refreshes when access token is missing but refresh token exists", async () => {
|
|
const storage = createMemoryStorage({
|
|
version: 0,
|
|
state: {
|
|
token: null,
|
|
refreshToken: "valid-refresh-only",
|
|
},
|
|
});
|
|
const calls = [];
|
|
const fetchImpl = async (url, init = {}) => {
|
|
calls.push({ url, auth: init.headers?.Authorization });
|
|
if (url === ADMIN_AUTH_REFRESH_ENDPOINT) {
|
|
return jsonResponse(200, {
|
|
access_token: "proactive-access",
|
|
refresh_token: "valid-refresh-only",
|
|
});
|
|
}
|
|
return jsonResponse(200, { saved: true });
|
|
};
|
|
|
|
const response = await fetchAdminWriteJson(
|
|
"/api/v1/visualization/compute-centers/cc-2/location",
|
|
{ latitude: 10, longitude: 20 },
|
|
{ fetchImpl, storage },
|
|
);
|
|
|
|
expect(response.status).toBe(200);
|
|
expect(calls).toEqual([
|
|
{ url: ADMIN_AUTH_REFRESH_ENDPOINT, auth: "Bearer valid-refresh-only" },
|
|
{ url: "/api/v1/visualization/compute-centers/cc-2/location", auth: "Bearer proactive-access" },
|
|
]);
|
|
});
|
|
|
|
test("deduplicates concurrent /auth/refresh calls when multiple writes hit 401 simultaneously", async () => {
|
|
const storage = createMemoryStorage({
|
|
version: 0,
|
|
state: {
|
|
token: "stale-token",
|
|
refreshToken: "shared-refresh",
|
|
},
|
|
});
|
|
let refreshCount = 0;
|
|
const fetchImpl = async (url, init = {}) => {
|
|
if (url === ADMIN_AUTH_REFRESH_ENDPOINT) {
|
|
refreshCount += 1;
|
|
await Promise.resolve();
|
|
return jsonResponse(200, {
|
|
access_token: "deduped-token",
|
|
refresh_token: "shared-refresh",
|
|
});
|
|
}
|
|
if (init.headers?.Authorization === "Bearer stale-token") {
|
|
return jsonResponse(401, { detail: "Expired" });
|
|
}
|
|
return jsonResponse(200, { ok: true, url });
|
|
};
|
|
|
|
const [resA, resB] = await Promise.all([
|
|
fetchAdminWriteJson("/api/v1/visualization/compute-centers/a/collect-location", {}, { fetchImpl, storage }),
|
|
fetchAdminWriteJson("/api/v1/visualization/compute-centers/b/collect-location", {}, { fetchImpl, storage }),
|
|
]);
|
|
|
|
expect(resA.status).toBe(200);
|
|
expect(resB.status).toBe(200);
|
|
expect(refreshCount).toBe(1);
|
|
});
|
|
|
|
test("throws typed ADMIN_AUTH_REQUIRED error and clears stale tokens when refresh rejects with 401", async () => {
|
|
const storage = createMemoryStorage({
|
|
version: 0,
|
|
state: {
|
|
token: "dead-access",
|
|
refreshToken: "dead-refresh",
|
|
},
|
|
});
|
|
const fetchImpl = async (url) => {
|
|
if (url === ADMIN_AUTH_REFRESH_ENDPOINT) {
|
|
return jsonResponse(401, { detail: "Invalid refresh token" });
|
|
}
|
|
return jsonResponse(401, { detail: "Invalid access token" });
|
|
};
|
|
|
|
let caught = null;
|
|
try {
|
|
await fetchAdminWriteJson(
|
|
"/api/v1/visualization/compute-centers/cc-3/collect-location",
|
|
{},
|
|
{ fetchImpl, storage },
|
|
);
|
|
} catch (error) {
|
|
caught = error;
|
|
}
|
|
|
|
expect(isAdminAuthRequiredError(caught)).toBe(true);
|
|
expect(caught?.code).toBe(ADMIN_AUTH_REQUIRED_CODE);
|
|
expect(caught?.status).toBe(401);
|
|
expect(caught?.loginUrl).toBe("/login");
|
|
|
|
const persisted = readStoredAdminAuthState(storage);
|
|
expect(persisted.token).toBe("");
|
|
expect(persisted.refreshToken).toBe("");
|
|
});
|
|
|
|
test("throws typed ADMIN_AUTH_REQUIRED immediately on 403 without refreshing or clearing storage", async () => {
|
|
const storage = createMemoryStorage({
|
|
version: 0,
|
|
state: {
|
|
token: "non-admin-access",
|
|
refreshToken: "non-admin-refresh",
|
|
},
|
|
});
|
|
let refreshCalls = 0;
|
|
const fetchImpl = async (url) => {
|
|
if (url === ADMIN_AUTH_REFRESH_ENDPOINT) {
|
|
refreshCalls += 1;
|
|
}
|
|
return jsonResponse(403, { detail: "Administrator privileges required" });
|
|
};
|
|
|
|
let caught = null;
|
|
try {
|
|
await fetchAdminWriteJson(
|
|
"/api/v1/visualization/compute-centers/cc-4/collect-location",
|
|
{},
|
|
{ fetchImpl, storage },
|
|
);
|
|
} catch (error) {
|
|
caught = error;
|
|
}
|
|
|
|
expect(refreshCalls).toBe(0);
|
|
expect(isAdminAuthRequiredError(caught)).toBe(true);
|
|
expect(caught?.code).toBe(ADMIN_AUTH_REQUIRED_CODE);
|
|
expect(caught?.status).toBe(403);
|
|
const persisted = readStoredAdminAuthState(storage);
|
|
expect(persisted.token).toBe("non-admin-access");
|
|
expect(persisted.refreshToken).toBe("non-admin-refresh");
|
|
});
|
|
|
|
test("preserves existing refresh token when /auth/refresh fails with transient 500", async () => {
|
|
const storage = createMemoryStorage({
|
|
version: 0,
|
|
state: {
|
|
token: "maybe-expired",
|
|
refreshToken: "keep-this-refresh",
|
|
},
|
|
});
|
|
const fetchImpl = async (url) => {
|
|
if (url === ADMIN_AUTH_REFRESH_ENDPOINT) {
|
|
return jsonResponse(500, { detail: "Temporary upstream failure" });
|
|
}
|
|
return jsonResponse(401, { detail: "Expired" });
|
|
};
|
|
|
|
let caught = null;
|
|
try {
|
|
await fetchAdminWriteJson(
|
|
"/api/v1/visualization/compute-centers/cc-5/collect-location",
|
|
{},
|
|
{ fetchImpl, storage },
|
|
);
|
|
} catch (error) {
|
|
caught = error;
|
|
}
|
|
|
|
expect(isAdminAuthRequiredError(caught)).toBe(true);
|
|
expect(caught?.status).toBe(401);
|
|
const persisted = readStoredAdminAuthState(storage);
|
|
expect(persisted.refreshToken).toBe("keep-this-refresh");
|
|
});
|