Skip to content

improvement: handle azure workload identity authentication #945

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/handlers/handlerUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -914,6 +914,8 @@ export function constructConfigFromRequestHeaders(
azureAuthMode: requestHeaders[`x-${POWERED_BY}-azure-auth-mode`],
azureManagedClientId:
requestHeaders[`x-${POWERED_BY}-azure-managed-client-id`],
azureWorkloadClientId:
requestHeaders[`x-${POWERED_BY}-azure-workload-client-id`],
azureEntraClientId: requestHeaders[`x-${POWERED_BY}-azure-entra-client-id`],
azureEntraClientSecret:
requestHeaders[`x-${POWERED_BY}-azure-entra-client-secret`],
Expand Down
7 changes: 6 additions & 1 deletion src/middlewares/requestValidator/schema/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
VALID_PROVIDERS,
GOOGLE_VERTEX_AI,
TRITON,
AZURE_OPEN_AI,
} from '../../../globals';

export const configSchema: any = z
Expand Down Expand Up @@ -107,6 +108,7 @@ export const configSchema: any = z
openai_organization: z.string().optional(),
// AzureOpenAI specific
azure_model_name: z.string().optional(),
azure_auth_mode: z.string().optional(),
strict_open_ai_compliance: z.boolean().optional(),
})
.refine(
Expand All @@ -123,6 +125,8 @@ export const configSchema: any = z
(value.vertex_service_account_json || value.vertex_project_id);
const hasAWSDetails =
value.aws_access_key_id && value.aws_secret_access_key;
const hasAzureAuth =
value.provider == AZURE_OPEN_AI && value.azure_auth_mode;

return (
hasProviderApiKey ||
Expand All @@ -137,7 +141,8 @@ export const configSchema: any = z
value.after_request_hooks ||
value.before_request_hooks ||
value.input_guardrails ||
value.output_guardrails
value.output_guardrails ||
hasAzureAuth
);
},
{
Expand Down
38 changes: 37 additions & 1 deletion src/providers/azure-openai/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,16 @@ import { ProviderAPIConfig } from '../types';
import {
getAccessTokenFromEntraId,
getAzureManagedIdentityToken,
getAzureWorkloadIdentityToken,
} from './utils';
import { env, getRuntimeKey } from 'hono/adapter';

const AzureOpenAIAPIConfig: ProviderAPIConfig = {
getBaseURL: ({ providerOptions }) => {
const { resourceName } = providerOptions;
return `https://${resourceName}.openai.azure.com/openai`;
},
headers: async ({ providerOptions, fn }) => {
headers: async ({ c, providerOptions, fn }) => {
const { apiKey, azureAuthMode } = providerOptions;

if (azureAuthMode === 'entra') {
Expand Down Expand Up @@ -39,6 +41,40 @@ const AzureOpenAIAPIConfig: ProviderAPIConfig = {
Authorization: `Bearer ${accessToken}`,
};
}
if (azureAuthMode === 'workload') {
const { azureWorkloadClientId } = providerOptions;

const authorityHost = env(c).AZURE_AUTHORITY_HOST;
const tenantId = env(c).AZURE_TENANT_ID;
const clientId = azureWorkloadClientId || env(c).AZURE_CLIENT_ID;
const federatedTokenFile = env(c).AZURE_FEDERATED_TOKEN_FILE;

const runtime = getRuntimeKey();
if (
authorityHost &&
tenantId &&
clientId &&
federatedTokenFile &&
runtime === 'node'
) {
const fs = await import('fs');
const federatedToken = fs.readFileSync(federatedTokenFile, 'utf8');
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@VisargD Please share your opinion here, we can also accept the contents of AZURE_FEDERATED_TOKEN_FILE file from header and parse it here. With this we can also make sure this works with cloudflare env as well.


if (federatedToken) {
const scope = 'https://cognitiveservices.azure.com/.default';
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We can remove the scope from here and just handling inside the getAzureWorkloadIdentityToken.

const accessToken = await getAzureWorkloadIdentityToken(
authorityHost,
tenantId,
clientId,
federatedToken,
scope
);
return {
Authorization: `Bearer ${accessToken}`,
};
}
}
}
const headersObj: Record<string, string> = {
'api-key': `${apiKey}`,
};
Expand Down
38 changes: 38 additions & 0 deletions src/providers/azure-openai/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,44 @@ export async function getAzureManagedIdentityToken(
}
}

export async function getAzureWorkloadIdentityToken(
authorityHost: string,
tenantId: string,
clientId: string,
federatedToken: string,
scope = 'https://cognitiveservices.azure.com/.default'
) {
try {
const url = `${authorityHost}/${tenantId}/oauth2/v2.0/token`;
const params = new URLSearchParams({
client_id: clientId,
client_assertion: federatedToken,
client_assertion_type:
'urn:ietf:params:oauth:client-assertion-type:jwt-bearer',
scope: scope,
grant_type: 'client_credentials',
});

const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: params,
});

if (!response.ok) {
const errorMessage = await response.text();
console.log({ message: `Error from Entra ${errorMessage}` });
return undefined;
}
const data: { access_token: string } = await response.json();
return data.access_token;
} catch (error) {
console.log(error);
}
}

export const AzureOpenAIFinetuneResponseTransform = (
response: Response | ErrorResponse,
responseStatus: number
Expand Down
1 change: 1 addition & 0 deletions src/types/requestBody.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ export interface Options {
adAuth?: string;
azureAuthMode?: string;
azureManagedClientId?: string;
azureWorkloadClientId?: string;
azureEntraClientId?: string;
azureEntraClientSecret?: string;
azureEntraTenantId?: string;
Expand Down
Loading