Add cloud enterprise storage mode and credential resolver
Enterprise configs gain a root-level storage field (default local). Cloud configs must not persist any secret and fail closed on load. Route credential reads through resolveCorpCredentials, which returns local fields unchanged and fails with exit code 11 for cloud enterprises until the bridge client lands. Cloud enterprises skip the local token store and delegation renewal.
This commit is contained in:
1 parent
837f4e2db6
commit
887df2d32f
14 files changed
+504
-41
No files matched your search
@@ -0,0 +1,100 @@
|
||||
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 { CorpConfigSchema, type CorpConfig } from "../config/types.js";
|
||||
import { CliError } from "../errors.js";
|
||||
import { getSealSessionForCorp } from "./seal.js";
|
||||
import { getSealSession } from "./token-store.js";
|
||||
import { isCloudCorp, resolveCorpCredentials } from "./credentials.js";
|
||||
|
||||
function localHoseCorp(): CorpConfig {
|
||||
return CorpConfigSchema.parse({
|
||||
id: "local-hose",
|
||||
name: "Local Hose",
|
||||
source: {
|
||||
type: "hose",
|
||||
domain: "https://app.ekuaibao.com",
|
||||
appKey: "app-key",
|
||||
appSecurity: "app-security",
|
||||
corpId: "ID01",
|
||||
staffId: "ID01:STAFF01"
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function localSealCorp(): CorpConfig {
|
||||
return CorpConfigSchema.parse({
|
||||
id: "local-seal",
|
||||
name: "Local Seal",
|
||||
seal: { cookies: { sdp_app_session: "cookie-value" } },
|
||||
source: {
|
||||
type: "seal",
|
||||
token: "seal-token",
|
||||
sealUrl: "https://seal.example.com"
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function cloudSealCorp(): CorpConfig {
|
||||
return CorpConfigSchema.parse({
|
||||
id: "cloud-seal",
|
||||
name: "Cloud Seal",
|
||||
storage: "cloud",
|
||||
source: {
|
||||
type: "seal",
|
||||
sealUrl: "https://seal.example.com"
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
describe("resolveCorpCredentials", () => {
|
||||
test("returns local hose credentials from the config", async () => {
|
||||
const credentials = await resolveCorpCredentials(localHoseCorp());
|
||||
expect(credentials).toEqual({
|
||||
appKey: "app-key",
|
||||
appSecurity: "app-security",
|
||||
closeToken: undefined
|
||||
});
|
||||
});
|
||||
|
||||
test("returns local seal credentials and gateway cookies", async () => {
|
||||
const credentials = await resolveCorpCredentials(localSealCorp());
|
||||
expect(credentials.token).toBe("seal-token");
|
||||
expect(credentials.cookies).toEqual({ sdp_app_session: "cookie-value" });
|
||||
});
|
||||
|
||||
test("fails closed with exit code 11 for cloud enterprises", async () => {
|
||||
const corp = cloudSealCorp();
|
||||
expect(isCloudCorp(corp)).toBe(true);
|
||||
|
||||
try {
|
||||
await resolveCorpCredentials(corp);
|
||||
throw new Error("expected resolveCorpCredentials to reject");
|
||||
} catch (error) {
|
||||
expect(error).toBeInstanceOf(CliError);
|
||||
expect((error as CliError).exitCode).toBe(11);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("cloud session isolation", () => {
|
||||
let tempDir: string;
|
||||
|
||||
beforeEach(() => {
|
||||
tempDir = mkdtempSync(join(tmpdir(), "seal-credentials-test-"));
|
||||
process.env.SEAL_USE_TOKEN_STORE = join(tempDir, "tokens.json");
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
delete process.env.SEAL_USE_TOKEN_STORE;
|
||||
rmSync(tempDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
test("cloud enterprises never read or write the local token store", async () => {
|
||||
const corp = cloudSealCorp();
|
||||
|
||||
await expect(getSealSessionForCorp(corp)).rejects.toBeInstanceOf(CliError);
|
||||
expect(getSealSession(corp.id)).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,55 @@
|
||||
import type { CorpConfig } from "../config/types.js";
|
||||
import { CliError } from "../errors.js";
|
||||
|
||||
/**
|
||||
* Credentials needed to authenticate one enterprise. `local` enterprises read
|
||||
* them from the config file; `cloud` enterprises will receive them from the
|
||||
* bridge credential service. Callers must never read `corp.source` secrets
|
||||
* directly so both modes share one path.
|
||||
*/
|
||||
export type CorpCredentials = {
|
||||
appKey?: string;
|
||||
appSecurity?: string;
|
||||
closeToken?: string;
|
||||
token?: string;
|
||||
cookies?: Record<string, string>;
|
||||
};
|
||||
|
||||
export function isCloudCorp(corp: CorpConfig): boolean {
|
||||
return (corp.storage ?? "local") === "cloud";
|
||||
}
|
||||
|
||||
export function cloudAuthRequiredError(corp: CorpConfig): CliError {
|
||||
return new CliError(
|
||||
`企业「${corp.name}」(id: ${corp.id}) 使用云端凭据,需要先登录桥接服务。`,
|
||||
11,
|
||||
"登录能力在阶段三提供;本地 (storage: local) 企业不受影响。"
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve credentials for a corp.
|
||||
*
|
||||
* Local enterprises return their config fields unchanged. Cloud enterprises
|
||||
* fail closed until the bridge client lands: there is no local secret to fall
|
||||
* back to, so a silent fallback would be worse than an explicit error.
|
||||
*/
|
||||
export async function resolveCorpCredentials(corp: CorpConfig): Promise<CorpCredentials> {
|
||||
if (isCloudCorp(corp)) {
|
||||
throw cloudAuthRequiredError(corp);
|
||||
}
|
||||
|
||||
const source = corp.source;
|
||||
if (source.type === "hose") {
|
||||
return {
|
||||
appKey: source.appKey,
|
||||
appSecurity: source.appSecurity,
|
||||
closeToken: source.closeToken
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
token: source.token,
|
||||
cookies: corp.seal.cookies
|
||||
};
|
||||
}
|
||||
+12
-8
@@ -3,6 +3,7 @@ import { CorpConfig, HoseSealSource } from "../config/types.js";
|
||||
import { createSealClientForUrl } from "../http/factory.js";
|
||||
import { resolveSealCustomHeaders } from "../http/request-headers.js";
|
||||
import { getHoseAuthCache, setHoseAuthCache } from "./token-store.js";
|
||||
import { isCloudCorp, resolveCorpCredentials, type CorpCredentials } from "./credentials.js";
|
||||
import { SealEnterpriseConfig, SealSession, TokenEntry } from "./types.js";
|
||||
|
||||
type HoseLoginResponse = {
|
||||
@@ -272,10 +273,10 @@ function hoseClient(source: HoseSealSource): KyInstance {
|
||||
});
|
||||
}
|
||||
|
||||
async function fetchHoseOpenapiToken(source: HoseSealSource): Promise<TokenEntry> {
|
||||
async function fetchHoseOpenapiToken(source: HoseSealSource, credentials: CorpCredentials): Promise<TokenEntry> {
|
||||
const client = hoseClient(source);
|
||||
const appKey = source.appKey;
|
||||
const appSecurity = source.appSecurity;
|
||||
const appKey = credentials.appKey;
|
||||
const appSecurity = credentials.appSecurity;
|
||||
|
||||
if (!appKey || !appSecurity) {
|
||||
throw new Error("Hose source has no OpenAPI credentials; the configured closeToken is only valid for Hose web-session APIs");
|
||||
@@ -308,7 +309,8 @@ export async function getHoseOpenapiToken(
|
||||
if (corp.source.type !== "hose") {
|
||||
throw new Error(`Unsupported Seal source: ${corp.source.type}`);
|
||||
}
|
||||
const cache = getHoseAuthCache(corp.id);
|
||||
const cloud = isCloudCorp(corp);
|
||||
const cache = cloud ? {} : getHoseAuthCache(corp.id);
|
||||
if (!options?.force && isFresh(cache.openapi)) {
|
||||
return { ...cache.openapi, cached: true };
|
||||
}
|
||||
@@ -316,7 +318,8 @@ export async function getHoseOpenapiToken(
|
||||
const pending = openapiTokenRequests.get(corp.id);
|
||||
if (pending) return { ...(await pending), cached: false };
|
||||
|
||||
const request = fetchHoseOpenapiToken(corp.source)
|
||||
const credentials = await resolveCorpCredentials(corp);
|
||||
const request = fetchHoseOpenapiToken(corp.source, credentials)
|
||||
.then((openapi) => {
|
||||
setHoseAuthCache(corp.id, {
|
||||
...getHoseAuthCache(corp.id),
|
||||
@@ -379,19 +382,20 @@ export async function ensureHoseCloseApiToken(corp: CorpConfig): Promise<TokenEn
|
||||
throw new Error(`Unsupported Seal source: ${corp.source.type}`);
|
||||
}
|
||||
const source = corp.source;
|
||||
const credentials = await resolveCorpCredentials(corp);
|
||||
|
||||
if (source.closeToken) {
|
||||
if (credentials.closeToken) {
|
||||
const expiresAt = source.expiresAt ? Date.parse(source.expiresAt) : Number.MAX_SAFE_INTEGER;
|
||||
if (expiresAt !== Number.MAX_SAFE_INTEGER && Date.now() >= expiresAt) {
|
||||
throw new Error("Configured Hose closeToken has expired; import a fresh Hose web session");
|
||||
}
|
||||
return {
|
||||
token: source.closeToken,
|
||||
token: credentials.closeToken,
|
||||
expiresAt
|
||||
};
|
||||
}
|
||||
|
||||
const cache = getHoseAuthCache(corp.id);
|
||||
const cache = isCloudCorp(corp) ? {} : getHoseAuthCache(corp.id);
|
||||
if (isFresh(cache.closeapi) && cache.closeapi.url) {
|
||||
return cache.closeapi;
|
||||
}
|
||||
|
||||
@@ -1,10 +1,16 @@
|
||||
import { CorpConfig } from "../config/types.js";
|
||||
import { validationError } from "../errors.js";
|
||||
import { SealSession } from "./types.js";
|
||||
|
||||
export async function getNativeSealSession(corp: CorpConfig): Promise<SealSession> {
|
||||
if (corp.source.type !== "seal") {
|
||||
throw new Error(`Unsupported Seal source: ${corp.source.type}`);
|
||||
}
|
||||
if (!corp.source.token) {
|
||||
throw validationError(
|
||||
`企业「${corp.name}」(id: ${corp.id}) 没有本地 Seal token;cloud 企业需先通过凭据服务登录后获取。`
|
||||
);
|
||||
}
|
||||
|
||||
const sealUrl = corp.seal.url ?? corp.source.sealUrl;
|
||||
const expiresAt = corp.source.expiresAt
|
||||
|
||||
+11
-2
@@ -15,6 +15,7 @@ import {
|
||||
rotateBackupCookies
|
||||
} from "./session-fallback.js";
|
||||
import { createSealDelegationLink, exchangeSealDelegateLink } from "./delegate.js";
|
||||
import { cloudAuthRequiredError, isCloudCorp } from "./credentials.js";
|
||||
import { saveCorpConfig } from "../config/repository.js";
|
||||
import { formatBeijingIso } from "../config/timestamps.js";
|
||||
|
||||
@@ -32,6 +33,8 @@ function isExpired(session: SealSession, refreshTtl: number): boolean {
|
||||
export async function renewNativeSealSession(corp: CorpConfig): Promise<SealSession | undefined> {
|
||||
const source = corp.source;
|
||||
if (source.type !== "seal") return undefined;
|
||||
// Cloud enterprises have no local token and never renew through delegation.
|
||||
if (!source.token) return undefined;
|
||||
|
||||
const authCache = getSealDelegateAuthCache(corp.id);
|
||||
const candidateCookies = resolveCandidateCookies(authCache);
|
||||
@@ -104,6 +107,11 @@ export async function renewNativeSealSession(corp: CorpConfig): Promise<SealSess
|
||||
}
|
||||
|
||||
async function refreshSealSession(corp: CorpConfig): Promise<SealSession> {
|
||||
if (isCloudCorp(corp)) {
|
||||
// Phase 3 replaces this with the bridge credential fetch.
|
||||
throw cloudAuthRequiredError(corp);
|
||||
}
|
||||
|
||||
switch (corp.source.type) {
|
||||
case "hose":
|
||||
return getHoseSealSession(corp);
|
||||
@@ -130,7 +138,8 @@ export async function getSealSessionForCorp(corp: CorpConfig): Promise<SealSessi
|
||||
return cached;
|
||||
}
|
||||
|
||||
const stored = getSealSession(corp.id);
|
||||
const cloud = isCloudCorp(corp);
|
||||
const stored = cloud ? undefined : getSealSession(corp.id);
|
||||
if (stored && !isExpired(stored, refreshTtl)) {
|
||||
memoryCache.set(corp.id, stored);
|
||||
return stored;
|
||||
@@ -140,7 +149,7 @@ export async function getSealSessionForCorp(corp: CorpConfig): Promise<SealSessi
|
||||
if (pending) return pending;
|
||||
const request = refreshSealSession(corp).then((next) => {
|
||||
memoryCache.set(corp.id, next);
|
||||
setSealSession(corp.id, next);
|
||||
if (!cloud) setSealSession(corp.id, next);
|
||||
return next;
|
||||
}).finally(() => pendingSessions.delete(corp.id));
|
||||
pendingSessions.set(corp.id, request);
|
||||
|
||||
@@ -135,7 +135,7 @@ function loadCorpConfigEntries(): Array<{ config: CorpConfig; path: string }> {
|
||||
// Materialize the tenant availability default so every config read from
|
||||
// disk carries an explicit boolean. Legacy files without `active` stay
|
||||
// enabled; `false` (explicit or normalized) gates command execution.
|
||||
corp = { ...parsed, active: parsed.active ?? true };
|
||||
corp = { ...parsed, active: parsed.active ?? true, storage: parsed.storage ?? "local" };
|
||||
} catch (error) {
|
||||
issues.push({ dir, file, reason: error instanceof Error ? error.message : String(error) });
|
||||
continue;
|
||||
|
||||
@@ -158,6 +158,108 @@ describe("CorpConfigSchema", () => {
|
||||
expect(config.source.tenantSlug).toBe("xiezihao");
|
||||
});
|
||||
|
||||
test("accepts a cloud hose source without local credentials", () => {
|
||||
const config = CorpConfigSchema.parse({
|
||||
id: "cloud-hose",
|
||||
name: "Cloud Hose",
|
||||
storage: "cloud",
|
||||
source: {
|
||||
type: "hose",
|
||||
domain: "https://app.ekuaibao.com",
|
||||
corpId: "ID01",
|
||||
staffId: "ID01:STAFF01"
|
||||
}
|
||||
});
|
||||
|
||||
expect(config.storage).toBe("cloud");
|
||||
expect(config.source.type).toBe("hose");
|
||||
});
|
||||
|
||||
test("accepts a cloud seal source without a local token", () => {
|
||||
const config = CorpConfigSchema.parse({
|
||||
id: "cloud-seal",
|
||||
name: "Cloud Seal",
|
||||
storage: "cloud",
|
||||
source: {
|
||||
type: "seal",
|
||||
sealUrl: "https://seal.sealai.cc"
|
||||
}
|
||||
});
|
||||
|
||||
expect(config.storage).toBe("cloud");
|
||||
expect(config.source.type).toBe("seal");
|
||||
});
|
||||
|
||||
test("rejects cloud configs that still persist secrets", () => {
|
||||
const hoseResult = CorpConfigSchema.safeParse({
|
||||
id: "cloud-hose",
|
||||
name: "Cloud Hose",
|
||||
storage: "cloud",
|
||||
source: {
|
||||
type: "hose",
|
||||
domain: "https://app.ekuaibao.com",
|
||||
appKey: "app-key",
|
||||
corpId: "ID01",
|
||||
staffId: "ID01:STAFF01"
|
||||
}
|
||||
});
|
||||
expect(hoseResult.success).toBe(false);
|
||||
|
||||
const sealResult = CorpConfigSchema.safeParse({
|
||||
id: "cloud-seal",
|
||||
name: "Cloud Seal",
|
||||
storage: "cloud",
|
||||
source: {
|
||||
type: "seal",
|
||||
token: "seal-token",
|
||||
sealUrl: "https://seal.sealai.cc"
|
||||
}
|
||||
});
|
||||
expect(sealResult.success).toBe(false);
|
||||
|
||||
const cookieResult = CorpConfigSchema.safeParse({
|
||||
id: "cloud-seal-cookie",
|
||||
name: "Cloud Seal Cookie",
|
||||
storage: "cloud",
|
||||
seal: {
|
||||
url: "https://seal.sealai.cc",
|
||||
cookies: { sdp_app_session: "secret" }
|
||||
},
|
||||
source: {
|
||||
type: "seal",
|
||||
sealUrl: "https://seal.sealai.cc"
|
||||
}
|
||||
});
|
||||
expect(cookieResult.success).toBe(false);
|
||||
});
|
||||
|
||||
test("legacy configs without storage remain local", () => {
|
||||
const config = CorpConfigSchema.parse({
|
||||
id: "legacy-local",
|
||||
name: "Legacy Local",
|
||||
source: {
|
||||
type: "seal",
|
||||
token: "seal-token",
|
||||
sealUrl: "https://seal.sealai.cc"
|
||||
}
|
||||
});
|
||||
|
||||
expect(config.storage).toBeUndefined();
|
||||
});
|
||||
|
||||
test("requires a token for local seal sources", () => {
|
||||
const result = CorpConfigSchema.safeParse({
|
||||
id: "local-seal",
|
||||
name: "Local Seal",
|
||||
source: {
|
||||
type: "seal",
|
||||
sealUrl: "https://seal.sealai.cc"
|
||||
}
|
||||
});
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
});
|
||||
|
||||
test("leaves custom headers and cookies absent by default", () => {
|
||||
const config = CorpConfigSchema.parse({
|
||||
id: "seal",
|
||||
|
||||
+68
-17
@@ -17,27 +17,13 @@ export const HoseSealSourceSchema = z.object({
|
||||
staffId: z.string(),
|
||||
corpId: z.string(),
|
||||
sealUrl: z.string().url().optional()
|
||||
}).superRefine((source, ctx) => {
|
||||
if (!source.closeToken && !source.appKey) {
|
||||
ctx.addIssue({
|
||||
code: "custom",
|
||||
path: ["appKey"],
|
||||
message: "Hose source requires appKey or closeToken"
|
||||
});
|
||||
}
|
||||
|
||||
if (!source.closeToken && !source.appSecurity) {
|
||||
ctx.addIssue({
|
||||
code: "custom",
|
||||
path: ["appSecurity"],
|
||||
message: "Hose source requires appSecurity or closeToken"
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
export const NativeSealSourceSchema = z.object({
|
||||
type: z.literal("seal"),
|
||||
token: z.string(),
|
||||
// Optional at the source level: local enterprises must supply it, while
|
||||
// cloud enterprises obtain it at runtime. CorpConfigSchema enforces both.
|
||||
token: z.string().optional(),
|
||||
sealUrl: z.string().url(),
|
||||
expiresIn: z.number().int().positive().default(3600),
|
||||
expiresAt: IsoSecondTimestampSchema.optional(),
|
||||
@@ -104,9 +90,18 @@ export const CorpAuthConfigSchema = z.object({
|
||||
|
||||
export const CorpEnvironmentSchema = z.enum(["production", "test"]).default("production");
|
||||
|
||||
/**
|
||||
* Where the enterprise credentials live. `local` keeps them in this file;
|
||||
* `cloud` keeps them in the bridge credential service and the local file must
|
||||
* not contain any secret. Absent means `local` for legacy configs; the loader
|
||||
* materializes it on read.
|
||||
*/
|
||||
export const CorpStorageSchema = z.enum(["local", "cloud"]);
|
||||
|
||||
export const CorpConfigSchema = z.object({
|
||||
id: z.string(),
|
||||
name: z.string(),
|
||||
storage: CorpStorageSchema.optional(),
|
||||
// Tenant availability gate. It lives on the enterprise, NOT on a source, so
|
||||
// `hose` and `seal` sources share exactly one switch and cannot diverge.
|
||||
// Fail-closed three-way semantics:
|
||||
@@ -124,6 +119,61 @@ export const CorpConfigSchema = z.object({
|
||||
environment: CorpEnvironmentSchema,
|
||||
testCorpId: z.string().optional(),
|
||||
prodCorpId: z.string().optional()
|
||||
}).superRefine((config, ctx) => {
|
||||
const storage = config.storage ?? "local";
|
||||
const source = config.source;
|
||||
|
||||
if (storage === "cloud") {
|
||||
if (source.type === "hose") {
|
||||
for (const field of ["appKey", "appSecurity", "closeToken"] as const) {
|
||||
if (source[field] !== undefined) {
|
||||
ctx.addIssue({
|
||||
code: "custom",
|
||||
path: ["source", field],
|
||||
message: `cloud storage must not persist ${field}; manage it in the credential service`
|
||||
});
|
||||
}
|
||||
}
|
||||
} else if (source.token !== undefined) {
|
||||
ctx.addIssue({
|
||||
code: "custom",
|
||||
path: ["source", "token"],
|
||||
message: "cloud storage must not persist token; manage it in the credential service"
|
||||
});
|
||||
}
|
||||
|
||||
if (config.seal.cookies && Object.keys(config.seal.cookies).length > 0) {
|
||||
ctx.addIssue({
|
||||
code: "custom",
|
||||
path: ["seal", "cookies"],
|
||||
message: "cloud storage must not persist seal.cookies; manage them in the credential service"
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (source.type === "hose") {
|
||||
if (!source.closeToken && !source.appKey) {
|
||||
ctx.addIssue({
|
||||
code: "custom",
|
||||
path: ["source", "appKey"],
|
||||
message: "Hose source requires appKey or closeToken"
|
||||
});
|
||||
}
|
||||
if (!source.closeToken && !source.appSecurity) {
|
||||
ctx.addIssue({
|
||||
code: "custom",
|
||||
path: ["source", "appSecurity"],
|
||||
message: "Hose source requires appSecurity or closeToken"
|
||||
});
|
||||
}
|
||||
} else if (!source.token) {
|
||||
ctx.addIssue({
|
||||
code: "custom",
|
||||
path: ["source", "token"],
|
||||
message: "Seal source requires token"
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
export const GlobalLintConfigSchema = z.object({
|
||||
@@ -144,6 +194,7 @@ export const GlobalConfigSchema = z.object({
|
||||
});
|
||||
|
||||
export type CorpEnvironment = z.infer<typeof CorpEnvironmentSchema>;
|
||||
export type CorpStorage = z.infer<typeof CorpStorageSchema>;
|
||||
export type HoseSealSource = z.infer<typeof HoseSealSourceSchema>;
|
||||
export type NativeSealSource = z.infer<typeof NativeSealSourceSchema>;
|
||||
export type SealSource = z.infer<typeof SealSourceSchema>;
|
||||
|
||||
Reference in new issue
Block a user