Multiplayer agent harness for work.
Broker: fixed non-secret headers on brokered credentials (#2432)
Joshua Francebbf170aa6872
diff --git a/docs/deployment-broker-credentials.md b/docs/deployment-broker-credentials.mdindex c1ec1d162..5b8f0ba6b 100644--- a/docs/deployment-broker-credentials.md+++ b/docs/deployment-broker-credentials.md@@ -26,16 +26,16 @@ can see them in Settings but can't edit, delete or replace them.]```-| Field | Required | Meaning |-| --------------------- | -------- | -------------------------------------------------------------------------------------------------------------------------------- |-| `slug` | yes | Lowercase kebab-case name agents use. Must be unique. |-| `host` | yes | Bare hostname the broker pins requests to (subdomains match, as for stored credentials). |-| `secretEnv` | yes | Name of the env var holding the secret. It must be set and non-empty. |-| `displayName` | no | Label shown in Settings and to agents. Defaults to the slug. |-| `injection` | no | `header` and `scheme` for the secret. Defaults to `Authorization: Bearer <secret>`; set `scheme` to `""` to send the raw secret. |-| `allowedMethods` | no | Allowed HTTP methods. Defaults to `GET`. |-| `allowedPathPrefixes` | no | Allowed path prefixes. Defaults to any path. |-| `maxRequestsPerDay` | no | Cap on calls let through per UTC day, shared by every core process. Calls over the cap get `429 daily_cap_reached`. |+| Field | Required | Meaning |+| --------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |+| `slug` | yes | Lowercase kebab-case name agents use. Must be unique. |+| `host` | yes | Bare hostname the broker pins requests to (subdomains match, as for stored credentials). |+| `secretEnv` | yes | Name of the env var holding the secret. It must be set and non-empty. |+| `displayName` | no | Label shown in Settings and to agents. Defaults to the slug. |+| `injection` | no | `header` and `scheme` for the secret. Defaults to `Authorization: Bearer <secret>`; set `scheme` to `""` to send the raw secret. `headers` adds fixed, non-secret headers the API needs on every call, such as `{"x-api-version": "2025-11-01"}`; callers cannot override them, and they cannot replace the secret's header, `content-type`, or transport headers. |+| `allowedMethods` | no | Allowed HTTP methods. Defaults to `GET`. |+| `allowedPathPrefixes` | no | Allowed path prefixes. Defaults to any path. |+| `maxRequestsPerDay` | no | Cap on calls let through per UTC day, shared by every core process. Calls over the cap get `429 daily_cap_reached`. |Never put a secret in `BROKER_CREDENTIALS` itself; a JSON syntax error can quote part of the value.Unknown fields, a missing secret, a duplicate slug or any invalid value stop the core at startup with andiff --git a/plugins/admin/test/default-view.test.ts b/plugins/admin/test/default-view.test.tsindex 9d7da5217..4c182e78a 100644--- a/plugins/admin/test/default-view.test.ts+++ b/plugins/admin/test/default-view.test.ts@@ -379,6 +379,22 @@ test("governance credential editor previews effective capability and uses an in-const state = new CredentialState();state.begin({ slug: "test", name: "Test", host: "example.com", updatedAt: 42 });assert.equal(state.collect().expectedUpdatedAt, 42);+ const fixed = new CredentialState();+ fixed.begin({+ slug: "versioned",+ name: "Versioned",+ host: "api.example.com",+ updatedAt: 7,+ injection: { header: "x-api-key", scheme: "Token", actor: true, headers: { "x-api-version": "2025-11-01" } },+ });+ fixed.draft.secret = "rotated";+ fixed.draft.host = "api2.example.com";+ assert.deepEqual(fixed.collect().injection, {+ actor: true,+ headers: { "x-api-version": "2025-11-01" },+ header: "x-api-key",+ scheme: "Token",+ });assert.match(html, /it remains an edit and cannot recreate the credential/);assert.match(html, /latest state could not be loaded\. Refresh the page before deleting/);assert.match(html, /latest revision could not be loaded\. Your draft is preserved/);diff --git a/plugins/admin/ui/settings-credentials.ts b/plugins/admin/ui/settings-credentials.tsindex d5348c46f..affa150ac 100644--- a/plugins/admin/ui/settings-credentials.ts+++ b/plugins/admin/ui/settings-credentials.ts@@ -141,6 +141,7 @@ export class CredentialState {const d = this.draft;const env = d.delivery === "env";const actor = this.original?.injection?.actor;+ const fixedHeaders = this.original?.injection?.headers;return {slug: d.slug.trim(),name: d.name.trim(),@@ -150,6 +151,7 @@ export class CredentialState {...(d.secret ? { secret: d.secret } : {}),injection: {...(typeof actor === "boolean" ? { actor } : {}),+ ...(fixedHeaders ? { headers: fixedHeaders } : {}),...(d.header.trim() ? { header: d.header.trim() } : {}),...(d.scheme ? { scheme: d.scheme } : {}),},diff --git a/src/api/credential-broker.ts b/src/api/credential-broker.tsindex 7663d047e..43a92715a 100644--- a/src/api/credential-broker.ts+++ b/src/api/credential-broker.ts@@ -5,6 +5,7 @@ import type { ScopeId } from "../types.ts";import type { CredentialUsageSink } from "../admin/credential-usage-sink.ts";import {credentialInjectionError,+ credentialRequestHeaders,type DecryptedServiceCredential,type ServiceCredentialReader,} from "../credentials/keychain.ts";@@ -81,11 +82,15 @@ export function brokerPathAllowed(pathname: string, prefixes?: string[]): boolea);}-export function brokerCredentialAuthHeader(rec: DecryptedServiceCredential): [string, string] {- const injHeader = rec.injection?.header || "Authorization";- const rawScheme = rec.injection?.scheme ?? "Bearer ";- const injScheme = rawScheme && !/\s$/.test(rawScheme) ? `${rawScheme} ` : rawScheme;- return [injHeader, `${injScheme}${rec.secret}`];+export function brokerRequestHeaders(+ rec: DecryptedServiceCredential,+ caller: Record<string, string>,+): Record<string, string> {+ const injected = credentialRequestHeaders(rec);+ const owned = new Set(Object.keys(injected).map((name) => name.toLowerCase()));+ const headers: Record<string, string> = {};+ for (const [name, value] of Object.entries(caller)) if (!owned.has(name.toLowerCase())) headers[name] = value;+ return { ...headers, ...injected };}type CredentialGrant =@@ -217,14 +222,13 @@ export async function brokerCredentialCall(opts: {);}- const headers: Record<string, string> = {};+ const caller: Record<string, string> = {};if (body.headers && typeof body.headers === "object") {for (const [k, v] of Object.entries(body.headers as Record<string, unknown>)) {- if (typeof v === "string" && ALLOWED_CALLER_HEADERS.has(k.toLowerCase())) headers[k] = v;+ if (typeof v === "string" && ALLOWED_CALLER_HEADERS.has(k.toLowerCase())) caller[k] = v;}}- const [injHeader, injValue] = brokerCredentialAuthHeader(rec);- headers[injHeader] = injValue;+ const headers = brokerRequestHeaders(rec, caller);if (rec.injection?.actor) headers["x-qm-actor"] = claims.actorId;let resp: BrokerFetchResponse;diff --git a/src/api/git-http-broker.ts b/src/api/git-http-broker.tsindex b13ab2a43..f58c03d6d 100644--- a/src/api/git-http-broker.ts+++ b/src/api/git-http-broker.ts@@ -3,7 +3,7 @@ import { Readable } from "node:stream";import type { CapabilityClaims } from "../auth/capability-token.ts";import { scopeId as makeScopeId } from "../types.ts";import { type DecryptedServiceCredential, isValidCredentialSlug, isComposioHost } from "../credentials/keychain.ts";-import { brokerCredentialAuthHeader, brokerPathAllowed, grantedCredential } from "./credential-broker.ts";+import { brokerPathAllowed, brokerRequestHeaders, grantedCredential } from "./credential-broker.ts";import { pipeToResponse, sendJson } from "./http.ts";import type { BaseCtx } from "./routes/route.ts";import { proxyHeaders } from "../util/http-proxy.ts";@@ -154,9 +154,7 @@ export async function brokerGitHttp(ctx: BaseCtx): Promise<void> {);}- const headers = callerHeaders(ctx);- const [authHeader, authValue] = brokerCredentialAuthHeader(rec);- headers[authHeader] = authValue;+ const headers = brokerRequestHeaders(rec, callerHeaders(ctx));let upstreamResp: GitHttpFetchResponse;try {diff --git a/src/api/routes/admin-resources.ts b/src/api/routes/admin-resources.tsindex 345fb29f7..4fb3a0a79 100644--- a/src/api/routes/admin-resources.ts+++ b/src/api/routes/admin-resources.ts@@ -1181,9 +1181,7 @@ export const ADMIN_RESOURCES: readonly AdminResource[] = [...(delivery === "env" ? { envKey } : {}),host: delivery === "env" ? "" : host,...(typeof b.secret === "string" && b.secret ? { secret: b.secret } : {}),- ...(delivery === "broker" &&- effectiveInjection &&- (effectiveInjection.header || effectiveInjection.scheme || effectiveInjection.actor !== undefined)+ ...(delivery === "broker" && effectiveInjection && Object.keys(effectiveInjection).length? { injection: effectiveInjection }: {}),...(delivery === "broker" ? brokerMethods : {}),diff --git a/src/credentials/keychain.ts b/src/credentials/keychain.tsindex e5adb1d9c..740685cec 100644--- a/src/credentials/keychain.ts+++ b/src/credentials/keychain.ts@@ -1,6 +1,8 @@import { createMemoryAdvisoryLock, type AdvisoryLock } from "../persistence/advisory-lock.ts";import { orgId as configOrgId } from "../config.ts";import { randomBytes } from "node:crypto";+import { validateHeaderName, validateHeaderValue } from "node:http";+import { HOP_BY_HOP } from "../util/http-proxy.ts";import { scopeId as toScopeId, parseScopeId, type Destination, type ScopeId } from "../types.ts";import type { DurableMap } from "../persistence/durable-map.ts";import { encryptSecret, decryptSecret, type SecretKey } from "../connectors/connector-client-store.ts";@@ -29,6 +31,56 @@ export interface CredentialInjection {header?: string;scheme?: string;actor?: boolean;+ headers?: Record<string, string>;+}++const DEFAULT_AUTH_HEADER = "Authorization";+const RESERVED_FIXED_HEADERS = new Set([+ ...HOP_BY_HOP,+ "authorization",+ "content-encoding",+ "content-length",+ "content-type",+ "cookie",+ "expect",+ "host",+ "x-qm-actor",+]);++const headerError = (validate: () => void): boolean => {+ try {+ validate();+ return false;+ } catch {+ return true;+ }+};++function fixedHeadersError(headers: unknown, authHeader: string): string | undefined {+ if (headers === undefined) return undefined;+ if (!headers || typeof headers !== "object" || Array.isArray(headers)) return "injection.headers must be an object";+ const seen = new Set<string>();+ for (const [name, value] of Object.entries(headers)) {+ const lower = name.toLowerCase();+ if (headerError(() => validateHeaderName(name)))+ return `injection.headers: "${name}" is not a valid HTTP header name`;+ if (RESERVED_FIXED_HEADERS.has(lower) || lower === authHeader) return `injection.headers cannot set ${lower}`;+ if (seen.has(lower)) return `injection.headers lists ${lower} more than once`;+ seen.add(lower);+ if (typeof value !== "string" || !value || headerError(() => validateHeaderValue(name, value)))+ return `injection.headers.${name} must be a non-empty valid HTTP header value`;+ }+ return undefined;+}++export function credentialRequestHeaders(rec: {+ injection?: CredentialInjection;+ secret: string;+}): Record<string, string> {+ const header = rec.injection?.header || DEFAULT_AUTH_HEADER;+ const rawScheme = rec.injection?.scheme ?? "Bearer ";+ const scheme = rawScheme && !/\s$/.test(rawScheme) ? `${rawScheme} ` : rawScheme;+ return { ...rec.injection?.headers, [header]: `${scheme}${rec.secret}` };}export function credentialInjectionError(value: unknown): string | undefined {@@ -38,13 +90,13 @@ export function credentialInjectionError(value: unknown): string | undefined {if (injection.actor !== undefined && typeof injection.actor !== "boolean") return "injection.actor must be boolean";if (injection.header !== undefined &&- (typeof injection.header !== "string" || !/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/.test(injection.header))+ (typeof injection.header !== "string" || headerError(() => validateHeaderName(injection.header!))))return "authentication header must be a valid HTTP header name";if (injection.header?.toLowerCase() === "x-qm-actor") return "x-qm-actor is reserved for broker actor attestation";if (injection.scheme !== undefined && (typeof injection.scheme !== "string" || /[\r\n]/.test(injection.scheme)))return "authentication value prefix must be a single line";- return undefined;+ return fixedHeadersError(injection.headers, (injection.header || DEFAULT_AUTH_HEADER).toLowerCase());}interface BrokerDelivery {diff --git a/src/decisions/providers.ts b/src/decisions/providers.tsindex 7282ceec7..d1d56fd67 100644--- a/src/decisions/providers.ts+++ b/src/decisions/providers.ts@@ -147,7 +147,7 @@ const PROTOCOLS: Record<export function createDecisionBackend(opts: {providers: (ids: string[]) => readonly DecisionProvider[] | Promise<readonly DecisionProvider[]>;gateway?: { url: string; apiKey: string; apiKeyHeader?: string };- credential: (slug: string) => Promise<{ host: string; enabled: boolean; header: [string, string] } | null>;+ credential: (slug: string) => Promise<{ host: string; enabled: boolean; headers: Record<string, string> } | null>;fetch?: typeof fetch;}): DecisionBackend {const fetchImpl = opts.fetch ?? fetch;@@ -168,7 +168,7 @@ export function createDecisionBackend(opts: {throw new Error(`decision provider ${provider.id}: credential ${provider.credential} is for ${rec.host}, not ${url.host}`,);- return { base: provider.baseUrl, auth: { [rec.header[0]]: rec.header[1] } };+ return { base: provider.baseUrl, auth: rec.headers };};return {async choose({ questions, state, model, signal }) {diff --git a/src/skills/pack-fetcher.ts b/src/skills/pack-fetcher.tsindex 482f8e58a..20133c3f7 100644--- a/src/skills/pack-fetcher.ts+++ b/src/skills/pack-fetcher.ts@@ -5,6 +5,7 @@ import { tmpdir } from "node:os";import { join, relative, sep } from "node:path";import { lookup as dnsLookup } from "node:dns/promises";import { isIP } from "node:net";+import { credentialRequestHeaders, type CredentialInjection } from "../credentials/keychain.ts";import { errMessage } from "../util/errors.ts";import { isPrivateNetworkIp } from "../util/network.ts";import { isProbablyBinary } from "./seed.ts";@@ -32,7 +33,7 @@ export interface PackTokenSources {secret: string;host: string;enabled: boolean;- injection?: { header?: string; scheme?: string };+ injection?: CredentialInjection;allowedMethods?: string[];allowedPathPrefixes?: string[];}@@ -42,8 +43,7 @@ export interface PackTokenSources {}export interface GitAuth {- header: string;- value: string;+ headers: Record<string, string>;secret: string;}@@ -129,14 +129,12 @@ export async function resolvePackAuth() {throw new Error(`skill pack credential is not authorized for ${repo.pathname}`);}- const header = credential.injection?.header?.trim() || "Authorization";- const scheme = credential.injection?.scheme ?? "Bearer ";- return { header, value: `${scheme}${credential.secret}`, secret: credential.secret };+ return { headers: credentialRequestHeaders(credential), secret: credential.secret };}const host = connectorHostFor(pack.url);if (host) {const token = await sources.connectorToken(host, pack.createdBy);- if (token) return { header: "Authorization", value: `Bearer ${token}`, secret: token };+ if (token) return { headers: { Authorization: `Bearer ${token}` }, secret: token };}return undefined;}@@ -147,7 +145,9 @@ const BRANCH_RE = /^[A-Za-z0-9][A-Za-z0-9._/-]{0,199}$/;const execFileP = promisify(execFile);function scrub(s: string, auth: GitAuth | undefined): string {- return auth ? s.split(auth.secret).join("***").split(auth.value).join("***") : s;+ if (!auth) return s;+ const secrets = [auth.secret, ...Object.values(auth.headers).filter((value) => value.includes(auth.secret))];+ return secrets.reduce((out, value) => out.split(value).join("***"), s);}export function createGitFetcher(opts: GitFetcherOptions = {}): SkillPackFetcher {@@ -171,7 +171,9 @@ export function createGitFetcher(opts: GitFetcherOptions = {}): SkillPackFetcherenv.GIT_ALLOW_PROTOCOL = allowLocalRepos ? "https:file" : "https";const entries = [...config,- ...(auth ? [["http.extraHeader", `${auth.header}: ${auth.value}`] as [string, string]] : []),+ ...Object.entries(auth?.headers ?? {}).map(+ ([name, value]) => ["http.extraHeader", `${name}: ${value}`] as [string, string],+ ),];if (entries.length) {env.GIT_CONFIG_COUNT = String(entries.length);diff --git a/src/util/http-proxy.ts b/src/util/http-proxy.tsindex 9d469ea9b..65a12a9d6 100644--- a/src/util/http-proxy.ts+++ b/src/util/http-proxy.ts@@ -1,4 +1,4 @@-const HOP_BY_HOP = new Set([+export const HOP_BY_HOP: ReadonlySet<string> = new Set(["connection","keep-alive","proxy-authenticate",diff --git a/src/wiring.ts b/src/wiring.tsindex 49f7ff458..90ef4047e 100644--- a/src/wiring.ts+++ b/src/wiring.ts@@ -2,7 +2,6 @@ import type { MemoryEmbedder } from "./model/embeddings.ts";import { nonDeploymentCredential, withDeploymentCredentials } from "./credentials/deployment-credentials.ts";import { resolveEmbeddingModel } from "./model/pi-models.ts";import { createPostgresTeamStore, type TeamStore } from "./teams/teams.ts";-import { brokerCredentialAuthHeader } from "./api/credential-broker.ts";import type { DecisionBackend } from "./decisions/decisions.ts";import { createDecisionHooks, routeTurnRuntime, turnStartState } from "./decisions/hooks.ts";import { createDecisionBackend } from "./decisions/providers.ts";@@ -274,6 +273,7 @@ import {createLayeredSecretSource,} from "./credentials/secret-source.ts";import {+ credentialRequestHeaders,createKeychain,type ConnectorTokenStore,type OAuthToken,@@ -1525,7 +1525,7 @@ export function buildApp(const rec = keychain? nonDeploymentCredential(await serviceCreds.getServiceCredentialSecret(scopeId("org", config.orgId), slug)): null;- return rec ? { host: rec.host, enabled: rec.enabled, header: brokerCredentialAuthHeader(rec) } : null;+ return rec ? { host: rec.host, enabled: rec.enabled, headers: credentialRequestHeaders(rec) } : null;},}),auditLog,diff --git a/test/decision-rules.test.ts b/test/decision-rules.test.tsindex 13c1e61ee..c95262d36 100644--- a/test/decision-rules.test.ts+++ b/test/decision-rules.test.ts@@ -121,7 +121,7 @@ test("runHook: highest-probability option decides; observe rules never act; errocredential: async (slug: string) => ({host: slug === "dec" ? "dec.example" : "ts.example",enabled: true,- header: ["Authorization", `Bearer ${slug}-key`] as [string, string],+ headers: { Authorization: `Bearer ${slug}-key` },}),fetch: async () =>new Response(@@ -240,7 +240,7 @@ test("decisions protocol calls the Decisions API and reads its probability arraycredential: async (slug: string) => ({host: slug === "dec" ? "dec.example" : "ts.example",enabled: true,- header: ["Authorization", `Bearer ${slug}-key`] as [string, string],+ headers: { Authorization: `Bearer ${slug}-key` },}),fetch: fetchImpl,});@@ -267,7 +267,7 @@ test("systemone protocol posts to /systemone", async () => {credential: async (slug: string) => ({host: slug === "dec" ? "dec.example" : "ts.example",enabled: true,- header: ["Authorization", `Bearer ${slug}-key`] as [string, string],+ headers: { Authorization: `Bearer ${slug}-key` },}),fetch: fetchImpl,});@@ -279,7 +279,7 @@ test("a missing, disabled or mismatched credential is an error, so the rule fallconst backend = (rec: { host: string; enabled: boolean } | null) =>createDecisionBackend({providers: () => [{ id: "oa", protocol: "decisions", baseUrl: "https://dec.example/v1", credential: "dec" }],- credential: async () => rec && { ...rec, header: ["Authorization", "Bearer x"] as [string, string] },+ credential: async () => rec && { ...rec, headers: { Authorization: "Bearer x" } },});await assert.rejects(ask(backend(null), { provider: "oa", model: "m" }), /missing or disabled/);await assert.rejects(diff --git a/test/deployment-broker-credentials.test.ts b/test/deployment-broker-credentials.test.tsindex a2f0b665f..18faecd94 100644--- a/test/deployment-broker-credentials.test.ts+++ b/test/deployment-broker-credentials.test.ts@@ -82,6 +82,27 @@ test("BROKER_CREDENTIALS fails fast on any malformed entry without echoing secre[[{ ...entry, maxRequestsPerDay: 0 }], /maxRequestsPerDay/],[[{ ...entry, maxRequestsPerDay: 1.5 }], /maxRequestsPerDay/],[[{ ...entry, injection: { header: "x-qm-actor" } }], /reserved/],+ [+ [{ ...entry, injection: { ...entry.injection, headers: ["x-api-version"] } }],+ /injection.headers must be an object/,+ ],+ [[{ ...entry, injection: { ...entry.injection, headers: { "x api": "1" } } }], /not a valid HTTP header name/],+ [[{ ...entry, injection: { ...entry.injection, headers: { Host: "evil.example" } } }], /cannot set host/],+ [+ [{ ...entry, injection: { ...entry.injection, headers: { "Content-Type": "text/plain" } } }],+ /cannot set content-type/,+ ],+ [[{ ...entry, injection: { ...entry.injection, headers: { Expect: "100-continue" } } }], /cannot set expect/],+ [[{ ...entry, injection: { ...entry.injection, headers: { Upgrade: "websocket" } } }], /cannot set upgrade/],+ [[{ ...entry, injection: { ...entry.injection, headers: { "x-v": "a\u0001b" } } }], /valid HTTP header value/],+ [[{ ...entry, injection: { ...entry.injection, headers: { "x-api-key": "1" } } }], /cannot set x-api-key/],+ [[{ ...entry, injection: { headers: { Authorization: "Bearer other" } } }], /cannot set authorization/],+ [[{ ...entry, injection: { ...entry.injection, headers: { "x-v": "1", "X-V": "2" } } }], /more than once/],+ [+ [{ ...entry, injection: { ...entry.injection, headers: { "x-v": "1\r\nx-evil: 1" } } }],+ /valid HTTP header value/,+ ],+ [[{ ...entry, injection: { ...entry.injection, headers: { "x-v": "" } } }], /valid HTTP header value/],[[{ ...entry, displayName: "" }], /displayName/],];for (const [list, pattern, extra] of cases) {@@ -166,12 +187,12 @@ test("deployment credentials win lookups in their org and reserve their slugs agassert.deepEqual(stored.writes, ["set:stored"]);});-function start(fetchImpl: BrokerFetch, admin = false) {+function start(fetchImpl: BrokerFetch, admin = false, brokerCredentials = deploymentCreds()) {const built = buildApp(testConfig({dataDir: mkdtempSync(join(tmpdir(), "deploy-broker-")),signingSecret: SECRET,- brokerCredentials: deploymentCreds(),+ brokerCredentials,}),);const deps = {@@ -258,6 +279,7 @@ test("the broker serves a deployment credential with its pins, injection, usageassert.equal(capped.body.error, "daily_cap_reached");assert.equal(calls.length, 2);assert.equal(calls[0]!.headers["X-API-KEY"], KEY);+ assert.equal(calls[0]!.headers["x-api-version"], undefined);const usage = await srv.built.credentialUsage.list({ slug: "search" });assert.equal(usage.filter((u) => u.status === "ok").length, 2);assert.equal(usage.filter((u) => u.status === "denied").length, 4);@@ -324,3 +346,47 @@ test("a deployment credential cannot back a decision provider", async () => {const listing = (await decisionsResource.get!(ctx({}).deps, ORG)) as { credentials: string[] };assert.deepEqual(listing.credentials, ["stored"]);});++test("the broker adds a deployment credential's fixed headers, which callers cannot override", async () => {+ const pinned = {+ ...entry,+ slug: "versioned",+ injection: { ...entry.injection, headers: { "x-api-version": "2025-11-01" } },+ };+ const calls: Array<Record<string, string>> = [];+ const srv = start(+ async (_url, init) => {+ calls.push(init.headers);+ return { status: 200, contentType: "application/json", text: async () => "{}" };+ },+ false,+ deploymentBrokerCredentialsFromEnv(envWith([pinned])),+ );+ try {+ const token = await mintCapabilityToken(+ {+ actorId: "U1",+ scopeId: "personal:U1",+ aud: CREDENTIAL_BROKER_AUD,+ credentials: ["versioned"],+ exp: Date.now() + CAPABILITY_TTL_MS,+ },+ SECRET,+ );+ const res = await fetch(`${srv.base}/v1/credentials/broker`, {+ method: "POST",+ headers: { "content-type": "application/json", "x-agent-capability": token },+ body: JSON.stringify({+ credential: "versioned",+ method: "POST",+ url: "https://api.search.example/search",+ headers: { "X-Api-Version": "1999-01-01", "content-type": "application/json", "x-api-key": "caller" },+ body: "{}",+ }),+ });+ assert.equal(res.status, 200);+ assert.deepEqual(calls[0], { "content-type": "application/json", "x-api-version": "2025-11-01", "X-API-KEY": KEY });+ } finally {+ await srv.close();+ }+});diff --git a/test/git-http-broker.test.ts b/test/git-http-broker.test.tsindex 87f93f197..99f5ea96f 100644--- a/test/git-http-broker.test.ts+++ b/test/git-http-broker.test.ts@@ -112,6 +112,38 @@ test("git HTTP broker streams a smart-HTTP request through the pinned service cr});});+test("git HTTP broker sends a credential's fixed headers over a caller's case variant", async () => {+ let seen: Record<string, string> | undefined;+ const deps: ServerDeps = {+ control: {} as ServerDeps["control"],+ serviceCreds: {+ getServiceCredentialSecret: async () => ({+ slug: "gitlab",+ name: "GitLab git",+ secret: "dXNlcjp0b2tlbg==",+ host: "gitlab.example",+ injection: { scheme: "Basic ", headers: { "Git-Protocol": "version=1", "x-tenant": "acme" } },+ allowedMethods: ["GET", "POST"],+ allowedPathPrefixes: ["/acme/repo.git"],+ enabled: true,+ }),+ } as unknown as ServerDeps["serviceCreds"],+ gitHttpFetch: async (_url, init) => {+ seen = init.headers;+ return { status: 200, headers: {}, body: Readable.from(["0000"]) };+ },+ };+ const c = ctx("/v1/credentials/git/gitlab/acme/repo.git/git-receive-pack", "POST", deps, "PACK");+ await brokerGitHttp(c);+ await text(c.res);+ assert.deepEqual(seen, {+ "content-type": "application/x-git-receive-pack-request",+ "Git-Protocol": "version=1",+ "x-tenant": "acme",+ Authorization: "Basic dXNlcjp0b2tlbg==",+ });+});+test("git HTTP broker refuses an env-delivery record like a missing credential", async () => {let fetched = false;const deps: ServerDeps = {diff --git a/test/pack-fetcher.test.ts b/test/pack-fetcher.test.tsindex 0312852a8..ec63af595 100644--- a/test/pack-fetcher.test.ts+++ b/test/pack-fetcher.test.ts@@ -149,7 +149,23 @@ test("resolvePackAuth: an explicit host-bound slug honors the configured injecti};assert.deepEqual(await resolvePackAuth(sources, { url: "https://github.com/o/r", authCredentialSlug: "dep", createdBy: "u1" }),- { header: "Authorization", value: "Bearer svc:dep", secret: "svc:dep" },+ { headers: { Authorization: "Bearer svc:dep" }, secret: "svc:dep" },+ );+});++test("resolvePackAuth: a credential's fixed headers ride along with its auth header", async () => {+ const sources = {+ serviceCredential: async (s: string) => ({+ secret: "svc:" + s,+ host: "github.com",+ enabled: true,+ injection: { header: "X-Token", scheme: "", headers: { "x-api-version": "2" } },+ }),+ connectorToken: async () => "connector",+ };+ assert.deepEqual(+ await resolvePackAuth(sources, { url: "https://github.com/o/r", authCredentialSlug: "dep", createdBy: "u1" }),+ { headers: { "x-api-version": "2", "X-Token": "svc:dep" }, secret: "svc:dep" },);});@@ -209,8 +225,7 @@ test("resolvePackAuth: a github repo with no slug reuses the registrant's connec},};assert.deepEqual(await resolvePackAuth(sources, { url: "https://github.com/o/r.git", createdBy: "alice" }), {- header: "Authorization",- value: "Bearer ghtok",+ headers: { Authorization: "Bearer ghtok" },secret: "ghtok",});assert.deepEqual(calls, [["api.github.com", "alice"]], "looks up the registrant's api.github.com connector token");diff --git a/test/service-credential-route.test.ts b/test/service-credential-route.test.tsindex 061e75553..c765ad427 100644--- a/test/service-credential-route.test.ts+++ b/test/service-credential-route.test.ts@@ -101,7 +101,7 @@ const getCfg = async (base: string) =>enabled: boolean;grantees: string[];updatedAt: number;- injection?: { header?: string; scheme?: string; actor?: boolean };+ injection?: { header?: string; scheme?: string; actor?: boolean; headers?: Record<string, string> };allowedMethods?: string[];allowedPathPrefixes?: string[];}>;@@ -339,6 +339,20 @@ test("partial credential updates preserve capability lists while explicit empty}});+test("a credential whose injection only adds fixed headers keeps them", async () => {+ const srv = start();+ try {+ const injection = { headers: { "x-api-version": "2025-11-01" } };+ assert.equal(+ (await putCred(srv.base, { slug: "k", name: "K", secret: "s", host: "h.example", injection })).status,+ 200,+ );+ assert.deepEqual((await getCfg(srv.base)).serviceCredentials[0]!.injection, injection);+ } finally {+ await srv.close();+ }+});+test("admin credential edits reject a stale loaded revision", async () => {const srv = start();try {