Skip to content

Commit ea3a63a

Browse files
oldsjclaude
andauthored
feat: subscription auth for Claude and Codex (OAuth token, ChatGPT login, credential refresh) (#60)
* feat(api): add subscription auth methods to ModelConfig Add anthropic.authMethod (apiKey | oauthToken) and openAI.authMethod (apiKey | chatGPT) with openAI.accountID and openAI.responsesTransport. CEL rules require accountID for chatGPT and limit accountID and responsesTransport to chatGPT. In chatGPT mode baseUrl replaces the default Codex subscription backend. Generated CRD manifests follow in a separate commit. Signed-off-by: James Olds <12104969+oldsj@users.noreply.github.com> (cherry picked from commit a71c97c) * feat(claude): support Claude subscription OAuth tokens With anthropic.authMethod oauthToken, the Claude Harness gets an inert CLAUDE_CODE_OAUTH_TOKEN placeholder, and the egress gateway injects the real token from the referenced Secret as an Authorization: Bearer header. API-key mode is unchanged. Signed-off-by: James Olds <12104969+oldsj@users.noreply.github.com> (cherry picked from commit a3fc473) * feat(codex): support ChatGPT subscription auth With openAI.authMethod chatGPT, the Codex adapter writes a synthetic auth.json (inert JWTs, no refresh token) and removes API-key variables, so the Actor never holds a usable credential. The gateway binds the real access token to the backend host: chatgpt.com by default, or the openAI.baseUrl host when set. responsesTransport https selects a custom provider with WebSockets disabled. The kagent ADK harness rejects ChatGPT auth. Harness config version moves to 4. Signed-off-by: James Olds <12104969+oldsj@users.noreply.github.com> (cherry picked from commit 8878e05) * feat(controller): refresh ChatGPT credentials through the Codex CLI When KAGENT_CHATGPT_REFRESH_IMAGE is set, the leader-elected controller schedules one Job per ChatGPT Secret before the access token expires. The Job runs the pinned official Codex CLI (app-server account/read with refreshToken) against a tmpfs CODEX_HOME. It then commits the rotated auth.json and access token in one version-checked Secret update. Job RBAC is scoped to that Secret by resourceNames. A refresh attempt that fails after it may have spent the refresh token marks the ModelConfig ResolvedRefs=False with ReauthenticationRequired instead of retrying. Re-seeding the Secret clears it. The Codex image now ships the kagent-credential-refresh binary. Signed-off-by: James Olds <12104969+oldsj@users.noreply.github.com> (cherry picked from commit baaeebf) * docs: describe subscription credential injection Document Claude OAuth tokens, Codex ChatGPT mode, including the default backend, baseUrl override and host binding, and the dedicated-login seeding and refresh lifecycle. Signed-off-by: James Olds <12104969+oldsj@users.noreply.github.com> (cherry picked from commit 7a1513d) * feat: bootstrap ChatGPT runtime credentials from a seed Secret (#3) (cherry picked from commit 7e3b3b3) * Codex harness: report expired auth clearly without leaking upstream error text (#32) * fix(codex): expose safe native turn failure diagnostics Signed-off-by: James Olds <12104969+oldsj@users.noreply.github.com> * test(auth): verify renewal after runtime credential replacement Signed-off-by: James Olds <12104969+oldsj@users.noreply.github.com> * fix(codex): restrict public failures to fixed summaries Signed-off-by: James Olds <12104969+oldsj@users.noreply.github.com> --------- Signed-off-by: James Olds <12104969+oldsj@users.noreply.github.com> (cherry picked from commit 656163a) * feat(helm): gate credential refresh RBAC and move its settings to controller config Upstream narrowed the controller's roles, so the Job, ServiceAccount, Role, RoleBinding, NetworkPolicy and Secret-update permissions the ChatGPT refresh needs get their own role, rendered only when config.credentialRefresh.chatgptImage enables refresh. The image setting replaces the KAGENT_CHATGPT_REFRESH_IMAGE environment variable. The refresh worker now requires the Codex CLI version the Codex Harness image pins instead of a separate constant. Regenerate the ModelConfig CRD, update the model discovery expectations, and run the chart unit tests and the subscription packages in fork CI. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Signed-off-by: James Olds <12104969+oldsj@users.noreply.github.com> --------- Signed-off-by: James Olds <12104969+oldsj@users.noreply.github.com> Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
1 parent f5c589d commit ea3a63a

40 files changed

Lines changed: 2876 additions & 237 deletions

‎.github/workflows/mainloop-fork-ci.yaml‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,11 +72,40 @@ jobs:
7272
./core/internal/database ./core/pkg/migrations
7373
./core/internal/service/session ./core/internal/service/checkpoint
7474
./core/internal/grpcserver ./core/internal/httpserver/auth ./core/pkg/auth
75+
- name: Test subscription credential refresh and compilation
76+
run: >-
77+
go test -count=1
78+
./core/internal/controller/chatgptrefresh ./core/internal/translator/...
79+
./core/internal/service/model ./core/pkg/config
7580
- name: Test fake native consumers
7681
run: >-
7782
go test -count=1 -skip '^TestPinnedCodexAcceptsGeneratedConfiguration$'
7883
./harness/claude/... ./harness/codex/... ./harness/runtime/...
7984
85+
helm-unit-tests:
86+
name: Helm chart unit tests
87+
runs-on: ubuntu-latest
88+
timeout-minutes: 15
89+
env:
90+
VERSION: v0.0.1-test
91+
SOURCE_SHA: ${{ github.event.pull_request.head.sha || github.sha }}
92+
steps:
93+
- name: Checkout exact source
94+
uses: actions/checkout@v6
95+
with:
96+
ref: ${{ env.SOURCE_SHA }}
97+
persist-credentials: false
98+
- name: Set up Helm
99+
uses: azure/setup-helm@9bc31f4ebc9c6b171d7bfbaa5d006ae7abdb4310 # v5.0.1
100+
with:
101+
version: v3.18.0
102+
- name: Install unittest plugin
103+
run: helm plugin install https://github.com/helm-unittest/helm-unittest
104+
- name: Chart init
105+
run: make helm-version
106+
- name: Run helm unit tests
107+
run: helm unittest helm/kagent
108+
80109
controller-dev-entrypoint:
81110
name: controller-dev-entrypoint.sh rebuild-on-change
82111
runs-on: ubuntu-latest

‎docs/architecture/credential-injection.md‎

Lines changed: 193 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,8 @@ overrides of these variables are rejected.
5858
| --- | --- |
5959
| OpenAI API key | `authorization: Bearer <key>` |
6060
| Anthropic API key | `x-api-key: <key>` |
61+
| Claude Code OAuth token | `authorization: Bearer <token>` |
62+
| Codex ChatGPT access token | `authorization: Bearer <token>` |
6163
| Azure OpenAI and Foundry OpenAI API key | `api-key: <key>` |
6264
| Foundry Anthropic API key | `x-api-key: <key>` |
6365
| Gemini API key | `x-goog-api-key: <key>` |
@@ -195,3 +197,194 @@ for gateway injection is configured by the platform.
195197
AWS IAM signing, Vertex service-account, and SAP OAuth credentials still fail
196198
compilation; sharing this field with supported providers does not enable those
197199
credential modes.
200+
201+
For the Claude Harness, `anthropic.authMethod: oauthToken` reads the token from
202+
the ModelConfig's `apiKeySecret` and `apiKeySecretKey`, sets only an inert
203+
`CLAUDE_CODE_OAUTH_TOKEN` placeholder in the Actor, and binds the real token to
204+
the Anthropic `Authorization: Bearer` request header at the egress gateway. The
205+
default `apiKey` mode retains `ANTHROPIC_API_KEY` and `x-api-key` behavior.
206+
`claude setup-token` creates a long-lived token without a refresh flow; rotate
207+
it manually by replacing the referenced Secret value.
208+
209+
For the Codex Harness, `openAI.authMethod: chatGPT` uses `openAI.accountID` and
210+
the current access token referenced by `apiKeySecret` / `apiKeySecretKey`.
211+
The adapter writes synthetic JWTs, an empty refresh token, and a recent refresh
212+
timestamp into private `CODEX_HOME/auth.json`; real bearer credentials remain
213+
at the gateway, bound only to the backend host. That host is `chatgpt.com`
214+
(`https://chatgpt.com/backend-api/codex`) unless `openAI.baseUrl` replaces the
215+
backend, in which case egress and the credential binding follow the `baseUrl`
216+
host. Actors cannot reach `auth.openai.com` or `api.openai.com`.
217+
`responsesTransport: https` disables WebSockets; omission uses the native
218+
WebSocket-capable provider and fallback.
219+
The account ID is identifying data retained in the Actor and provenance.
220+
221+
## ChatGPT credential refresh
222+
223+
Create a **dedicated** ChatGPT login for the controller. Never seed it from a
224+
developer's existing Codex home: rotating a shared refresh token invalidates
225+
the other login. Use the official pinned Codex CLI with an isolated temporary
226+
`CODEX_HOME` and file credential storage. Store the original full `auth.json`
227+
and its exact paired access token in your secret store. A Secret operator can
228+
publish this pair to a source Secret; kagent automatically bootstraps a separate
229+
runtime Secret when its `kagent.dev/chatgpt-auth-seed-secret` annotation names
230+
that source in the **same namespace**. ModelConfig references the runtime
231+
Secret and its access-token key, with a nonempty `openAI.accountID` matching
232+
both the file and the access token's `https://api.openai.com/auth` /
233+
`chatgpt_account_id` claim.
234+
235+
For example, with an existing External Secrets Operator and SecretStore, keep
236+
the dedicated login pair in two properties of one store entry. Replace the
237+
store, entry, model and account placeholders with your deployment's values:
238+
239+
```yaml
240+
apiVersion: external-secrets.io/v1
241+
kind: ExternalSecret
242+
metadata:
243+
name: chatgpt-auth-seed
244+
namespace: kagent
245+
spec:
246+
refreshInterval: 1h
247+
secretStoreRef:
248+
name: credential-store
249+
kind: SecretStore
250+
target:
251+
name: chatgpt-auth-seed
252+
creationPolicy: Owner
253+
template:
254+
type: Opaque
255+
data:
256+
- secretKey: auth.json
257+
remoteRef:
258+
key: dedicated-chatgpt-login
259+
property: auth.json
260+
- secretKey: access-token
261+
remoteRef:
262+
key: dedicated-chatgpt-login
263+
property: access-token
264+
---
265+
apiVersion: v1
266+
kind: Secret
267+
metadata:
268+
name: chatgpt-auth-runtime
269+
namespace: kagent
270+
annotations:
271+
kagent.dev/chatgpt-auth-seed-secret: chatgpt-auth-seed
272+
type: Opaque
273+
---
274+
apiVersion: api.kagent.dev/v1alpha3
275+
kind: ModelConfig
276+
metadata:
277+
name: chatgpt
278+
namespace: kagent
279+
spec:
280+
provider: OpenAI
281+
model: <model-name>
282+
apiKeySecret: chatgpt-auth-runtime
283+
apiKeySecretKey: access-token
284+
openAI:
285+
authMethod: chatGPT
286+
accountID: <account-id-from-dedicated-login>
287+
```
288+
289+
The operator owns only the source; the refresher owns the runtime credential
290+
values. GitOps manages the runtime envelope and annotation, leaving runtime
291+
data to kagent. Do not configure an operator or GitOps reconciliation to reset
292+
the runtime data. No backend Secret copying or new RBAC is needed. Enable the
293+
existing leader-owned credential controller with the refresh image below.
294+
295+
Each normal uncached sweep attempts bootstrap before refresh. It waits without
296+
mutation when the source is absent or a nonterminal Secret-UID-owned Job exists.
297+
Only a mutable Opaque runtime with no populated data and no refresh state,
298+
claim, hash or retry annotations is eligible; empty unrelated keys are kept.
299+
The source name must be a canonical Secret name, without a namespace prefix,
300+
and cannot reference the runtime itself. All ChatGPT ModelConfigs sharing the
301+
runtime must agree on the account and access key, which must differ from
302+
`auth.json`. The seed must pass the deployed credential-file parser, contain a
303+
nonempty refresh token and matching account identities, and have an access
304+
token with more than ten minutes remaining. Invalid or ambiguous configuration
305+
produces a sanitized controller failure without persisting a rejection or claim;
306+
correcting the source or configuration permits a later sweep to bootstrap.
307+
308+
One resourceVersion-fenced update writes the original file bytes and paired
309+
access token together, preserving the runtime UID and metadata. Bootstrap
310+
neither invokes Codex nor spends refresh tokens. Conflicts and uncertain update
311+
responses wait for the next sweep to reread the destination. Once populated,
312+
the runtime automatically hands off to the existing refresher: seed updates,
313+
controller restarts, expiry and rejection never reseed or overwrite it. A rejected
314+
runtime requires the explicit dedicated re-authentication procedure below.
315+
316+
Without the annotation, the existing manual mode remains available: load the
317+
full `auth.json` and its derived access token into the runtime in one
318+
version-checked update. Do not use client-side apply for credentials, which
319+
retains the credential-bearing manifest in an annotation. Remove the temporary
320+
home after storing the dedicated login. Neither the gateway nor an Actor receives
321+
the source or runtime `auth.json` key; bindings continue to reference only the
322+
runtime access-token key, and Actors retain their synthetic auth file.
323+
324+
Set `config.credentialRefresh.chatgptImage` in the Helm values
325+
(`credential_refresh.chatgpt_image` in the controller configuration) to an
326+
immutable digest of the Codex Harness image, which contains
327+
`/usr/local/bin/kagent-credential-refresh` and the Codex CLI version the Harness
328+
pins. Setting it also renders the `credential-refresh` role: the controller's
329+
other roles no longer carry the Job, ServiceAccount, Role, RoleBinding,
330+
NetworkPolicy and Secret-update permissions the refresh needs.
331+
The worker checks the executable version before requesting refresh. An empty
332+
image setting disables automatic refresh. Leader election must be enabled.
333+
Secrets without an `auth.json` key retain manual access-token rotation.
334+
335+
Refresh state annotations are operation markers, not an enrollment or health
336+
status. A valid pair outside the ten-minute expiry margin is left unchanged,
337+
and successful rotation removes its claim, state, hash, and retry annotations.
338+
Replacing a populated runtime pair does not require an idle state annotation;
339+
the controller schedules that pair from its new expiry without reading the seed.
340+
Backend authentication failures do not currently trigger early refresh, so
341+
rejection before the claimed expiry requires owner reauthentication.
342+
343+
The controller checks access-token expiry every 15 seconds and schedules
344+
refresh ten minutes before expiry, including the gateway's five-minute cache
345+
window. ModelConfigs sharing a Secret share one deterministic Job name and one
346+
access-token key. Jobs use a private memory-backed Codex home, read-only root
347+
filesystem, non-root user, no Pod restarts, no Job retries, and a three-minute
348+
deadline. The Job ServiceAccount can only get/update that Secret through a
349+
Role restricted by `resourceNames`. The controller requires create access to
350+
Roles, RoleBindings, and NetworkPolicies in the watched credential namespaces.
351+
These resources are owned by the Secret and contain no token values.
352+
353+
The Job invokes `codex app-server --strict-config --stdio`, initializes the
354+
protocol, and sends only `account/read` with `refreshToken: true`. In pinned
355+
Codex source, `codex-rs/app-server/src/request_processors/account_processor.rs`
356+
calls `AuthManager::refresh_token` in
357+
`codex-rs/login/src/auth/manager.rs`, which refreshes and persists the official
358+
credential file. This path creates no thread or model turn. `codex login
359+
status` only reads login state and does not perform this refresh. Kagent
360+
implements no OAuth endpoint, grant, or client ID.
361+
362+
The controller claims a Secret with its resourceVersion before creating the
363+
Job. Each Pod must acquire a second version-checked transition before starting
364+
Codex, so duplicate Job execution cannot spend the same credential twice.
365+
After Codex runs, the worker validates that both tokens changed, the account
366+
matches, and the new access-token lifetime exceeds the safety margin. It
367+
commits the full rotated file and derived access token in one Secret update.
368+
Concurrent metadata edits are preserved by re-reading and retrying only
369+
persistence; replacing the credential file or Secret UID cancels that write.
370+
An uncertain successful update is recognized by comparing both stored values
371+
in memory. Token values, upstream errors, stdout, and stderr are never logged.
372+
Codex tracing is disabled and analytics/telemetry export is disabled.
373+
374+
Failures before the Pod acquires its claim retry after a durable jittered
375+
one-to-two-minute delay. Once Codex may have used the token, failures and lost
376+
Jobs require re-authentication instead of replaying it. Pinned `account/read`
377+
suppresses the refresh error category, so even its successful response must
378+
be checked against the rotated file; unchanged credentials are a failure.
379+
This conservatively handles terminal rejection, timeout, and ambiguous
380+
upstream failures. `ModelConfig` reports `ResolvedRefs=False` with reason
381+
`ReauthenticationRequired`. Replacing the dedicated credential pair clears
382+
the failure on reconciliation. Do not clear failure annotations to retry an
383+
old credential. Loss of a Pod after rotation but before Secret persistence
384+
also needs a new dedicated login; no cross-provider atomic commit exists.
385+
386+
The Job's NetworkPolicy permits DNS and TCP 443/6443 (including the login
387+
authority and Kubernetes API, before or after service DNAT) and denies ingress. Standard Kubernetes
388+
NetworkPolicy cannot restrict egress by DNS name; installations requiring
389+
host-only egress must additionally configure their CNI's FQDN policy.
390+
NetworkPolicy requires an enforcing CNI. Actor egress rules remain unchanged.

0 commit comments

Comments
 (0)