Skip to content
Merged
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
104 changes: 97 additions & 7 deletions docs/architecture/credential-injection.md
Original file line number Diff line number Diff line change
Expand Up @@ -130,13 +130,103 @@ The account ID is identifying data retained in the Actor and provenance.
Create a **dedicated** ChatGPT login for the controller. Never seed it from a
developer's existing Codex home: rotating a shared refresh token invalidates
the other login. Use the official pinned Codex CLI with an isolated temporary
`CODEX_HOME` and file credential storage. After interactive login, load its full
`auth.json` into the control-side Secret key `auth.json` and its derived access
token into the ModelConfig's existing `apiKeySecretKey` (normally
`access-token`), in one version-checked update. Do not use client-side apply,
which retains the credential-bearing manifest in an annotation. Remove the
temporary home after seeding. Neither the gateway nor an Actor receives the
`auth.json` key; bindings continue to reference only the access-token key.
`CODEX_HOME` and file credential storage. Store the original full `auth.json`
and its exact paired access token in your secret store. A Secret operator can
publish this pair to a source Secret; kagent automatically bootstraps a separate
runtime Secret when its `kagent.dev/chatgpt-auth-seed-secret` annotation names
that source in the **same namespace**. ModelConfig references the runtime
Secret and its access-token key, with a nonempty `openAI.accountID` matching
both the file and the access token's `https://api.openai.com/auth` /
`chatgpt_account_id` claim.

For example, with an existing External Secrets Operator and SecretStore, keep
the dedicated login pair in two properties of one store entry. Replace the
store, entry, model and account placeholders with your deployment's values:

```yaml
apiVersion: external-secrets.io/v1
kind: ExternalSecret
metadata:
name: chatgpt-auth-seed
namespace: kagent
spec:
refreshInterval: 1h
secretStoreRef:
name: credential-store
kind: SecretStore
target:
name: chatgpt-auth-seed
creationPolicy: Owner
template:
type: Opaque
data:
- secretKey: auth.json
remoteRef:
key: dedicated-chatgpt-login
property: auth.json
- secretKey: access-token
remoteRef:
key: dedicated-chatgpt-login
property: access-token
---
apiVersion: v1
kind: Secret
metadata:
name: chatgpt-auth-runtime
namespace: kagent
annotations:
kagent.dev/chatgpt-auth-seed-secret: chatgpt-auth-seed
type: Opaque
---
apiVersion: api.kagent.dev/v1alpha3
kind: ModelConfig
metadata:
name: chatgpt
namespace: kagent
spec:
provider: OpenAI
model: <model-name>
apiKeySecret: chatgpt-auth-runtime
apiKeySecretKey: access-token
openAI:
authMethod: chatGPT
accountID: <account-id-from-dedicated-login>
```

The operator owns only the source; the refresher owns the runtime credential
values. GitOps manages the runtime envelope and annotation, leaving runtime
data to kagent. Do not configure an operator or GitOps reconciliation to reset
the runtime data. No backend Secret copying or new RBAC is needed. Enable the
existing leader-owned credential controller with the refresh image below.

Each normal uncached sweep attempts bootstrap before refresh. It waits without
mutation when the source is absent or a nonterminal Secret-UID-owned Job exists.
Only a mutable Opaque runtime with no populated data and no refresh state,
claim, hash or retry annotations is eligible; empty unrelated keys are kept.
The source name must be a canonical Secret name, without a namespace prefix,
and cannot reference the runtime itself. All ChatGPT ModelConfigs sharing the
runtime must agree on the account and access key, which must differ from
`auth.json`. The seed must pass the deployed credential-file parser, contain a
nonempty refresh token and matching account identities, and have an access
token with more than ten minutes remaining. Invalid or ambiguous configuration
produces a sanitized controller failure without persisting a rejection or claim;
correcting the source or configuration permits a later sweep to bootstrap.

One resourceVersion-fenced update writes the original file bytes and paired
access token together, preserving the runtime UID and metadata. Bootstrap
neither invokes Codex nor spends refresh tokens. Conflicts and uncertain update
responses wait for the next sweep to reread the destination. Once populated,
the runtime automatically hands off to the existing refresher: seed updates,
controller restarts, expiry and rejection never reseed or overwrite it. A rejected
runtime requires the explicit dedicated re-authentication procedure below.

Without the annotation, the existing manual mode remains available: load the
full `auth.json` and its derived access token into the runtime in one
version-checked update. Do not use client-side apply for credentials, which
retains the credential-bearing manifest in an annotation. Remove the temporary
home after storing the dedicated login. Neither the gateway nor an Actor receives
the source or runtime `auth.json` key; bindings continue to reference only the
runtime access-token key, and Actors retain their synthetic auth file.

