-
Notifications
You must be signed in to change notification settings - Fork 21.7k
feat(opencode): added in oauth connection for azure provider through MS Entra ID and az cli #31351
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
OpeOginni
wants to merge
13
commits into
anomalyco:dev
Choose a base branch
from
OpeOginni:feat/azure-oauth
base: dev
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+201
−27
Open
Changes from all commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
4abac2a
feat(opencode): added oauth to azure through MS Entra ID and az cli
OpeOginni d862d02
docs: added more docs on new methods to connect azure and az cognitive
OpeOginni dffa104
Merge branch 'dev' into feat/azure-oauth
OpeOginni 2b53cf0
Merge branch 'dev' into feat/azure-oauth
OpeOginni db43ee0
docs: revert localized provider updates
OpeOginni fdf14a8
chore: improved azure oauth method name and ran format
OpeOginni fa40659
fix: Preserve model-specific endpoints for Azure Cognitive Services
OpeOginni fcc21f3
fix: Remove the Anthropic API-key header when using bearer
OpeOginni 3cf9cfb
docs: display to use the Foundry inference role for Cognitive Services
OpeOginni be5f5db
fix: prefer azure cli expires_on for token cache
OpeOginni c0ecd5d
fix: validate azure cli token expiry parsing
OpeOginni 5613ebb
docs: fixed description of azure oauth
OpeOginni 7adfe50
fix(provider): resolve azure cognitive services resource vars
OpeOginni File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,26 +1,160 @@ | ||
| import type { Hooks, PluginInput } from "@opencode-ai/plugin" | ||
| import { OAUTH_DUMMY_KEY } from "../auth" | ||
| import { InstallationVersion } from "@opencode-ai/core/installation/version" | ||
| import { Option, Schema } from "effect" | ||
|
|
||
| const AZURE_SCOPE = "https://cognitiveservices.azure.com" | ||
| const AZURE_TOKEN_REFRESH_BUFFER = 60_000 | ||
| const AzureCliToken = Schema.Struct({ | ||
| accessToken: Schema.String, | ||
| expires_on: Schema.optional(Schema.Number), | ||
| expiresOn: Schema.optional(Schema.String), | ||
| }) | ||
| const decodeAzureCliToken = Schema.decodeUnknownOption(Schema.fromJsonString(AzureCliToken)) | ||
|
|
||
| export async function AzureAuthPlugin(_input: PluginInput): Promise<Hooks> { | ||
| const prompts = [] | ||
| if (!process.env.AZURE_RESOURCE_NAME) { | ||
| prompts.push({ | ||
| type: "text" as const, | ||
| key: "resourceName", | ||
| message: "Enter Azure Resource Name", | ||
| placeholder: "e.g. my-models", | ||
| }) | ||
| } | ||
| return azureAuthPlugin({ | ||
| provider: "azure", | ||
| resourceEnv: "AZURE_RESOURCE_NAME", | ||
| oauthInstructions: | ||
| "Sign in with `az login`. The signed-in Azure identity must have the Cognitive Services OpenAI User role for this resource.", | ||
| prompts: process.env.AZURE_RESOURCE_NAME | ||
| ? [] | ||
| : [ | ||
| { | ||
| type: "text" as const, | ||
| key: "resourceName", | ||
| message: "Enter Azure Resource Name", | ||
| placeholder: "e.g. my-models", | ||
| }, | ||
| ], | ||
| providerOptions: (resourceName) => ({ resourceName }), | ||
| }) | ||
| } | ||
|
|
||
| export async function AzureCognitiveServicesAuthPlugin(_input: PluginInput): Promise<Hooks> { | ||
| return azureAuthPlugin({ | ||
| provider: "azure-cognitive-services", | ||
| resourceEnv: "AZURE_COGNITIVE_SERVICES_RESOURCE_NAME", | ||
| oauthInstructions: | ||
| "Sign in with `az login`. The signed-in Azure identity must have the Cognitive Services User or Foundry User role for this resource.", | ||
| prompts: process.env.AZURE_COGNITIVE_SERVICES_RESOURCE_NAME | ||
| ? [] | ||
| : [ | ||
| { | ||
| type: "text" as const, | ||
| key: "resourceName", | ||
| message: "Enter Azure Cognitive Services Resource Name", | ||
| placeholder: "e.g. my-models", | ||
| }, | ||
| ], | ||
| }) | ||
| } | ||
|
|
||
| function azureAuthPlugin(input: { | ||
| provider: string | ||
| resourceEnv: string | ||
| oauthInstructions: string | ||
| prompts: NonNullable<Hooks["auth"]>["methods"][number]["prompts"] | ||
| providerOptions?: (resourceName: string) => Record<string, string> | ||
| }): Hooks { | ||
| return { | ||
| auth: { | ||
| provider: "azure", | ||
| provider: input.provider, | ||
| async loader(getAuth) { | ||
| const auth = await getAuth() | ||
| if (auth.type !== "oauth") return {} | ||
|
|
||
| const resourceName = process.env[input.resourceEnv] || auth.accountId | ||
| const tokenProvider = azureCliTokenProvider() | ||
|
|
||
| return { | ||
| ...((resourceName && input.providerOptions?.(resourceName)) ?? {}), | ||
| apiKey: OAUTH_DUMMY_KEY, | ||
| async fetch(requestInput: RequestInfo | URL, init?: RequestInit) { | ||
| const currentAuth = await getAuth() | ||
| if (currentAuth.type !== "oauth") return fetch(requestInput, init) | ||
|
|
||
| const headers = new Headers(requestInput instanceof Request ? requestInput.headers : undefined) | ||
| if (init?.headers) { | ||
| const entries = | ||
| init.headers instanceof Headers | ||
| ? init.headers.entries() | ||
| : Array.isArray(init.headers) | ||
| ? init.headers | ||
| : Object.entries(init.headers as Record<string, string | undefined>) | ||
| for (const [key, value] of entries) { | ||
| if (value !== undefined) headers.set(key, String(value)) | ||
| } | ||
| } | ||
| headers.delete("api-key") | ||
| headers.delete("x-api-key") | ||
| headers.set("authorization", `Bearer ${await tokenProvider()}`) | ||
| headers.set("User-Agent", `opencode/${InstallationVersion}`) | ||
|
|
||
| return fetch(requestInput, { ...init, headers }) | ||
| }, | ||
| } | ||
| }, | ||
| methods: [ | ||
| { | ||
| type: "api", | ||
| label: "API key", | ||
| prompts, | ||
| prompts: input.prompts, | ||
| }, | ||
| { | ||
| type: "oauth", | ||
| label: "Microsoft Entra ID (OAuth via az cli)", | ||
| prompts: input.prompts, | ||
| authorize: async (inputs) => ({ | ||
| url: "https://learn.microsoft.com/azure/developer/ai/keyless-connections", | ||
| instructions: input.oauthInstructions, | ||
| method: "auto" as const, | ||
| callback: async () => ({ | ||
| type: "success" as const, | ||
| access: OAUTH_DUMMY_KEY, | ||
| refresh: OAUTH_DUMMY_KEY, | ||
| expires: Date.now() + 365 * 24 * 60 * 60 * 1000, | ||
| accountId: inputs?.resourceName || process.env[input.resourceEnv], | ||
| }), | ||
| }), | ||
| }, | ||
| ], | ||
| }, | ||
| } | ||
| } | ||
|
|
||
| function azureCliTokenProvider() { | ||
| let cached: { token: string; expires: number } | undefined | ||
| return async () => { | ||
| if (cached && cached.expires - Date.now() > AZURE_TOKEN_REFRESH_BUFFER) return cached.token | ||
|
|
||
| const proc = Bun.spawn(["az", "account", "get-access-token", "--resource", AZURE_SCOPE, "--output", "json"], { | ||
| stdout: "pipe", | ||
| stderr: "pipe", | ||
| }) | ||
| const [stdout, stderr, exitCode] = await Promise.all([ | ||
| new Response(proc.stdout).text(), | ||
| new Response(proc.stderr).text(), | ||
| proc.exited, | ||
| ]) | ||
| if (exitCode !== 0) { | ||
| throw new Error(stderr.trim() || "Failed to get Azure access token. Run `az login` and try again.") | ||
| } | ||
|
|
||
| const decoded = decodeAzureCliToken(stdout) | ||
| if (Option.isNone(decoded)) throw new Error("Azure CLI did not return an access token") | ||
|
|
||
| cached = { | ||
| token: decoded.value.accessToken, | ||
| // Azure CLI's expiresOn is a timezone-less local datetime; expires_on avoids DST ambiguity. | ||
| expires: | ||
| decoded.value.expires_on !== undefined | ||
| ? decoded.value.expires_on * 1000 | ||
| : decoded.value.expiresOn | ||
| ? new Date(decoded.value.expiresOn).getTime() | ||
| : Date.now() + 30 * 60 * 1000, | ||
| } | ||
| return cached.token | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.