Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(azure): keyless (Entra/AAD) auth for the azure-openai embedding recipe (#2354)

Jonathan AW2c758e23e8c7
diff --git a/src/core/ai/build-gateway-config.ts b/src/core/ai/build-gateway-config.ts
index c63812b4c9..628575ccb3 100644
--- a/src/core/ai/build-gateway-config.ts
+++ b/src/core/ai/build-gateway-config.ts
@@ -44,6 +44,13 @@ export function buildGatewayConfig(c: GBrainConfig): AIGatewayConfig {
// multimodal/image embeds despite config.json looking complete. process.env
// still wins via the later spread.
if (c.voyage_api_key) envFromConfig.VOYAGE_API_KEY = c.voyage_api_key;
+ // Azure OpenAI (keyless/Entra): fold the non-secret endpoint/deployment + the
+ // Entra opt-in into the gateway env so the azure-openai recipe works in any
+ // shell (incl. non-interactive agent shells). The bearer token is minted at
+ // request time via `az`; no secret is stored in config.json.
+ if (c.azure_openai_endpoint) envFromConfig.AZURE_OPENAI_ENDPOINT = c.azure_openai_endpoint;
+ if (c.azure_openai_deployment) envFromConfig.AZURE_OPENAI_DEPLOYMENT = c.azure_openai_deployment;
+ if (c.azure_openai_use_entra) envFromConfig.AZURE_OPENAI_USE_ENTRA = c.azure_openai_use_entra;
// v0.32 codex finding #4+#5 fix: thread local-server _BASE_URL env vars
// into base_urls so the gateway hits the user's configured port. Without
diff --git a/src/core/ai/recipes/azure-openai.ts b/src/core/ai/recipes/azure-openai.ts
index 23aa7ab470..46b810c9c9 100644
--- a/src/core/ai/recipes/azure-openai.ts
+++ b/src/core/ai/recipes/azure-openai.ts
@@ -1,8 +1,55 @@
import type { Recipe } from '../types.ts';
import { AIConfigError } from '../errors.ts';
+import { execSync } from 'node:child_process';
const DEFAULT_API_VERSION = '2024-10-21'; // stable Azure OpenAI version as of 2026-05
+// Entra (keyless) auth support. Subscriptions that enforce disableLocalAuth via
+// Azure Policy reject api-key auth, so when no AZURE_OPENAI_API_KEY is present
+// (or AZURE_OPENAI_USE_ENTRA=1) we mint a short-lived AAD bearer token via the
+// Azure CLI and cache it. resolveAuth is synchronous, so execSync is the seam.
+// The caller needs `az login` + the "Cognitive Services OpenAI User" role.
+let _entraToken: { token: string; fetchedAt: number } | null = null;
+const ENTRA_TOKEN_TTL_MS = 45 * 60 * 1000; // refresh well before the ~60-90min expiry
+
+function fetchEntraToken(): string {
+ const now = Date.now();
+ if (_entraToken && now - _entraToken.fetchedAt < ENTRA_TOKEN_TTL_MS) {
+ return _entraToken.token;
+ }
+ let token = '';
+ try {
+ token = execSync(
+ 'az account get-access-token --resource https://cognitiveservices.azure.com --query accessToken -o tsv',
+ { encoding: 'utf-8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 30_000 },
+ ).trim();
+ } catch {
+ throw new AIConfigError(
+ 'Azure OpenAI (Entra/keyless): could not get an access token via `az account get-access-token`.',
+ 'Run `az login` and ensure your identity has the "Cognitive Services OpenAI User" role on the resource.',
+ );
+ }
+ if (!token) {
+ throw new AIConfigError(
+ 'Azure OpenAI (Entra/keyless): `az account get-access-token` returned an empty token.',
+ 'Run `az login` and verify the active subscription owns the Azure OpenAI resource.',
+ );
+ }
+ _entraToken = { token, fetchedAt: now };
+ return token;
+}
+
+/** @internal test seam: pre-populate (or clear) the Entra token cache so unit
+ * tests never shell out to `az`. */
+export function __setEntraTokenForTests(token: string | null): void {
+ _entraToken = token === null ? null : { token, fetchedAt: Date.now() };
+}
+
+/** Entra/keyless mode: explicit opt-in, or no api-key present (disableLocalAuth). */
+function isEntraMode(env: Record<string, string | undefined>): boolean {
+ return env.AZURE_OPENAI_USE_ENTRA === '1' || !env.AZURE_OPENAI_API_KEY;
+}
+
/**
* Azure OpenAI. The first recipe in v0.32 to exercise both seams:
* - resolveAuth returns `{headerName: 'api-key', token: <key>}` instead of
@@ -30,11 +77,13 @@ export const azureOpenAI: Recipe = {
// base_url_default omitted: Azure URLs are env-templated only.
auth_env: {
required: [
- 'AZURE_OPENAI_API_KEY',
'AZURE_OPENAI_ENDPOINT',
'AZURE_OPENAI_DEPLOYMENT',
],
- optional: ['AZURE_OPENAI_API_VERSION'],
+ // AZURE_OPENAI_API_KEY optional: when absent (or AZURE_OPENAI_USE_ENTRA=1)
+ // the recipe uses a refreshing Entra/AAD bearer token via the Azure CLI,
+ // required on subscriptions that enforce disableLocalAuth (keyless).
+ optional: ['AZURE_OPENAI_API_KEY', 'AZURE_OPENAI_USE_ENTRA', 'AZURE_OPENAI_API_VERSION'],
setup_url:
'https://learn.microsoft.com/en-us/azure/ai-services/openai/quickstart',
},
@@ -54,17 +103,18 @@ export const azureOpenAI: Recipe = {
},
},
resolveAuth(env) {
- const key = env.AZURE_OPENAI_API_KEY;
- if (!key) {
- throw new AIConfigError(
- `Azure OpenAI requires AZURE_OPENAI_API_KEY.`,
- 'Get a key from your Azure portal: https://learn.microsoft.com/en-us/azure/ai-services/openai/quickstart',
- );
+ // Entra/keyless mode: no api-key (disableLocalAuth) or opt-in via
+ // AZURE_OPENAI_USE_ENTRA=1. Mint a refreshing AAD bearer token. Returning
+ // an `Authorization: Bearer …` pair makes the gateway use the SDK's native
+ // bearer path (it strips the prefix and re-adds it), so no double-auth.
+ if (isEntraMode(env)) {
+ return { headerName: 'Authorization', token: `Bearer ${fetchEntraToken()}` };
}
- // Azure uses `api-key:` (no Bearer); the unified seam routes this
+ // Key mode: Azure uses `api-key:` (no Bearer); the unified seam routes this
// through `headers` instead of the SDK's apiKey field to avoid any
- // double-auth Authorization header sneaking in.
- return { headerName: 'api-key', token: key };
+ // double-auth Authorization header sneaking in. The key is present here:
+ // !isEntraMode(env) implies AZURE_OPENAI_API_KEY is set.
+ return { headerName: 'api-key', token: env.AZURE_OPENAI_API_KEY! };
},
resolveOpenAICompatConfig(env) {
const endpoint = env.AZURE_OPENAI_ENDPOINT?.replace(/\/+$/, '');
@@ -82,6 +132,7 @@ export const azureOpenAI: Recipe = {
);
}
const apiVersion = env.AZURE_OPENAI_API_VERSION ?? DEFAULT_API_VERSION;
+ const entra = isEntraMode(env);
const baseURL = `${endpoint}/openai/deployments/${deployment}`;
// Custom fetch wrapper splices ?api-version=... onto every request.
// Azure rejects requests without it.
@@ -102,10 +153,23 @@ export const azureOpenAI: Recipe = {
typeof input === 'string' || input instanceof URL
? finalUrl
: new Request(finalUrl, input as Request);
+ if (entra) {
+ // Entra mode: refresh the AAD bearer on every request. The gateway
+ // caches model instances (auth is baked in at instantiation), so a
+ // long-running process would otherwise send an expired token after
+ // ~1h. fetchEntraToken()'s 45-min TTL cache keeps `az` invocations
+ // rare; the override here keeps the header fresh.
+ const headers = new Headers(
+ init?.headers ??
+ (typeof finalInput !== 'string' ? (finalInput as Request).headers : undefined),
+ );
+ headers.set('Authorization', `Bearer ${fetchEntraToken()}`);
+ init = { ...init, headers };
+ }
return fetch(finalInput, init);
}) as unknown as typeof fetch;
return { baseURL, fetch: wrappedFetch };
},
setup_hint:
- 'Azure portal → Azure OpenAI resource. Set AZURE_OPENAI_API_KEY, AZURE_OPENAI_ENDPOINT, AZURE_OPENAI_DEPLOYMENT. Optionally AZURE_OPENAI_API_VERSION (default 2024-10-21).',
+ 'Azure portal → Azure OpenAI resource. Set AZURE_OPENAI_ENDPOINT + AZURE_OPENAI_DEPLOYMENT, and either AZURE_OPENAI_API_KEY or keyless Entra auth (`az login` + "Cognitive Services OpenAI User" role; force with AZURE_OPENAI_USE_ENTRA=1). Optionally AZURE_OPENAI_API_VERSION (default 2024-10-21).',
};
diff --git a/src/core/config.ts b/src/core/config.ts
index 590a936cab..e92b62a46f 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -63,6 +63,12 @@ export interface GBrainConfig {
* config.json file-plane route is wired through today.
*/
voyage_api_key?: string;
+ /** Azure OpenAI (keyless/Entra). Non-secret endpoint + deployment + Entra opt-in,
+ * folded into the gateway env so the azure-openai recipe works in any shell.
+ * The bearer token is minted at request time via `az` — no secret stored here. */
+ azure_openai_endpoint?: string;
+ azure_openai_deployment?: string;
+ azure_openai_use_entra?: string;
/** AI gateway config (v0.14+). v0.36+ default: "zeroentropyai:zembed-1" / 1280 / "anthropic:claude-haiku-4-5-20251001". */
embedding_model?: string;
embedding_dimensions?: number;
@@ -913,6 +919,9 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [
'zeroentropy_api_key',
'openrouter_api_key',
'voyage_api_key',
+ 'azure_openai_endpoint',
+ 'azure_openai_deployment',
+ 'azure_openai_use_entra',
'embedding_model',
'embedding_dimensions',
'embedding_disabled',
diff --git a/test/ai/recipe-azure-openai.test.ts b/test/ai/recipe-azure-openai.test.ts
index 1bd4dcd079..6ef77cfcce 100644
--- a/test/ai/recipe-azure-openai.test.ts
+++ b/test/ai/recipe-azure-openai.test.ts
@@ -38,11 +38,13 @@ describe('recipe: azure-openai', () => {
expect(r!.tier).toBe('openai-compat');
expect(r!.implementation).toBe('openai-compatible');
expect(r!.base_url_default).toBeUndefined(); // env-templated only
+ // Keyless (Entra/AAD) support: AZURE_OPENAI_API_KEY moved required → optional.
expect(r!.auth_env?.required).toEqual([
- 'AZURE_OPENAI_API_KEY',
'AZURE_OPENAI_ENDPOINT',
'AZURE_OPENAI_DEPLOYMENT',
]);
+ expect(r!.auth_env?.optional).toContain('AZURE_OPENAI_API_KEY');
+ expect(r!.auth_env?.optional).toContain('AZURE_OPENAI_USE_ENTRA');
expect(r!.auth_env?.optional).toContain('AZURE_OPENAI_API_VERSION');
});
@@ -66,9 +68,86 @@ describe('recipe: azure-openai', () => {
expect(auth.token).not.toContain('Bearer'); // critical: no Bearer prefix
});
- test('resolveAuth throws AIConfigError when AZURE_OPENAI_API_KEY missing', () => {
+ test('resolveAuth key mode wins when a key is present and Entra is not forced', () => {
const r = getRecipe('azure-openai')!;
- expect(() => r.resolveAuth!({})).toThrow(AIConfigError);
+ const auth = r.resolveAuth!({ ...FULL_ENV });
+ expect(auth.headerName).toBe('api-key');
+ });
+
+ test('resolveAuth Entra mode (no key) returns Authorization Bearer from the token cache', async () => {
+ const { __setEntraTokenForTests } = await import('../../src/core/ai/recipes/azure-openai.ts');
+ __setEntraTokenForTests('fake-aad-token');
+ try {
+ const r = getRecipe('azure-openai')!;
+ const auth = r.resolveAuth!({
+ AZURE_OPENAI_ENDPOINT: FULL_ENV.AZURE_OPENAI_ENDPOINT,
+ AZURE_OPENAI_DEPLOYMENT: FULL_ENV.AZURE_OPENAI_DEPLOYMENT,
+ });
+ expect(auth.headerName).toBe('Authorization');
+ expect(auth.token).toBe('Bearer fake-aad-token');
+ } finally {
+ __setEntraTokenForTests(null);
+ }
+ });
+
+ test('resolveAuth AZURE_OPENAI_USE_ENTRA=1 forces Entra even with a key present', async () => {
+ const { __setEntraTokenForTests } = await import('../../src/core/ai/recipes/azure-openai.ts');
+ __setEntraTokenForTests('fake-aad-token');
+ try {
+ const r = getRecipe('azure-openai')!;
+ const auth = r.resolveAuth!({ ...FULL_ENV, AZURE_OPENAI_USE_ENTRA: '1' });
+ expect(auth.headerName).toBe('Authorization');
+ expect(auth.token).toBe('Bearer fake-aad-token');
+ } finally {
+ __setEntraTokenForTests(null);
+ }
+ });
+
+ test('Entra fetch wrapper refreshes the Authorization header per request (cached models never go stale)', async () => {
+ const { __setEntraTokenForTests } = await import('../../src/core/ai/recipes/azure-openai.ts');
+ __setEntraTokenForTests('fresh-aad-token');
+ const r = getRecipe('azure-openai')!;
+ const cfg = r.resolveOpenAICompatConfig!({
+ AZURE_OPENAI_ENDPOINT: FULL_ENV.AZURE_OPENAI_ENDPOINT,
+ AZURE_OPENAI_DEPLOYMENT: FULL_ENV.AZURE_OPENAI_DEPLOYMENT,
+ }); // no key → Entra mode
+ const capturedAuth: (string | null)[] = [];
+ const realFetch = globalThis.fetch;
+ globalThis.fetch = ((_input: any, init?: any) => {
+ capturedAuth.push(new Headers(init?.headers).get('Authorization'));
+ return Promise.resolve(new Response('{}', { status: 200 }));
+ }) as typeof fetch;
+ try {
+ await cfg.fetch!(
+ 'https://my-resource.openai.azure.com/openai/deployments/embed-deployment/embeddings',
+ { headers: { Authorization: 'Bearer stale-instantiation-token', 'content-type': 'application/json' } },
+ );
+ expect(capturedAuth).toEqual(['Bearer fresh-aad-token']);
+ } finally {
+ globalThis.fetch = realFetch;
+ __setEntraTokenForTests(null);
+ }
+ });
+
+ test('key-mode fetch wrapper does NOT touch the Authorization header', async () => {
+ const r = getRecipe('azure-openai')!;
+ const cfg = r.resolveOpenAICompatConfig!(FULL_ENV); // key present → key mode
+ const captured: any[] = [];
+ const realFetch = globalThis.fetch;
+ globalThis.fetch = ((_input: any, init?: any) => {
+ captured.push(init);
+ return Promise.resolve(new Response('{}', { status: 200 }));
+ }) as typeof fetch;
+ try {
+ await cfg.fetch!(
+ 'https://my-resource.openai.azure.com/openai/deployments/embed-deployment/embeddings',
+ { headers: { 'api-key': 'az-fake-key' } },
+ );
+ expect(new Headers(captured[0]?.headers).get('Authorization')).toBeNull();
+ expect(new Headers(captured[0]?.headers).get('api-key')).toBe('az-fake-key');
+ } finally {
+ globalThis.fetch = realFetch;
+ }
});
test('applyResolveAuth puts the key in headers (NOT apiKey) — no double-auth', () => {