Add per-enterprise custom HTTP headers and cookies
Some Seal tenants sit behind a gateway that only forwards requests carrying its own session cookie. Corp configs can now set seal.headers/seal.cookies, which the client merges into every request; cookies are rendered into one Cookie header and the session bearer token still wins over any configured Authorization. corps add-seal accepts both fields and applies them when verifying the tenant, so a gated enterprise can be registered in one step.
This commit is contained in:
1 parent
fc06434813
commit
bb8b5edec6
6 files changed
+203
-6
No files matched your search
@@ -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", () => {
|
||||
|
||||
@@ -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({
|
||||
|
||||
@@ -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<KyInstance> {
|
||||
const session = await getSealSessionForCorp(corp);
|
||||
@@ -9,6 +10,7 @@ export async function createSealClient(corp: CorpConfig): Promise<KyInstance> {
|
||||
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<KyInstance> {
|
||||
export async function createSealClientForToken(corp: CorpConfig, token: string): Promise<KyInstance> {
|
||||
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<string, string> = {}
|
||||
): KyInstance {
|
||||
return ky.create({
|
||||
prefix: sealUrl.replace(/\/+$/, ""),
|
||||
timeout: 30000,
|
||||
headers: {
|
||||
...customHeaders,
|
||||
Authorization: `Bearer ${token}`
|
||||
},
|
||||
hooks: {
|
||||
|
||||
@@ -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");
|
||||
});
|
||||
});
|
||||
@@ -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<CorpConfig["seal"], "headers" | "cookies">;
|
||||
|
||||
// Renders configured cookies into one Cookie header, joined with "; ".
|
||||
export function formatCookieHeader(cookies: Record<string, string> | 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<string, string> {
|
||||
const headers: Record<string, string> = { ...(seal?.headers ?? {}) };
|
||||
const cookieHeader = formatCookieHeader(seal?.cookies);
|
||||
if (cookieHeader) headers.Cookie = cookieHeader;
|
||||
return headers;
|
||||
}
|
||||
Reference in new issue
Block a user