diff --git a/src/cli/commands/corps.ts b/src/cli/commands/corps.ts index 65d92f4..c9bcae8 100644 --- a/src/cli/commands/corps.ts +++ b/src/cli/commands/corps.ts @@ -10,12 +10,14 @@ import { } from "../../core/auth/hose.js"; import { clearCorpTokenCache } from "../../core/auth/token-store.js"; import { createSealClientForUrl } from "../../core/http/factory.js"; +import { resolveSealCustomHeaders } from "../../core/http/request-headers.js"; import { loadCorpConfigs, loadGlobalConfig, resolveWritableEnterprisesDir, saveGlobalConfig } from "../../core/config/loader.js"; +import { SealCookieMapSchema, SealHeaderMapSchema } from "../../core/config/types.js"; import type { CorpConfig } from "../../core/config/types.js"; import { getMe } from "../../domains/seal/api.js"; import { resolveLiveSealEnterpriseConfig } from "../../domains/seal/source.js"; @@ -374,8 +376,20 @@ async function addSealCorp(input: Record) { const expiresIn = optionalNumber(input, "expiresIn") ?? 30 * 24 * 60 * 60; const verify = input.force === true || input.verify === false ? false : true; - const remote = verify ? await resolveSealWhoami(sealUrl, token) : undefined; - writeSealCorpConfig(input, { token, sealUrl, expiresIn, verify, remote }); + const custom = sealCustomHeadersFromInput(input); + const remote = verify + ? await resolveSealWhoami(sealUrl, token, resolveSealCustomHeaders(custom)) + : undefined; + writeSealCorpConfig(input, { token, sealUrl, expiresIn, verify, remote, custom }); +} + +// Validates extra headers/cookies up front so a malformed name fails here +// rather than on the next config load. +function sealCustomHeadersFromInput(input: Record) { + return { + headers: SealHeaderMapSchema.parse(input.headers), + cookies: SealCookieMapSchema.parse(input.cookies) + }; } async function addLinkCorp(link: string, name: string | undefined, overwrite: boolean) { @@ -419,9 +433,11 @@ function writeSealCorpConfig( expiresIn: number; verify: boolean; remote?: RemoteSealIdentity; + custom?: { headers?: Record; cookies?: Record }; } ) { const { token, sealUrl, expiresIn, verify, remote } = auth; + const custom = auth.custom ?? sealCustomHeadersFromInput(input); const remoteUser = remote?.user; const remoteTenant = remote?.tenant; const tenantSlug = optionalString(input, "tenantSlug") ?? stringValue(remoteTenant?.tenantSlug); @@ -447,6 +463,8 @@ function writeSealCorpConfig( seal: { url: sealUrl, tenantSlug, + headers: custom.headers, + cookies: custom.cookies, endpoints: { approvalStylePreferences: "api/v1/agent/ai-approval/config" } @@ -522,8 +540,9 @@ async function resolveHoseCorporation(domain: string, appKey: string, appSecurit : undefined; } -async function resolveSealWhoami(sealUrl: string, token: string) { +async function resolveSealWhoami(sealUrl: string, token: string, customHeaders: Record = {}) { const json = await getJson(`${sealUrl}/api/v1/auth/me`, { + ...customHeaders, authorization: `Bearer ${token}` }); const data = objectValue(json.data); diff --git a/src/core/config/types.test.ts b/src/core/config/types.test.ts index 4f22fa8..53d75af 100644 --- a/src/core/config/types.test.ts +++ b/src/core/config/types.test.ts @@ -1,5 +1,10 @@ import { describe, expect, test } from "bun:test"; -import { CorpConfigSchema, GlobalConfigSchema } from "./types.js"; +import { + CorpConfigSchema, + GlobalConfigSchema, + SealCookieMapSchema, + SealHeaderMapSchema +} from "./types.js"; describe("CorpConfigSchema", () => { test("accepts Hose key/password aliases", () => { @@ -78,6 +83,59 @@ describe("CorpConfigSchema", () => { expect(config.source.staffId).toBe("seal"); expect(config.source.tenantSlug).toBe("xiezihao"); }); + + test("leaves custom headers and cookies absent by default", () => { + const config = CorpConfigSchema.parse({ + id: "direct", + name: "Direct", + source: { + type: "direct", + token: "seal-token", + sealUrl: "https://direct.sealai.cc" + } + }); + + expect(config.seal.headers).toBeUndefined(); + expect(config.seal.cookies).toBeUndefined(); + }); + + test("accepts custom headers and cookies on the Seal endpoint", () => { + const config = CorpConfigSchema.parse({ + id: "gated", + name: "Gated", + seal: { + url: "https://gated.sealai.cc", + headers: { "X-Tenant": "acme" }, + cookies: { sdp_app_session_20142: "abc" } + }, + source: { + type: "direct", + token: "seal-token", + sealUrl: "https://gated.sealai.cc" + } + }); + + expect(config.seal.headers).toEqual({ "X-Tenant": "acme" }); + expect(config.seal.cookies).toEqual({ sdp_app_session_20142: "abc" }); + }); +}); + +describe("Seal custom header schemas", () => { + test("rejects an Authorization header supplied through config", () => { + expect(SealHeaderMapSchema.safeParse({ Authorization: "Bearer x" }).success).toBe(false); + expect(SealHeaderMapSchema.safeParse({ authorization: "Bearer x" }).success).toBe(false); + }); + + test("rejects malformed header and cookie names", () => { + expect(SealHeaderMapSchema.safeParse({ "bad name": "v" }).success).toBe(false); + expect(SealCookieMapSchema.safeParse({ "bad;name": "v" }).success).toBe(false); + }); + + test("rejects cookie values containing separators", () => { + expect(SealCookieMapSchema.safeParse({ name: "v;other=1" }).success).toBe(false); + expect(SealCookieMapSchema.safeParse({ name: "line\nbreak" }).success).toBe(false); + expect(SealCookieMapSchema.safeParse({ name: "ok-value" }).success).toBe(true); + }); }); describe("GlobalConfigSchema", () => { diff --git a/src/core/config/types.ts b/src/core/config/types.ts index 5adb714..bee4d9f 100644 --- a/src/core/config/types.ts +++ b/src/core/config/types.ts @@ -58,9 +58,38 @@ export const SealSourceSchema = z.discriminatedUnion("type", [ NativeSealSourceSchema ]); +// RFC 7230 token: shared by HTTP header names and cookie names. +const HTTP_TOKEN_PATTERN = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/; + +export const SealHeaderMapSchema = z.record( + z.string().regex(HTTP_TOKEN_PATTERN, "Invalid HTTP header name"), + z.string() +).superRefine((headers, ctx) => { + for (const name of Object.keys(headers)) { + if (name.toLowerCase() === "authorization") { + ctx.addIssue({ + code: "custom", + path: [name], + message: "seal.headers cannot set Authorization; the Seal session supplies the bearer token" + }); + } + } +}).optional(); + +export const SealCookieMapSchema = z.record( + z.string().regex(HTTP_TOKEN_PATTERN, "Invalid cookie name"), + z.string().refine((value) => !/[\u0000-\u001f\u007f;]/.test(value), { + message: "Cookie value cannot contain control characters or semicolons" + }) +).optional(); + export const SealEndpointSchema = z.object({ url: z.string().url().optional(), tenantSlug: z.string().optional(), + // Extra headers/cookies for Seal deployments reachable only through an + // upstream gateway that expects its own session cookie. + headers: SealHeaderMapSchema, + cookies: SealCookieMapSchema, endpoints: z.object({ approvalStylePreferences: z.string().default("api/v1/agent/ai-approval/config") }).default({ diff --git a/src/core/http/factory.ts b/src/core/http/factory.ts index b47e52d..a0d2889 100644 --- a/src/core/http/factory.ts +++ b/src/core/http/factory.ts @@ -1,6 +1,7 @@ import ky, { HTTPError, KyInstance } from "ky"; import { CorpConfig } from "../config/types.js"; import { clearSealToken, getSealSessionForCorp } from "../auth/seal.js"; +import { resolveSealCustomHeaders } from "./request-headers.js"; export async function createSealClient(corp: CorpConfig): Promise { const session = await getSealSessionForCorp(corp); @@ -9,6 +10,7 @@ export async function createSealClient(corp: CorpConfig): Promise { prefix: session.enterprise.sealUrl, timeout: 30000, headers: { + ...resolveSealCustomHeaders(corp.seal), Authorization: `Bearer ${session.token}` }, hooks: { @@ -32,14 +34,19 @@ export async function createSealClient(corp: CorpConfig): Promise { export async function createSealClientForToken(corp: CorpConfig, token: string): Promise { const session = await getSealSessionForCorp(corp); - return createSealClientForUrl(session.enterprise.sealUrl, token); + return createSealClientForUrl(session.enterprise.sealUrl, token, resolveSealCustomHeaders(corp.seal)); } -export function createSealClientForUrl(sealUrl: string, token: string): KyInstance { +export function createSealClientForUrl( + sealUrl: string, + token: string, + customHeaders: Record = {} +): KyInstance { return ky.create({ prefix: sealUrl.replace(/\/+$/, ""), timeout: 30000, headers: { + ...customHeaders, Authorization: `Bearer ${token}` }, hooks: { diff --git a/src/core/http/request-headers.test.ts b/src/core/http/request-headers.test.ts new file mode 100644 index 0000000..4f42a0c --- /dev/null +++ b/src/core/http/request-headers.test.ts @@ -0,0 +1,64 @@ +import { describe, expect, test } from "bun:test"; +import { createSealClientForUrl } from "./factory.js"; +import { formatCookieHeader, resolveSealCustomHeaders } from "./request-headers.js"; + +describe("formatCookieHeader", () => { + test("returns undefined when there are no cookies", () => { + expect(formatCookieHeader(undefined)).toBeUndefined(); + expect(formatCookieHeader({})).toBeUndefined(); + }); + + test("joins cookies with a semicolon and a space", () => { + expect(formatCookieHeader({ a: "1", b: "2" })).toBe("a=1; b=2"); + }); +}); + +describe("resolveSealCustomHeaders", () => { + test("returns an empty map when no custom headers are configured", () => { + expect(resolveSealCustomHeaders(undefined)).toEqual({}); + }); + + test("keeps configured headers and renders cookies", () => { + expect(resolveSealCustomHeaders({ + headers: { "X-Tenant": "acme" }, + cookies: { sdp_session: "token" } + })).toEqual({ + "X-Tenant": "acme", + Cookie: "sdp_session=token" + }); + }); + + test("lets configured cookies replace a raw Cookie header", () => { + expect(resolveSealCustomHeaders({ + headers: { Cookie: "stale=1" }, + cookies: { fresh: "2" } + })).toEqual({ Cookie: "fresh=2" }); + }); +}); + +describe("createSealClientForUrl", () => { + test("sends custom headers and keeps the session Authorization", async () => { + const originalFetch = globalThis.fetch; + let sent: Headers | undefined; + globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => { + const request = input instanceof Request ? input : new Request(input, init); + sent = new Headers(request.headers); + return new Response(JSON.stringify({ data: {} }), { + headers: { "content-type": "application/json" } + }); + }) as typeof fetch; + + try { + const client = createSealClientForUrl("https://corp-a.sealai.cc", "session-token", { + Cookie: "sdp_session=token", + Authorization: "Bearer stale" + }); + await client.get("api/v1/auth/me"); + } finally { + globalThis.fetch = originalFetch; + } + + expect(sent?.get("cookie")).toBe("sdp_session=token"); + expect(sent?.get("authorization")).toBe("Bearer session-token"); + }); +}); diff --git a/src/core/http/request-headers.ts b/src/core/http/request-headers.ts new file mode 100644 index 0000000..1c6674e --- /dev/null +++ b/src/core/http/request-headers.ts @@ -0,0 +1,20 @@ +import type { CorpConfig } from "../config/types.js"; + +// The subset of the Seal endpoint config that carries extra request headers. +export type SealCustomHeaderSource = Pick; + +// Renders configured cookies into one Cookie header, joined with "; ". +export function formatCookieHeader(cookies: Record | undefined): string | undefined { + const pairs = Object.entries(cookies ?? {}).map(([name, value]) => `${name}=${value}`); + return pairs.length ? pairs.join("; ") : undefined; +} + +// Extra tenant headers from corp config. A rendered Cookie header replaces a +// same-named entry, while Authorization is always left to the caller so the +// session bearer token can never be silently replaced by config. +export function resolveSealCustomHeaders(seal: SealCustomHeaderSource | undefined): Record { + const headers: Record = { ...(seal?.headers ?? {}) }; + const cookieHeader = formatCookieHeader(seal?.cookies); + if (cookieHeader) headers.Cookie = cookieHeader; + return headers; +}