Debian Codegraph @

examples/workload_identity.py

raw
1 #!/usr/bin/env python3
2 """
3 Workload Identity Federation & Credential Providers — comprehensive examples.
4
5 The Anthropic client resolves auth in this precedence order:
6 1. Constructor args: api_key=, auth_token=, or credentials=
7 2. Env vars: ANTHROPIC_API_KEY, ANTHROPIC_AUTH_TOKEN, then the credential chain below
8 3. Standard defaults: ~/.config/anthropic/credentials.json if it exists
9
10 The `credentials=` arg accepts any AccessTokenProvider — a zero-arg callable returning
11 AccessToken(token, expires_at). The client caches the token and proactively refreshes
12 it (120s advisory / 30s mandatory before expiry).
13 """
14
15 import os
16
17 import anthropic
18 from anthropic import (
19 AccessToken,
20 StaticToken,
21 CredentialsFile,
22 IdentityTokenFile,
23 WorkloadIdentityCredentials,
24 )
25
26 # =============================================================================
27 # Section 1: Zero-config (recommended for production workloads)
28 # =============================================================================
29 # Just construct the client. Auth is resolved from the environment.
30 #
31 # For Kubernetes / GitHub Actions / etc., set these env vars on the workload:
32 # ANTHROPIC_IDENTITY_TOKEN_FILE=/var/run/secrets/kubernetes.io/serviceaccount/token
33 # ANTHROPIC_FEDERATION_RULE_ID=fdrl_01...
34 # ANTHROPIC_ORGANIZATION_ID=00000000-0000-0000-0000-000000000000
35 # ANTHROPIC_SERVICE_ACCOUNT_ID=svac_01... (optional)
36 #
37 # Or, if a sidecar/daemon writes a profile config + credentials file:
38 # ANTHROPIC_PROFILE=my-profile (picks ~/.config/anthropic/configs/my-profile.json
39 # and ~/.config/anthropic/credentials/my-profile.json)
40 # ANTHROPIC_CONFIG_DIR=/etc/anthropic (relocates the root; optional)
41 #
42 # Or, the existing env vars still work:
43 # ANTHROPIC_API_KEY=sk-ant-...
44 # ANTHROPIC_AUTH_TOKEN=sk-ant-oat01-...
45
46 client = anthropic.Anthropic()
47
48
49 # =============================================================================
50 # Section 2: Explicit credentials= via constructor
51 # =============================================================================
52
53 # --- 2a. WorkloadIdentityCredentials: exchange an external OIDC JWT --------
54
55 # JWT source option i: read from a file (re-read on every refresh — handles k8s rotation)
56 client = anthropic.Anthropic(
57 credentials=WorkloadIdentityCredentials(
58 identity_token_provider=IdentityTokenFile(
59 "/var/run/secrets/kubernetes.io/serviceaccount/token",
60 ),
61 federation_rule_id="fdrl_01...",
62 organization_id="00000000-0000-0000-0000-000000000000",
63 service_account_id="svac_01...",
64 ),
65 )
66
67 # JWT source option ii: from an env var (CI systems that inject the token directly)
68 client = anthropic.Anthropic(
69 credentials=WorkloadIdentityCredentials(
70 identity_token_provider=lambda: os.environ["ANTHROPIC_IDENTITY_TOKEN"],
71 federation_rule_id="fdrl_01...",
72 organization_id="00000000-0000-0000-0000-000000000000",
73 ),
74 )
75
76
77 # JWT source option iii: custom callable (secrets manager, internal token service, etc.)
78 def fetch_jwt_from_vault() -> str:
79 # your logic here
80 return ""
81
82
83 client = anthropic.Anthropic(
84 credentials=WorkloadIdentityCredentials(
85 identity_token_provider=fetch_jwt_from_vault,
86 federation_rule_id="fdrl_01...",
87 organization_id="00000000-0000-0000-0000-000000000000",
88 ),
89 )
90
91 # --- 2b. CredentialsFile: read auth config from a named profile on disk ----
92 #
93 # Profiles live under the config directory (default ~/.config/anthropic/,
94 # override with ANTHROPIC_CONFIG_DIR) as a pair of files:
95 #
96 # configs/<profile>.json — non-secret. Shape:
97 #
98 # {
99 # "authentication": {"type": "oidc_federation"|"user_oauth", ...},
100 # "organization_id": "00000000-0000-0000-0000-000000000000",
101 # "workspace_id": "wrkspc_01...",
102 # "base_url": "https://api.anthropic.com"
103 # }
104 #
105 # The "authentication" object is a tagged union discriminated on "type":
106 #
107 # {"type": "oidc_federation",
108 # "federation_rule_id": "fdrl_...",
109 # "service_account_id": "svac_...",
110 # "identity_token": {"source": "file", "path": "..."}}
111 # → SDK performs the jwt-bearer exchange itself. If "identity_token"
112 # is omitted, ANTHROPIC_IDENTITY_TOKEN_FILE is used instead.
113 # organization_id is read from the top level of the config.
114 #
115 # {"type": "user_oauth", "client_id": "..."}
116 # → interactive PKCE login with refresh_token rotation. On access-token
117 # expiry the SDK performs a refresh_token grant against
118 # /v1/oauth/token and writes the new tokens back to
119 # credentials/<profile>.json (atomic replace).
120 #
121 # {"type": "user_oauth"} (no client_id)
122 # → credentials file is externally rotated by a sidecar/daemon. The
123 # SDK re-reads the file on every refresh and returns whatever
124 # access_token is there; no refresh grant is attempted.
125 #
126 # credentials/<profile>.json — secret (0600). Holds access_token,
127 # expires_at, and (for user_oauth with
128 # a client_id) refresh_token.
129
130 # Point at a specific profile name:
131 client = anthropic.Anthropic(credentials=CredentialsFile(profile="production"))
132 # Or resolve the profile from ANTHROPIC_PROFILE / <config_dir>/active_config / "default":
133 client = anthropic.Anthropic(credentials=CredentialsFile())
134
135 # --- 2c. StaticToken: you already have a bearer token ---------------------
136 client = anthropic.Anthropic(credentials=StaticToken("sk-ant-oat01-..."))
137 # (equivalent to anthropic.Anthropic(auth_token="sk-ant-oat01-..."))
138
139
140 # --- 2d. Custom AccessTokenProvider ---------------------------------------
141 # Any callable matching AccessTokenProvider works. `force_refresh` is True after
142 # the API rejected the previous token; providers without a cache can ignore it.
143 # If your token source already does its own caching, use expires_at=0 and
144 # the client will call your provider before every request instead of caching.
145 def my_provider(*, force_refresh: bool = False) -> AccessToken: # noqa: ARG001
146 # call your internal auth service here
147 return AccessToken(token="sk-ant-oat01-...", expires_at=1775000000)
148
149
150 client = anthropic.Anthropic(credentials=my_provider)
151
152 # =============================================================================
153 # Section 3: Precedence demonstration
154 # =============================================================================
155 # Constructor args always win over env vars, which win over default file paths.
156 # Within constructor args, passing more than one of api_key/auth_token/credentials
157 # is supported but credentials takes the Bearer slot (api_key still sends X-Api-Key
158 # if both are set — generally don't do this).
159
160 # =============================================================================
161 # Section 4: Async
162 # =============================================================================
163 # AsyncAnthropic accepts the same providers. It also accepts an `async def`
164 # provider and awaits it on the event loop.
165
166
167 async def fetch_token_from_my_auth_service(*, force_refresh: bool = False) -> str: # noqa: ARG001
168 return "sk-ant-oat01-..."
169
170
171 async def my_async_provider(*, force_refresh: bool = False) -> AccessToken:
172 token = await fetch_token_from_my_auth_service(force_refresh=force_refresh)
173 return AccessToken(token=token, expires_at=1775000000)
174
175
176 async_client = anthropic.AsyncAnthropic(credentials=my_async_provider)
177
178
179 async def main() -> None:
180 aclient = anthropic.AsyncAnthropic(
181 credentials=WorkloadIdentityCredentials(
182 identity_token_provider=IdentityTokenFile(), # uses ANTHROPIC_IDENTITY_TOKEN_FILE
183 federation_rule_id="fdrl_01...",
184 organization_id="00000000-0000-0000-0000-000000000000",
185 ),
186 )
187 msg = await aclient.messages.create(
188 model="claude-opus-5-5",
189 max_tokens=1024,
190 messages=[{"role": "user", "content": "Hello"}],
191 )
192 print(msg)
193
194
195 # asyncio.run(main())