Skip to content

fix: refresh an expired DoiT session before requesting AI access - #214

Open
apgiorgi wants to merge 1 commit into
mainfrom
apgiorgi/ai-vend-refresh
Open

apgiorgi wants to merge 1 commit into
mainfrom
apgiorgi/ai-vend-refresh

Conversation

@apgiorgi

Copy link
Copy Markdown
Collaborator

Problem

With DoiT-provided access, dci ai asks the DoiT API for a temporary Anthropic token. That request read the cached DoiT access token straight from the cache and never refreshed it, unlike every other request, which goes through restish's auth handler. Once the token expired (after an hour), dci ai failed with "your DoiT session has expired — run dci login", although the stored refresh token was still valid. Running any ordinary command refreshed it and made dci ai work again.

Fix

  • aiDCIBearer (ai_credentials.go) re-reads the cache file, then refreshes an expired token through restish's oauth.TokenHandler + RefreshTokenSource and writes it back to the cache.
  • The fallback is a source that always errors, so a failed or missing refresh never opens the browser login in the middle of a session turn or a piped one-shot. It shows the existing "run dci login" message instead.
  • Re-reading the cache picks up tokens that commands the AI ran (child processes) already refreshed on disk, instead of overwriting them.
  • No recorded expiry and DCI_API_KEY both send the token unchanged, as before.
  • The OAuth client id and token URL in writeConfig are now shared constants, because restish keeps its parsed API configs private.

Known limits (not fixed here)

  • Restish's token request uses http.DefaultClient with no timeout or context, so a hung token endpoint stalls the turn.
  • After the session refreshes the token itself, its in-memory copy shadows later refreshes on disk by child processes. Its own token stays valid until it expires, but if the server rotates refresh tokens, the next refresh could fail and ask for dci login.

Test plan

  • Unit tests against a stand-in token endpoint, seven cases: an expired token that refreshes (the new bearer reaches the AI access request and is written to the cache); a rejected refresh; no refresh token (never dials); a valid token reused; no recorded expiry; a token renewed on disk by another process; DCI_API_KEY.
  • go vet ., go test .
  • Live: set the real cache's expiry to the past, then dci ai --quiet with this build answered and the cached expiry moved forward.

The DoiT-provided AI access request read the cached DoiT token directly
and never ran restish's auth handler, so once the access token expired it
got a 401 and told the user to run dci login, even though the stored
refresh token was still valid. Refresh the token first, the same way other
requests do, without ever falling back to the browser login.

@taltultc taltultc left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The test covers the refreshed bearer reaching the AI access request. Please address the two inline findings before merge.

Comment thread ai_credentials.go
if cli.Cache == nil {
return "", nil
}
reloadCredentialCache()

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 Credential cache

After the parent refreshes once, Viper keeps returning its bearer even when a child updates the cache. This also leaves the old bearer in use after logout or an account switch. Please honor the disk change and add a regression test for that sequence.