Set controller environment variable `KAGENT_CHATGPT_REFRESH_IMAGE` to an
immutable digest of the Codex Harness image containing
Expand Down
129 changes: 129 additions & 0 deletions go/core/internal/controller/chatgptrefresh/bootstrap.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
package chatgptrefresh

import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"strings"
"time"

batchv1 "k8s.io/api/batch/v1"
corev1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/validation"
"sigs.k8s.io/controller-runtime/pkg/client"
)

const SeedSecretAnnotation = "kagent.dev/chatgpt-auth-seed-secret"

type credentialDescriptor struct {
key, account string
keyConflict, accountConflict bool
}

// A populated destination belongs exclusively to rotation, even if its seed
// has changed or disappeared. Bootstrap failures never persist refresh state.
func (c *Controller) bootstrap(ctx context.Context, runtime *corev1.Secret, descriptor credentialDescriptor, now time.Time) (bool, error) {
seedName, optedIn := runtime.Annotations[SeedSecretAnnotation]
if !optedIn {
return false, nil
}
for _, value := range runtime.Data {
if len(value) != 0 {
return false, nil
}
}
for _, value := range runtime.StringData {
if value != "" {
return false, nil
}
}
if runtime.Type != corev1.SecretTypeOpaque || runtime.Immutable != nil && *runtime.Immutable || runtime.DeletionTimestamp != nil {
return true, errCredential
}
for _, annotation := range []string{StateAnnotation, ClaimAnnotation, HashAnnotation, RetryAnnotation} {
if _, exists := runtime.Annotations[annotation]; exists {
return true, errCredential
}
}
if len(validation.IsDNS1123Subdomain(seedName)) != 0 || seedName == runtime.Name ||
len(validation.IsDNS1123Subdomain(runtime.Name)) != 0 ||
len(validation.IsConfigMapKey(descriptor.key)) != 0 || descriptor.key == AuthKey ||
strings.TrimSpace(descriptor.account) == "" || descriptor.account != strings.TrimSpace(descriptor.account) ||
descriptor.keyConflict || descriptor.accountConflict {
return true, errCredential
}
// Inspect all Secret-UID-owned Jobs, including those outside the deterministic
// refresh name. A terminal condition proves execution has settled.
var jobs batchv1.JobList
if c.client.List(ctx, &jobs, client.InNamespace(runtime.Namespace)) != nil {
return true, errOperation
}
for _, job := range jobs.Items {
for _, owner := range job.OwnerReferences {
if owner.APIVersion == "v1" && owner.Kind == "Secret" && owner.UID == runtime.UID && !terminalJob(&job) {
return true, nil
}
}
}
var seed corev1.Secret
if err := c.client.Get(ctx, types.NamespacedName{Namespace: runtime.Namespace, Name: seedName}, &seed); err != nil {
if apierrors.IsNotFound(err) {
return true, nil
}
return true, errOperation
}
if validateSeed(&seed, descriptor, now) != nil {
return true, errCredential
}
if runtime.Data == nil {
runtime.Data = map[string][]byte{}
}
runtime.Data[AuthKey] = bytes.Clone(seed.Data[AuthKey])
runtime.Data[descriptor.key] = bytes.Clone(seed.Data[descriptor.key])
// Exactly one resourceVersion-fenced write. A conflict or ambiguous response
// is re-read by the next ordinary sweep, never retried from this snapshot.
if c.client.Update(ctx, runtime) != nil {
return true, errOperation
}
return true, nil
}

func terminalJob(job *batchv1.Job) bool {
for _, condition := range job.Status.Conditions {
if condition.Status == corev1.ConditionTrue && (condition.Type == batchv1.JobComplete || condition.Type == batchv1.JobFailed) {
return true
}
}
return false
}

func validateSeed(seed *corev1.Secret, descriptor credentialDescriptor, now time.Time) error {
auth, err := readAuth(seed.Data[AuthKey])
if err != nil || auth.Tokens.AccountID != descriptor.account || !bytes.Equal(seed.Data[descriptor.key], []byte(auth.Tokens.Access)) {
return errCredential
}
expires, err := expiry(seed.Data[descriptor.key])
if err != nil || !expires.After(now.Add(safetyMargin)) {
return errCredential
}
// Match the access token's ChatGPT account claim as well as the file account.
// This decodes identity metadata; provider signature verification stays with
// the existing credential consumer.
parts := strings.Split(auth.Tokens.Access, ".")
payload, err := base64.RawURLEncoding.DecodeString(parts[1])
if err != nil {
return errCredential
}
var claims struct {
Auth struct {
AccountID string `json:"chatgpt_account_id"`
} `json:"https://api.openai.com/auth"`
}
if json.Unmarshal(payload, &claims) != nil || claims.Auth.AccountID != descriptor.account {
return errCredential
}
return nil
}
Loading
Loading