|
| 1 | +/** |
| 2 | + * The `AnthropicWorkloadIdentity` module authenticates `AnthropicClient` with |
| 3 | + * [Workload Identity Federation](https://platform.claude.com/docs/en/manage-claude/workload-identity-federation). |
| 4 | + * |
| 5 | + * @stability unstable |
| 6 | + * @since 4.1.3 |
| 7 | + */ |
| 8 | +import * as WorkloadIdentity from "effect/ai/WorkloadIdentity" |
| 9 | +import * as Effect from "effect/Effect" |
| 10 | +import * as HttpClient from "effect/http/HttpClient" |
| 11 | +import * as HttpClientRequest from "effect/http/HttpClientRequest" |
| 12 | +import * as Layer from "effect/Layer" |
| 13 | +import type * as Redacted from "effect/Redacted" |
| 14 | + |
| 15 | +const OAUTH_BETA = "oauth-2025-04-20" |
| 16 | +const FEDERATION_BETA = "oidc-federation-2026-04-01" |
| 17 | + |
| 18 | +const withOAuthBeta = (request: HttpClientRequest.HttpClientRequest): HttpClientRequest.HttpClientRequest => { |
| 19 | + const betas = request.headers["anthropic-beta"]?.split(",").map((beta) => beta.trim()).filter(Boolean) ?? [] |
| 20 | + return betas.includes(OAUTH_BETA) |
| 21 | + ? request |
| 22 | + : HttpClientRequest.setHeader(request, "anthropic-beta", [...betas, OAUTH_BETA].join(",")) |
| 23 | +} |
| 24 | + |
| 25 | +/** |
| 26 | + * Options for authenticating Anthropic requests with Workload Identity |
| 27 | + * Federation. |
| 28 | + * |
| 29 | + * @see {@link make} for creating a client transform from these options |
| 30 | + * @see {@link layer} for providing a transformed `HttpClient` from these options |
| 31 | + * |
| 32 | + * @stability unstable |
| 33 | + * @category options |
| 34 | + * @since 4.1.3 |
| 35 | + */ |
| 36 | +export type Options<E = never, R = never> = { |
| 37 | + /** |
| 38 | + * Produces the identity token to exchange. Runs again on every exchange. |
| 39 | + */ |
| 40 | + readonly identityToken: Effect.Effect<Redacted.Redacted<string>, E, R> |
| 41 | + /** |
| 42 | + * Tagged ID (`fdrl_...`) of the federation rule to evaluate. |
| 43 | + */ |
| 44 | + readonly federationRuleId: string |
| 45 | + /** |
| 46 | + * UUID of the Anthropic organization. |
| 47 | + */ |
| 48 | + readonly organizationId: string |
| 49 | + /** |
| 50 | + * Tagged ID (`svac_...`) of the service account the token acts as. |
| 51 | + */ |
| 52 | + readonly serviceAccountId?: string | undefined |
| 53 | + /** |
| 54 | + * Tagged ID (`wrkspc_...`) of the workspace to scope the token to. Required |
| 55 | + * when the federation rule is enabled for more than one workspace. |
| 56 | + */ |
| 57 | + readonly workspaceId?: string | undefined |
| 58 | + /** |
| 59 | + * The base URL of the Anthropic API, used for the token exchange. Pass the |
| 60 | + * same value as the `apiUrl` option of `AnthropicClient`. |
| 61 | + * |
| 62 | + * @default "https://api.anthropic.com" |
| 63 | + */ |
| 64 | + readonly apiUrl?: string | undefined |
| 65 | +} |
| 66 | + |
| 67 | +/** |
| 68 | + * Creates an `HttpClient` transform that authenticates Anthropic requests with |
| 69 | + * Workload Identity Federation. |
| 70 | + * |
| 71 | + * **When to use** |
| 72 | + * |
| 73 | + * Use as the `transformClient` option of `AnthropicClient` instead of an API key. |
| 74 | + * |
| 75 | + * **Details** |
| 76 | + * |
| 77 | + * The first request runs `identityToken` and exchanges the result at |
| 78 | + * `${apiUrl}/v1/oauth/token` with the `jwt-bearer` grant. The access token is |
| 79 | + * cached and sent as `Authorization: Bearer` with the `oauth-2025-04-20` beta |
| 80 | + * until shortly before it expires. Concurrent requests share one exchange. |
| 81 | + * `identityToken` runs again on every exchange, so a token read from a file is |
| 82 | + * picked up after it rotates. Surrounding whitespace is trimmed. |
| 83 | + * |
| 84 | + * Exchanges use the `HttpClient` captured by `make`, not the transformed client. |
| 85 | + * Failures are `HttpClientError`s, mapped to `AiError` by `AnthropicClient`. |
| 86 | + * A failing or empty `identityToken` produces an `EncodeError`. Source failures |
| 87 | + * are preserved as causes and must not contain secrets. Exchange errors redact |
| 88 | + * the literal identity token, including JSON-escaped occurrences. |
| 89 | + * |
| 90 | + * **Gotchas** |
| 91 | + * |
| 92 | + * - No background refresh: the next request after expiry waits for an exchange. |
| 93 | + * - A 401 invalidates only the token used by that request, without replay. |
| 94 | + * - The exchange client must not follow redirects or log request bodies. |
| 95 | + * `FetchHttpClient` redirects are disabled; redirect responses fail the exchange. |
| 96 | + * - Anthropic accepts an identity token with a `jti` claim once, so the |
| 97 | + * exchange is never retried and `identityToken` must yield a new token for |
| 98 | + * each exchange. |
| 99 | + * - The token URL must use `https`, or `http` on `localhost`, `127.0.0.1` or |
| 100 | + * `::1`. Any other URL is a defect. |
| 101 | + * - Leave the `apiKey` option of `AnthropicClient` unset. |
| 102 | + * |
| 103 | + * **Example** (Reading a projected Kubernetes token) |
| 104 | + * |
| 105 | + * ```ts |
| 106 | + * import { AnthropicClient, AnthropicWorkloadIdentity } from "@effect/ai-anthropic" |
| 107 | + * import { Effect, FileSystem, Layer, Redacted } from "effect" |
| 108 | + * |
| 109 | + * // Provide an `HttpClient` and a `FileSystem` to this layer. |
| 110 | + * const AnthropicLayer = Layer.unwrap(Effect.gen(function*() { |
| 111 | + * const fs = yield* FileSystem.FileSystem |
| 112 | + * const transformClient = yield* AnthropicWorkloadIdentity.make({ |
| 113 | + * identityToken: Effect.map( |
| 114 | + * fs.readFileString("/var/run/secrets/anthropic.com/token"), |
| 115 | + * Redacted.make |
| 116 | + * ), |
| 117 | + * federationRuleId: "fdrl_...", |
| 118 | + * organizationId: "00000000-0000-0000-0000-000000000000", |
| 119 | + * serviceAccountId: "svac_..." |
| 120 | + * }) |
| 121 | + * return AnthropicClient.layer({ transformClient }) |
| 122 | + * })) |
| 123 | + * ``` |
| 124 | + * |
| 125 | + * @see {@link layer} for providing the transformed `HttpClient` as a layer |
| 126 | + * |
| 127 | + * @stability unstable |
| 128 | + * @category constructors |
| 129 | + * @since 4.1.3 |
| 130 | + */ |
| 131 | +export const make = <E = never, R = never>(options: Options<E, R>): Effect.Effect< |
| 132 | + (client: HttpClient.HttpClient) => HttpClient.HttpClient, |
| 133 | + never, |
| 134 | + HttpClient.HttpClient | R |
| 135 | +> => |
| 136 | + Effect.map( |
| 137 | + WorkloadIdentity.make({ |
| 138 | + tokenUrl: `${options.apiUrl ?? "https://api.anthropic.com"}/v1/oauth/token`, |
| 139 | + identityToken: options.identityToken, |
| 140 | + exchangeRequest: (request, assertion) => |
| 141 | + request.pipe( |
| 142 | + HttpClientRequest.setHeader("anthropic-beta", `${OAUTH_BETA},${FEDERATION_BETA}`), |
| 143 | + HttpClientRequest.bodyJsonUnsafe({ |
| 144 | + grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer", |
| 145 | + assertion, |
| 146 | + federation_rule_id: options.federationRuleId, |
| 147 | + organization_id: options.organizationId, |
| 148 | + service_account_id: options.serviceAccountId, |
| 149 | + workspace_id: options.workspaceId |
| 150 | + }) |
| 151 | + ) |
| 152 | + }), |
| 153 | + (transform) => (client) => transform(HttpClient.mapRequest(client, withOAuthBeta)) |
| 154 | + ) |
| 155 | + |
| 156 | +/** |
| 157 | + * Provides the current `HttpClient` authenticated with workload identity federation. |
| 158 | + * |
| 159 | + * **When to use** |
| 160 | + * |
| 161 | + * Use with `Layer.provide` to authenticate `AnthropicClient` without |
| 162 | + * setting its `transformClient` option. |
| 163 | + * |
| 164 | + * **Details** |
| 165 | + * |
| 166 | + * Applies `make` to the current client, which also performs token exchanges. |
| 167 | + * The layer requires the services needed by `identityToken`. |
| 168 | + * |
| 169 | + * **Gotchas** |
| 170 | + * |
| 171 | + * - Every request carries the access token regardless of URL. Provide this |
| 172 | + * layer only to `AnthropicClient`, not the whole application. |
| 173 | + * - The gotchas of `make` apply. |
| 174 | + * |
| 175 | + * **Example** (Providing an authenticated client to `AnthropicClient`) |
| 176 | + * |
| 177 | + * ```ts |
| 178 | + * import { AnthropicClient, AnthropicWorkloadIdentity } from "@effect/ai-anthropic" |
| 179 | + * import { Effect, FileSystem, Layer, Redacted } from "effect" |
| 180 | + * |
| 181 | + * const WorkloadIdentity = AnthropicWorkloadIdentity.layer({ |
| 182 | + * identityToken: Effect.gen(function*() { |
| 183 | + * const fs = yield* FileSystem.FileSystem |
| 184 | + * return Redacted.make(yield* fs.readFileString("/var/run/secrets/anthropic.com/token")) |
| 185 | + * }), |
| 186 | + * federationRuleId: "fdrl_...", |
| 187 | + * organizationId: "00000000-0000-0000-0000-000000000000", |
| 188 | + * serviceAccountId: "svac_..." |
| 189 | + * }) |
| 190 | + * |
| 191 | + * // Requires an `HttpClient` and a `FileSystem`. |
| 192 | + * const AnthropicLayer = AnthropicClient.layer({}).pipe( |
| 193 | + * Layer.provide(WorkloadIdentity) |
| 194 | + * ) |
| 195 | + * ``` |
| 196 | + * |
| 197 | + * @see {@link make} for the client transform this layer applies |
| 198 | + * |
| 199 | + * @stability unstable |
| 200 | + * @category layers |
| 201 | + * @since 4.1.3 |
| 202 | + */ |
| 203 | +export const layer = <E = never, R = never>( |
| 204 | + options: Options<E, R> |
| 205 | +): Layer.Layer<HttpClient.HttpClient, never, HttpClient.HttpClient | R> => |
| 206 | + Layer.effect( |
| 207 | + HttpClient.HttpClient, |
| 208 | + Effect.gen(function*() { |
| 209 | + const client = yield* HttpClient.HttpClient |
| 210 | + const transform = yield* make(options) |
| 211 | + return transform(client) |
| 212 | + }) |
| 213 | + ) |
0 commit comments