Files
seal-use/src/core/auth/seal-renew.test.ts
T
gitea 8d6b65d3d5 Remove redundant enterprise provider metadata
Drop source.provider/providerName, cached enterprise.provider, onboarding writes, CLI outputs, and the search index entry; legacy configs and token caches still parse. Add a compatibility test for stripping the old keys.
2026-11-19 15:48:59 +08:00

318 lines
11 KiB
TypeScript

import { afterEach, beforeEach, describe, expect, test } from "bun:test";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import type { CorpConfig } from "../config/types.js";
import {
clearSealToken,
getSealSessionForCorp,
recoverSealSessionForCorp,
renewNativeSealSession
} from "./seal.js";
import {
getSealDelegateAuthCache,
getSealSession,
setSealDelegateAuthCache
} from "./token-store.js";
const originalFetch = globalThis.fetch;
let tempDir: string;
let storePath: string;
const fixtureCorp: CorpConfig = {
id: "test-delegate-corp",
name: "测试委托租户",
environment: "production",
seal: {
url: "https://mytenant.sealai.cc",
tenantSlug: "mytenant",
endpoints: { approvalStylePreferences: "api/v1/agent/ai-approval/config" }
},
source: {
type: "seal",
token: "initial-static-token",
sealUrl: "https://mytenant.sealai.cc",
expiresIn: 3600,
expiresAt: new Date(Date.now() + 3600 * 1000).toISOString(),
staffId: "u-123",
corpId: "test-delegate-corp",
tenantId: "t-456",
tenantSlug: "mytenant",
tenantName: "My Tenant"
},
auth: { refreshTtl: 300 }
};
describe("seal-renew: 原生 Seal 协助授权长效续期与会话池救险", () => {
beforeEach(() => {
tempDir = mkdtempSync(join(tmpdir(), "seal-renew-test-"));
storePath = join(tempDir, "tokens.json");
process.env.SEAL_USE_TOKEN_STORE = storePath;
clearSealToken(fixtureCorp.id);
});
afterEach(() => {
globalThis.fetch = originalFetch;
clearSealToken(fixtureCorp.id);
delete process.env.SEAL_USE_TOKEN_STORE;
rmSync(tempDir, { recursive: true, force: true });
});
test("无可用 Cookie 时安全返回 undefined,平滑回退到静态 token", async () => {
const renewed = await renewNativeSealSession(fixtureCorp);
expect(renewed).toBeUndefined();
const session = await getSealSessionForCorp(fixtureCorp);
expect(session.token).toBe("initial-static-token");
});
test("主 Cookie 有效时成功自动续期换发新 token,并轮转归档历史 Cookie", async () => {
setSealDelegateAuthCache(fixtureCorp.id, {
cookie: "__Secure-x-seal.session_token=old-cookie-token",
backupCookies: []
});
let delegationCreateCalledWithCookie = "";
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
const url = new URL(
typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url
);
const headers = input instanceof Request ? input.headers : new Headers(init?.headers);
if (url.pathname === "/api/v1/delegation/create") {
delegationCreateCalledWithCookie = headers.get("cookie") || "";
return new Response(
JSON.stringify({
data: {
link: "https://mytenant.sealai.cc/delegate?token=minted-delegation-token",
token: "minted-delegation-token"
}
}),
{ headers: { "Content-Type": "application/json" } }
);
}
if (url.pathname === "/api/v1/delegation/consume") {
return new Response(
JSON.stringify({
data: {
userId: "u-123",
userName: "Alice",
tenantId: "t-456",
tenantName: "My Tenant",
delegationId: "del-new"
}
}),
{
headers: {
"Content-Type": "application/json",
"Set-Cookie":
"__Secure-x-seal.session_token=fresh-cookie-token.sig; Path=/; HttpOnly; Secure"
}
}
);
}
if (url.pathname === "/api/auth/get-session") {
return new Response(
JSON.stringify({
user: { id: "u-123", name: "Alice" },
session: {
token: "brand-new-bearer-token",
expiresAt: new Date(Date.now() + 168 * 3600 * 1000).toISOString()
}
}),
{ headers: { "Content-Type": "application/json" } }
);
}
if (url.pathname === "/api/v1/auth/me") {
return new Response(
JSON.stringify({
data: {
user: { id: "u-123", name: "Alice" },
tenant: { id: "t-456", name: "My Tenant", tenantSlug: "mytenant" }
}
}),
{ headers: { "Content-Type": "application/json" } }
);
}
return new Response("Not found", { status: 404 });
}) as typeof fetch;
const renewed = await renewNativeSealSession(fixtureCorp);
expect(renewed).toBeDefined();
expect(renewed!.token).toBe("brand-new-bearer-token");
expect(delegationCreateCalledWithCookie).toBe(
"__Secure-x-seal.session_token=old-cookie-token"
);
// 检查 tokens.json 中更新状态
const delegateCache = getSealDelegateAuthCache(fixtureCorp.id);
expect(delegateCache.cookie).toBe("__Secure-x-seal.session_token=fresh-cookie-token.sig");
expect(delegateCache.backupCookies).toEqual(["__Secure-x-seal.session_token=old-cookie-token"]);
// 再次读取 session 命中新缓存
const session = await getSealSessionForCorp(fixtureCorp);
expect(session.token).toBe("brand-new-bearer-token");
});
test("主 Cookie 失效时,依次由 backupCookies 兜底救险成功(断电超期场景)", async () => {
// 模拟主 Cookie 已在服务端注销失效,但历史 backupCookies 中包含一份 30 天未过期的长效会话
setSealDelegateAuthCache(fixtureCorp.id, {
cookie: "expired-cookie",
backupCookies: ["valid-backup-cookie"]
});
const attemptedCookies: string[] = [];
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
const url = new URL(
typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url
);
const headers = input instanceof Request ? input.headers : new Headers(init?.headers);
if (url.pathname === "/api/v1/delegation/create") {
const cookie = headers.get("cookie") || "";
attemptedCookies.push(cookie);
if (cookie === "expired-cookie") {
return new Response(JSON.stringify({ error: { message: "Session expired" } }), {
status: 401,
headers: { "Content-Type": "application/json" }
});
}
return new Response(
JSON.stringify({
data: {
link: "https://mytenant.sealai.cc/delegate?token=rescued-delegation-token",
token: "rescued-delegation-token"
}
}),
{ headers: { "Content-Type": "application/json" } }
);
}
if (url.pathname === "/api/v1/delegation/consume") {
return new Response(
JSON.stringify({
data: {
userId: "u-123",
userName: "Alice",
tenantId: "t-456",
tenantName: "My Tenant"
}
}),
{
headers: {
"Content-Type": "application/json",
"Set-Cookie": "__Secure-x-seal.session_token=rescued-cookie.sig; Path=/; HttpOnly"
}
}
);
}
if (url.pathname === "/api/auth/get-session") {
return new Response(
JSON.stringify({
session: {
token: "rescued-bearer-token",
expiresAt: new Date(Date.now() + 168 * 3600 * 1000).toISOString()
}
}),
{ headers: { "Content-Type": "application/json" } }
);
}
if (url.pathname === "/api/v1/auth/me") {
return new Response(
JSON.stringify({
data: {
user: { id: "u-123", name: "Alice" },
tenant: { id: "t-456", name: "My Tenant", tenantSlug: "mytenant" }
}
}),
{ headers: { "Content-Type": "application/json" } }
);
}
return new Response("Not found", { status: 404 });
}) as typeof fetch;
const renewed = await renewNativeSealSession(fixtureCorp);
expect(renewed).toBeDefined();
expect(renewed!.token).toBe("rescued-bearer-token");
expect(attemptedCookies).toEqual(["expired-cookie", "valid-backup-cookie"]);
const delegateCache = getSealDelegateAuthCache(fixtureCorp.id);
expect(delegateCache.cookie).toBe("__Secure-x-seal.session_token=rescued-cookie.sig");
expect(delegateCache.backupCookies).toContain("valid-backup-cookie");
});
test("recoverSealSessionForCorp 在收到 401 时自动触发自愈", async () => {
setSealDelegateAuthCache(fixtureCorp.id, {
cookie: "valid-cookie",
backupCookies: []
});
globalThis.fetch = (async (input: RequestInfo | URL) => {
const url = new URL(
typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url
);
if (url.pathname === "/api/v1/delegation/create") {
return new Response(
JSON.stringify({
data: {
link: "https://mytenant.sealai.cc/delegate?token=recovered-delegation-token",
token: "recovered-delegation-token"
}
}),
{ headers: { "Content-Type": "application/json" } }
);
}
if (url.pathname === "/api/v1/delegation/consume") {
return new Response(
JSON.stringify({
data: { userId: "u-123", userName: "Alice", tenantId: "t-456", tenantName: "My Tenant" }
}),
{
headers: {
"Content-Type": "application/json",
"Set-Cookie": "__Secure-x-seal.session_token=recovered-cookie.sig"
}
}
);
}
if (url.pathname === "/api/auth/get-session") {
return new Response(
JSON.stringify({
session: {
token: "recovered-bearer-token",
expiresAt: new Date(Date.now() + 168 * 3600 * 1000).toISOString()
}
}),
{ headers: { "Content-Type": "application/json" } }
);
}
if (url.pathname === "/api/v1/auth/me") {
return new Response(
JSON.stringify({
data: {
user: { id: "u-123", name: "Alice" },
tenant: { id: "t-456", name: "My Tenant", tenantSlug: "mytenant" }
}
}),
{ headers: { "Content-Type": "application/json" } }
);
}
return new Response("Not found", { status: 404 });
}) as typeof fetch;
// 假设当前正在使用 stale-token 遭遇 401
const recovered = await recoverSealSessionForCorp(fixtureCorp, "initial-static-token");
expect(recovered.token).toBe("recovered-bearer-token");
const sessionInStore = getSealSession(fixtureCorp.id);
expect(sessionInStore?.token).toBe("recovered-bearer-token");
});
});