Comment thread ai_credentials.go
if err != nil {
return "", err
}
if err := oauth.TokenHandler(source, key, probe); err != nil {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 Refresh cancellation

A stalled token endpoint keeps the turn waiting even after cancellation. Please pass the turn context to the refresh HTTP request and give it a timeout.

@claude claude Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Beyond the inline findings, I also checked whether hard-coding dci:default in aiDCIBearer breaks users on a non-default restish profile. It doesn't: main.go pins rsh-profile to "default" (line 785) and rejects --profile/--rsh-profile arguments (line 935), so dci:default is the only cache key a session can have.

Extended reasoning...

One candidate was ruled out: the hard-coded dci:default key can't miss a profile's token, because the CLI forces the restish profile to "default" and rejects the profile flags.

Findings marked 🟡 are optional suggestions and need no follow-up push.

Comment thread ai_credentials.go
if err != nil {
return "", err
}
if err := oauth.TokenHandler(source, key, probe); err != nil {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 After one in-session refresh, a later /login to another account or a logout in a dci ai session is ignored by that session, and can be undone on disk. oauth.TokenHandler stores the refreshed token with cli.Cache.Set, which is viper's override layer. reloadCredentialCache (ReadInConfig) never replaces override values. So the stale token, refresh token and expiry shadow whatever a child process writes to cache.json. Fix: never leave refreshed credentials in cli.Cache's override layer. For example, run TokenHandler against a scratch viper loaded from the cache file, then reload cli.Cache. Keep the DCI_API_KEY short-circuit first, since applyAPIKeyAuth relies on overrides.

Why this was flagged

Trigger: a dci ai session whose bearer expires (session longer than an hour, or started with an expired token). fetchAIProvidedToken -> aiDCIBearer -> oauth.TokenHandler (ai_credentials.go:292) refreshes and calls cli.Cache.Set on dci:default.token/.refresh/.expires. Those values now sit in viper's override layer. The user then runs /login as a different account or dci logout as a child process. Afterwards aiModel.refreshAuthState (ai_tui.go:722) calls reloadCredentialCache (main.go:2049). ReadInConfig only replaces the config layer, so cachedTokenClaims, the banner and aiDCIBearer keep returning the old account's token. When that token expires, TokenHandler refreshes with the old refresh token, and WriteConfig (which writes AllSettings, overrides included) puts the old account's credentials back in cache.json. On the base branch the session never Set these keys, so the reload after a login or logout picked up the child's credentials. The PR's known-limits note only mentions refresh-token rotation, not identity changes or logout.

Verification: At ai_credentials.go:292, aiDCIBearer calls oauth.TokenHandler(source, key, probe), which stores the refreshed token with cli.Cache.Set, and viper's Set writes to the override layer. reloadCredentialCache (main.go:2049-2052) only calls cli.Cache.ReadInConfig(), which never clears overrides. Before this change the session process never called cli.Cache.Set on dci:default.

Finding ID: f-b2080a47

Comment thread ai_credentials.go
Comment on lines +285 to +295
// TokenHandler reuses the cached token while it is valid, otherwise
// refreshes it and writes the new one back to the cache, then sets the
// Authorization header on the request it is given.
probe, err := http.NewRequest(http.MethodPost, "https://dci.invalid/", nil)
if err != nil {
return "", err
}
if err := oauth.TokenHandler(source, key, probe); err != nil {
return "", errors.New("your DoiT session has expired — run dci login and ask again")
}
_, refreshed, found := strings.Cut(probe.Header.Get("Authorization"), " ")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 Users whose DoiT session has expired can now get a dci ai turn that hangs with no limit and cannot be cancelled when the token endpoint stalls. The refresh at line 295 goes through restish's oauth.TokenHandler, which posts with http.DefaultClient: no timeout and no context. aiDCIBearer also never receives the ctx that fetchAIProvidedToken gets. Fix: bound the refresh like the vend call, for example run TokenHandler in a goroutine and select on ctx.Done() and a 15s timer, then return the existing "run dci login" error. [also at: ai_credentials.go:292 - If the token endpoint stalls, an AI session hangs with no time limit. Esc cannot cancel the turn, and only quitting dci ai recovers.]

Why this was flagged

Trigger: the session's cached dci:default.expires has passed and console.doit.com/api/auth/token accepts the connection but never answers (or the network black-holes it). fetchAIProvidedToken(ctx) (ai_credentials.go:316) calls aiDCIBearer() (line 321) without ctx. That reaches oauth.TokenHandler -> RefreshTokenSource.Token, and restish v0.21.2 does that POST on http.DefaultClient with no deadline. The vend request right after it is bounded by &http.Client{Timeout: 15 * time.Second} and NewRequestWithContext(ctx, ...) (lines 328-334), but the refresh is not, so the turn blocks forever and cancelling ctx does not unblock it. On the base branch there was no network call before the vend: an expired token got a 401 within 15s and a "run dci login" message. The PR description lists this as a known limit. In practice it makes a new unbounded call on the turn path that the vend call was deliberately written to avoid, and a fix inside this PR is possible.

Verification: Trigger: the cached dci:default.expires has passed and the token endpoint accepts the connection but never responds. fetchAIProvidedToken(ctx context.Context) (ai_credentials.go:316) calls bearer, err := aiDCIBearer() (line 321). ctx is never passed in. The vend call right after is bounded. The refresh is not. Now it can hang with no limit.

Finding ID: f-13046a7a

Comment thread ai_credentials.go
Comment on lines +279 to +281
source := &oauth.RefreshTokenSource{
ClientID: dciOAuthClientID,
TokenURL: dciOAuthTokenURL,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 (optional) Users whose apis.json sets its own OAuth token_url or client_id get no AI refresh. Their refresh token goes to production console.doit.com instead of their own endpoint. aiDCIBearer always refreshes with the dciOAuthClientID and dciOAuthTokenURL constants. restish's handler (login_page.go:697-719) reads token_url, client_id, scopes and extra params from the apis.json profile, and ensureConfig never rewrites an existing file. Fix: build the RefreshTokenSource from the dci:default profile's auth params in apis.json, the same file readConfigBase parses, and fall back to the constants only when the params are missing. [also at: ai_credentials.go:284 - pre-existing. Users whose apis.json names a different OAuth client, token URL or scopes still get "run dci login" from dci ai after expiry, and their refresh token now goes to the production Console. aiDCIBearer builds its RefreshTokenSource from the dciOAuthClientID and dciOAuthTokenURL constants.]

Why this was flagged

Trigger: a user's apis.json auth block differs from the constants at main.go:593-597, for example a hand edit or a dev environment with its own console. ensureConfig (main.go:178-194) keeps an existing file and never calls writeConfig, so those values stay authoritative. authorizationCodeHandler.OnRequest (login_page.go:697-719) refreshes every ordinary command against params["token_url"] and params["client_id"], with Scopes and EndpointParams. aiDCIBearer (ai_credentials.go:279-284) ignores all of these and sends the cached refresh token to the hard-coded https://console.doit.com/api/auth/token with client "cli". That endpoint rejects it, so the user still gets "your DoiT session has expired — run dci login and ask again" every hour. Ordinary commands keep working, which is the bug this PR set out to fix. On top of that, the refresh token now leaks to a host that did not issue it, which the base never did because the base did not refresh at all.

Verification: Trigger: the user's existing apis.json has a dci.profiles.default.auth.params token_url or client_id that differs from the constants. aiDCIBearer (ai_credentials.go, new code) builds the refresh source only from the constants, with no Scopes or EndpointParams. ensureConfig (main.go:178-194) keeps an existing apis.json.

Finding ID: f-e9481d31

Comment thread ai_credentials.go
Comment on lines +292 to +293
if err := oauth.TokenHandler(source, key, probe); err != nil {
return "", errors.New("your DoiT session has expired — run dci login and ask again")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 (optional) Users with an expired session who hit a network failure, token-endpoint outage or cache write error are now told to run dci login, even when signing in again cannot help. Line 292 throws away the error from oauth.TokenHandler and always returns "your DoiT session has expired — run dci login and ask again". Fix: keep that message only for a refresh the server actually refused. Report transport errors, 5xx replies and WriteConfig failures as their own errors. A cache write error can be told apart by a sentinel that aiNoInteractiveLogin sets. Telling network failures apart needs the refresh request made directly.

Why this was flagged

Trigger: dci:default.expires is in the past and a refresh token is stored. fetchAIProvidedToken calls aiDCIBearer (ai_credentials.go:321), which calls oauth.TokenHandler (ai_credentials.go:292). Restish's RefreshTokenSource handles a failed token request (DNS or proxy failure, connection refused, or a 5xx) by falling back to aiNoInteractiveLogin, which fails. TokenHandler can also fail after a successful refresh when cli.Cache.WriteConfig cannot write cache.json. Every one of these is mapped to the same "your DoiT session has expired — run dci login and ask again" at ai_credentials.go:293, and the underlying error is dropped. On the base branch, an offline user with an expired token got "could not reach the DoiT API for AI access: ..." from the vend call (ai_credentials.go:337), which names the real cause. aiProvidedTokenSource.token only hides this while a previously vended token is still valid (ai_credentials.go:193).

Verification: nit. The trigger is an expired dci:default.expires with a stored refresh token, while the token endpoint is unreachable or returning 5xx, or while cache.json cannot be written. The fallback source aiNoInteractiveLogin.Token() always errors. Now an outage is reported as an expired session. The impact is a misleading error message only.

Finding ID: f-1528b50f

Comment thread ai_credentials.go
Comment on lines +273 to +277
// No recorded expiry means nothing to refresh against; send the token
// as-is and let the API judge it. DCI_API_KEY lands here with a far-future
// expiry (applyAPIKeyAuth), so it is reused without a refresh too.
if cli.Cache.GetTime(key + ".expires").IsZero() {
return bearer, nil

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 (optional) The comment at lines 273-275 is wrong: DCI_API_KEY callers skip the zero-expiry early return and go through oauth.TokenHandler. applyAPIKeyAuth sets expires to "9999-12-31T23:59:59Z" (main.go:1961), so GetTime is not zero at line 276. The API key then reaches a RefreshTokenSource holding the production token URL, and the code depends on ReuseTokenSource never calling it. Fix: return early when os.Getenv(apiKeyEnvName) is set, or reword the comment to match the real path.

Why this was flagged

An API-key user sets DCI_API_KEY, and applyAPIKeyAuth puts a far-future expiry in the cache override (main.go:1961). At ai_credentials.go:276 the expiry is not zero, so execution builds the RefreshTokenSource (lines 279-284) and calls oauth.TokenHandler (line 295). The comment claims the opposite: that DCI_API_KEY lands on the early return. This works today only because the cached token is valid until year 9999 and ReuseTokenSource returns it unchanged. If restish's expiry parsing or the override's type ever changes, the API key goes through the refresh path and the user is told to run dci login, which cannot help an API-key user. Remedy: add an explicit API-key early return before line 276.

Verification: Trigger: DCI_API_KEY is set. The comment is wrong, but nothing breaks. applyAPIKeyAuth runs cli.Cache.Set(key+".expires", "9999-12-31T23:59:59Z") (main.go:1961). So cli.Cache.GetTime(key + ".expires").IsZero() in aiDCIBearer is false, and an API-key caller never takes the early return.

Finding ID: f-6e1b94f0

Comment thread ai_credentials.go
Comment on lines +267 to +295
reloadCredentialCache()
const key = "dci:default"
bearer := strings.TrimSpace(cli.Cache.GetString(key + ".token"))
if bearer == "" {
return "", nil
}
// No recorded expiry means nothing to refresh against; send the token
// as-is and let the API judge it. DCI_API_KEY lands here with a far-future
// expiry (applyAPIKeyAuth), so it is reused without a refresh too.
if cli.Cache.GetTime(key + ".expires").IsZero() {
return bearer, nil
}
source := &oauth.RefreshTokenSource{
ClientID: dciOAuthClientID,
TokenURL: dciOAuthTokenURL,
RefreshToken: cli.Cache.GetString(key + ".refresh"),
TokenSource: aiNoInteractiveLogin{},
}
// TokenHandler reuses the cached token while it is valid, otherwise
// refreshes it and writes the new one back to the cache, then sets the
// Authorization header on the request it is given.
probe, err := http.NewRequest(http.MethodPost, "https://dci.invalid/", nil)
if err != nil {
return "", err
}
if err := oauth.TokenHandler(source, key, probe); err != nil {
return "", errors.New("your DoiT session has expired — run dci login and ask again")
}
_, refreshed, found := strings.Cut(probe.Header.Get("Authorization"), " ")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 (optional) dci ai sessions can now crash with a fatal concurrent map access when a vend refresh overlaps a TUI cache read. On the base branch the vend goroutine only read the cache. aiDCIBearer now calls ReadInConfig (line 267), and on expiry oauth.TokenHandler (line 295) calls cli.Cache.Set and WriteConfig. Both run on the streamer goroutine while the Bubble Tea goroutine can call cachedTokenClaims (main.go:2042) at the same time. Fix: serialize every cli.Cache access behind one mutex shared by the vend path and the TUI, or run the reload and refresh on the TUI goroutine and pass the bearer in.

Why this was flagged

In provided mode, the streamer closure (ai_credentials.go:81) calls source.token, then fetchAIProvidedToken, then aiDCIBearer, all on the session goroutine. At the same time the TUI goroutine reads the same *viper.Viper through contextLabel, which calls cachedTokenIsDoer (ai_tui.go:475; reached from the aiCustomerNameMsg handler at ai_tui.go:665 and the /clear path at ai_tui.go:1655), through modelInfoText (ai_tui.go:1916) and through refreshAuthState (ai_tui.go:723). viper is not goroutine-safe. ReadInConfig swaps v.config, and TokenHandler's Set writes nested override maps, so a parallel GetString can hit Go's fatal "concurrent map read and map write" and kill the process. On the base branch the vend path only called GetString, and two concurrent reads are safe. The dismissal called the overlap speculative, but an async customer-name result or a /model command arriving during a turn that refreshes an expired token is enough to trigger it. Remedy: guard cache access with one shared lock.

Verification: On expiry, oauth.TokenHandler (ai_credentials.go:295) writes the refreshed token back with cli.Cache.Set, then calls WriteConfig. There is no lock around cli.Cache anywhere. A read that lands during the map write is a Go runtime fatal "concurrent map read and map write", which kills the session. On the base branch the session goroutine only called GetString (read with read is safe).

Finding ID: f-86c8a8ad

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants