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
@@ -10,12 +10,14 @@ import {
|
|||||||
} from "../../core/auth/hose.js";
|
} from "../../core/auth/hose.js";
|
||||||
import { clearCorpTokenCache } from "../../core/auth/token-store.js";
|
import { clearCorpTokenCache } from "../../core/auth/token-store.js";
|
||||||
import { createSealClientForUrl } from "../../core/http/factory.js";
|
import { createSealClientForUrl } from "../../core/http/factory.js";
|
||||||
|
import { resolveSealCustomHeaders } from "../../core/http/request-headers.js";
|
||||||
import {
|
import {
|
||||||
loadCorpConfigs,
|
loadCorpConfigs,
|
||||||
loadGlobalConfig,
|
loadGlobalConfig,
|
||||||
resolveWritableEnterprisesDir,
|
resolveWritableEnterprisesDir,
|
||||||
saveGlobalConfig
|
saveGlobalConfig
|
||||||
} from "../../core/config/loader.js";
|
} from "../../core/config/loader.js";
|
||||||
|
import { SealCookieMapSchema, SealHeaderMapSchema } from "../../core/config/types.js";
|
||||||
import type { CorpConfig } from "../../core/config/types.js";
|
import type { CorpConfig } from "../../core/config/types.js";
|
||||||
import { getMe } from "../../domains/seal/api.js";
|
import { getMe } from "../../domains/seal/api.js";
|
||||||
import { resolveLiveSealEnterpriseConfig } from "../../domains/seal/source.js";
|
import { resolveLiveSealEnterpriseConfig } from "../../domains/seal/source.js";
|
||||||
@@ -374,8 +376,20 @@ async function addSealCorp(input: Record<string, unknown>) {
|
|||||||
|
|
||||||
const expiresIn = optionalNumber(input, "expiresIn") ?? 30 * 24 * 60 * 60;
|
const expiresIn = optionalNumber(input, "expiresIn") ?? 30 * 24 * 60 * 60;
|
||||||
const verify = input.force === true || input.verify === false ? false : true;
|
const verify = input.force === true || input.verify === false ? false : true;
|
||||||
const remote = verify ? await resolveSealWhoami(sealUrl, token) : undefined;
|
const custom = sealCustomHeadersFromInput(input);
|
||||||
writeSealCorpConfig(input, { token, sealUrl, expiresIn, verify, remote });
|
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<string, unknown>) {
|
||||||
|
return {
|
||||||
|
headers: SealHeaderMapSchema.parse(input.headers),
|
||||||
|
cookies: SealCookieMapSchema.parse(input.cookies)
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
async function addLinkCorp(link: string, name: string | undefined, overwrite: boolean) {
|
async function addLinkCorp(link: string, name: string | undefined, overwrite: boolean) {
|
||||||
@@ -419,9 +433,11 @@ function writeSealCorpConfig(
|
|||||||
expiresIn: number;
|
expiresIn: number;
|
||||||
verify: boolean;
|
verify: boolean;
|
||||||
remote?: RemoteSealIdentity;
|
remote?: RemoteSealIdentity;
|
||||||
|
custom?: { headers?: Record<string, string>; cookies?: Record<string, string> };
|
||||||
}
|
}
|
||||||
) {
|
) {
|
||||||
const { token, sealUrl, expiresIn, verify, remote } = auth;
|
const { token, sealUrl, expiresIn, verify, remote } = auth;
|
||||||
|
const custom = auth.custom ?? sealCustomHeadersFromInput(input);
|
||||||
const remoteUser = remote?.user;
|
const remoteUser = remote?.user;
|
||||||
const remoteTenant = remote?.tenant;
|
const remoteTenant = remote?.tenant;
|
||||||
const tenantSlug = optionalString(input, "tenantSlug") ?? stringValue(remoteTenant?.tenantSlug);
|
const tenantSlug = optionalString(input, "tenantSlug") ?? stringValue(remoteTenant?.tenantSlug);
|
||||||
@@ -447,6 +463,8 @@ function writeSealCorpConfig(
|
|||||||
seal: {
|
seal: {
|
||||||
url: sealUrl,
|
url: sealUrl,
|
||||||
tenantSlug,
|
tenantSlug,
|
||||||
|
headers: custom.headers,
|
||||||
|
cookies: custom.cookies,
|
||||||
endpoints: {
|
endpoints: {
|
||||||
approvalStylePreferences: "api/v1/agent/ai-approval/config"
|
approvalStylePreferences: "api/v1/agent/ai-approval/config"
|
||||||
}
|
}
|
||||||
@@ -522,8 +540,9 @@ async function resolveHoseCorporation(domain: string, appKey: string, appSecurit
|
|||||||
: undefined;
|
: undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
async function resolveSealWhoami(sealUrl: string, token: string) {
|
async function resolveSealWhoami(sealUrl: string, token: string, customHeaders: Record<string, string> = {}) {
|
||||||
const json = await getJson(`${sealUrl}/api/v1/auth/me`, {
|
const json = await getJson(`${sealUrl}/api/v1/auth/me`, {
|
||||||
|
...customHeaders,
|
||||||
authorization: `Bearer ${token}`
|
authorization: `Bearer ${token}`
|
||||||
});
|
});
|
||||||
const data = objectValue(json.data);
|
const data = objectValue(json.data);
|
||||||
|
|||||||
@@ -1,5 +1,10 @@
|
|||||||
import { describe, expect, test } from "bun:test";
|
import { describe, expect, test } from "bun:test";
|
||||||
import { CorpConfigSchema, GlobalConfigSchema } from "./types.js";
|
import {
|
||||||
|
CorpConfigSchema,
|
||||||
|
GlobalConfigSchema,
|
||||||
|
SealCookieMapSchema,
|
||||||
|
SealHeaderMapSchema
|
||||||
|
} from "./types.js";
|
||||||
|
|
||||||
describe("CorpConfigSchema", () => {
|
describe("CorpConfigSchema", () => {
|
||||||
test("accepts Hose key/password aliases", () => {
|
test("accepts Hose key/password aliases", () => {
|
||||||
@@ -78,6 +83,59 @@ describe("CorpConfigSchema", () => {
|
|||||||
expect(config.source.staffId).toBe("seal");
|
expect(config.source.staffId).toBe("seal");
|
||||||
expect(config.source.tenantSlug).toBe("xiezihao");
|
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", () => {
|
describe("GlobalConfigSchema", () => {
|
||||||
|
|||||||
@@ -58,9 +58,38 @@ export const SealSourceSchema = z.discriminatedUnion("type", [
|
|||||||
NativeSealSourceSchema
|
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({
|
export const SealEndpointSchema = z.object({
|
||||||
url: z.string().url().optional(),
|
url: z.string().url().optional(),
|
||||||
tenantSlug: z.string().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({
|
endpoints: z.object({
|
||||||
approvalStylePreferences: z.string().default("api/v1/agent/ai-approval/config")
|
approvalStylePreferences: z.string().default("api/v1/agent/ai-approval/config")
|
||||||
}).default({
|
}).default({
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import ky, { HTTPError, KyInstance } from "ky";
|
import ky, { HTTPError, KyInstance } from "ky";
|
||||||
import { CorpConfig } from "../config/types.js";
|
import { CorpConfig } from "../config/types.js";
|
||||||
import { clearSealToken, getSealSessionForCorp } from "../auth/seal.js";
|
import { clearSealToken, getSealSessionForCorp } from "../auth/seal.js";
|
||||||
|
import { resolveSealCustomHeaders } from "./request-headers.js";
|
||||||
|
|
||||||
export async function createSealClient(corp: CorpConfig): Promise<KyInstance> {
|
export async function createSealClient(corp: CorpConfig): Promise<KyInstance> {
|
||||||
const session = await getSealSessionForCorp(corp);
|
const session = await getSealSessionForCorp(corp);
|
||||||
@@ -9,6 +10,7 @@ export async function createSealClient(corp: CorpConfig): Promise<KyInstance> {
|
|||||||
prefix: session.enterprise.sealUrl,
|
prefix: session.enterprise.sealUrl,
|
||||||
timeout: 30000,
|
timeout: 30000,
|
||||||
headers: {
|
headers: {
|
||||||
|
...resolveSealCustomHeaders(corp.seal),
|
||||||
Authorization: `Bearer ${session.token}`
|
Authorization: `Bearer ${session.token}`
|
||||||
},
|
},
|
||||||
hooks: {
|
hooks: {
|
||||||
@@ -32,14 +34,19 @@ export async function createSealClient(corp: CorpConfig): Promise<KyInstance> {
|
|||||||
export async function createSealClientForToken(corp: CorpConfig, token: string): Promise<KyInstance> {
|
export async function createSealClientForToken(corp: CorpConfig, token: string): Promise<KyInstance> {
|
||||||
const session = await getSealSessionForCorp(corp);
|
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({
|
return ky.create({
|
||||||
prefix: sealUrl.replace(/\/+$/, ""),
|
prefix: sealUrl.replace(/\/+$/, ""),
|
||||||
timeout: 30000,
|
timeout: 30000,
|
||||||
headers: {
|
headers: {
|
||||||
|
...customHeaders,
|
||||||
Authorization: `Bearer ${token}`
|
Authorization: `Bearer ${token}`
|
||||||
},
|
},
|
||||||
hooks: {
|
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