Repository navigation
fix: refresh an expired DoiT session before requesting AI access #214
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -26,6 +26,8 @@ import ( | |
| "github.com/anthropics/anthropic-sdk-go" | ||
| "github.com/anthropics/anthropic-sdk-go/option" | ||
| "github.com/rest-sh/restish/cli" | ||
| "github.com/rest-sh/restish/oauth" | ||
| "golang.org/x/oauth2" | ||
| ) | ||
|
|
||
| const ( | ||
|
|
@@ -242,6 +244,69 @@ func aiProvidedEndpoint() (string, error) { | |
| return parsed.String(), nil | ||
| } | ||
|
|
||
| // aiDCIBearer returns the DoiT access token for the vend call, refreshing an | ||
| // expired one first. Every other request gets this from restish's auth | ||
| // handler (authorizationCodeHandler.OnRequest, login_page.go); the vend call | ||
| // bypasses restish, so before this it sent an expired bearer, got a 401, and | ||
| // told the user to log in again although their refresh token was still good. | ||
| // | ||
| // The cache file is re-read first: in a session the commands the model runs | ||
| // are child processes that refresh the token on disk, so the in-memory copy | ||
| // can be stale, and refreshing from it would write an older token over the | ||
| // children's newer one. | ||
| // | ||
| // The refresh never opens a browser. Restish's RefreshTokenSource falls back | ||
| // to its wrapped source when the refresh fails, and in the real handler that | ||
| // source is the interactive PKCE login, which must not start in the middle of | ||
| // a session turn or a piped one-shot. Here the fallback just reports that the | ||
| // session needs a new login. | ||
| func aiDCIBearer() (string, error) { | ||
| if cli.Cache == nil { | ||
| return "", nil | ||
| } | ||
| 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 | ||
|
Comment on lines
+273
to
+277
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🟡 (optional) The comment at lines 273-275 is wrong: Why this was flaggedAn 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 Finding ID: |
||
| } | ||
| source := &oauth.RefreshTokenSource{ | ||
| ClientID: dciOAuthClientID, | ||
| TokenURL: dciOAuthTokenURL, | ||
|
Comment on lines
+279
to
+281
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 Why this was flaggedTrigger: 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 Finding ID: |
||
| 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 { | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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. There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 flaggedTrigger: 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 Verification: At ai_credentials.go:292, aiDCIBearer calls Finding ID: |
||
| return "", errors.New("your DoiT session has expired — run dci login and ask again") | ||
|
Comment on lines
+292
to
+293
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 Why this was flaggedTrigger: Verification: nit. The trigger is an expired Finding ID: |
||
| } | ||
| _, refreshed, found := strings.Cut(probe.Header.Get("Authorization"), " ") | ||
|
Comment on lines
+285
to
+295
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🔴 Users whose DoiT session has expired can now get a Why this was flaggedTrigger: the session's cached Verification: Trigger: the cached Finding ID:
Comment on lines
+267
to
+295
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🟡 (optional) Why this was flaggedIn 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, Finding ID: |
||
| if !found || strings.TrimSpace(refreshed) == "" { | ||
| return "", errors.New("your DoiT session has expired — run dci login and ask again") | ||
| } | ||
| return strings.TrimSpace(refreshed), nil | ||
| } | ||
|
|
||
| // aiNoInteractiveLogin is the fallback when the refresh token cannot renew | ||
| // the session: it fails instead of starting the browser login. | ||
| type aiNoInteractiveLogin struct{} | ||
|
|
||
| func (aiNoInteractiveLogin) Token() (*oauth2.Token, error) { | ||
| return nil, errors.New("the DoiT session cannot be refreshed without signing in again") | ||
| } | ||
|
|
||
| // fetchAIProvidedToken calls the vend endpoint with the same cached bearer | ||
| // every other CLI call uses (dci login and DCI_API_KEY both land in the | ||
| // restish cache slot — see applyAPIKeyOverride, main.go). Error strings are | ||
|
|
@@ -253,9 +318,9 @@ func fetchAIProvidedToken(ctx context.Context) (aiVendedToken, error) { | |
| if err != nil { | ||
| return aiVendedToken{}, err | ||
| } | ||
| bearer := "" | ||
| if cli.Cache != nil { | ||
| bearer = strings.TrimSpace(cli.Cache.GetString("dci:default.token")) | ||
| bearer, err := aiDCIBearer() | ||
| if err != nil { | ||
| return aiVendedToken{}, err | ||
| } | ||
| if bearer == "" { | ||
| return aiVendedToken{}, errors.New("DoiT-provided AI access needs a DoiT sign-in — run dci login first") | ||
|
|
||
There was a problem hiding this comment.
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.