diff --git a/ai_credentials.go b/ai_credentials.go index 41f2d4f..096b0d2 100644 --- a/ai_credentials.go +++ b/ai_credentials.go @@ -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 + } + 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"), " ") + 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") diff --git a/ai_credentials_test.go b/ai_credentials_test.go index fcfa60a..c2da85a 100644 --- a/ai_credentials_test.go +++ b/ai_credentials_test.go @@ -6,15 +6,19 @@ package main import ( "context" + "encoding/json" "errors" "fmt" "net/http" "net/http/httptest" + "os" + "path/filepath" "strings" "testing" "time" "github.com/rest-sh/restish/cli" + "github.com/spf13/viper" ) // seedCachedToken swaps in a fresh restish token cache holding token — the @@ -298,3 +302,151 @@ func TestAILooksLikeAuthError(t *testing.T) { t.Fatal("rate limit misread as auth error") } } + +// seedCacheFile backs cli.Cache with a real cache file holding the given +// dci:default entry, the way a signed-in CLI has it on disk. The refresh path +// re-reads that file and writes refreshed tokens back to it, which an +// in-memory-only cache cannot exercise. +func seedCacheFile(t *testing.T, entry map[string]any) string { + t.Helper() + path := filepath.Join(t.TempDir(), "cache.json") + writeCacheFile(t, path, entry) + old := cli.Cache + cli.Cache = viper.New() + cli.Cache.SetConfigFile(path) + if err := cli.Cache.ReadInConfig(); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { cli.Cache = old }) + return path +} + +func writeCacheFile(t *testing.T, path string, entry map[string]any) { + t.Helper() + data, err := json.Marshal(map[string]any{"dci:default": entry}) + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, data, 0o600); err != nil { + t.Fatal(err) + } +} + +// fakeTokenEndpoint stands in for the Console token URL; handler answers the +// refresh request. It returns a pointer to the request count. +func fakeTokenEndpoint(t *testing.T, handler http.HandlerFunc) *int { + t.Helper() + calls := 0 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + calls++ + handler(w, r) + })) + t.Cleanup(server.Close) + oldURL := dciOAuthTokenURL + dciOAuthTokenURL = server.URL + t.Cleanup(func() { dciOAuthTokenURL = oldURL }) + return &calls +} + +func TestAIDCIBearerRefresh(t *testing.T) { + past := time.Now().Add(-time.Hour).UTC().Format(time.RFC3339) + future := time.Now().Add(time.Hour).UTC().Format(time.RFC3339) + + t.Run("expired token is refreshed before the vend call", func(t *testing.T) { + path := seedCacheFile(t, map[string]any{"token": "stale-bearer", "type": "Bearer", "expires": past, "refresh": "refresh-1"}) + calls := fakeTokenEndpoint(t, func(w http.ResponseWriter, r *http.Request) { + _ = r.ParseForm() + if r.Form.Get("grant_type") != "refresh_token" || r.Form.Get("refresh_token") != "refresh-1" || r.Form.Get("client_id") != dciOAuthClientID { + t.Errorf("refresh form = %v", r.Form) + } + fmt.Fprint(w, `{"access_token":"fresh-bearer","token_type":"Bearer","expires_in":3600}`) + }) + vend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if got := r.Header.Get("Authorization"); got != "Bearer fresh-bearer" { + t.Errorf("vend Authorization = %q, want the refreshed bearer", got) + } + fmt.Fprint(w, `{"access_token":"sk-ant-oat01-test","expires_in":1800}`) + })) + defer vend.Close() + t.Setenv(aiProvidedURLEnvName, vend.URL) + if _, err := fetchAIProvidedToken(context.Background()); err != nil { + t.Fatal(err) + } + if *calls != 1 { + t.Fatalf("token endpoint calls = %d, want 1", *calls) + } + data, _ := os.ReadFile(path) + if !strings.Contains(string(data), "fresh-bearer") { + t.Fatalf("refreshed token not written back to the cache file: %s", data) + } + }) + + t.Run("failed refresh asks for a login and never goes interactive", func(t *testing.T) { + seedCacheFile(t, map[string]any{"token": "stale-bearer", "expires": past, "refresh": "revoked"}) + calls := fakeTokenEndpoint(t, func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusBadRequest) + }) + _, err := aiDCIBearer() + if err == nil || !strings.Contains(err.Error(), "dci login") { + t.Fatalf("expected a dci login error, got %v", err) + } + if *calls != 1 { + t.Fatalf("token endpoint calls = %d, want 1", *calls) + } + }) + + t.Run("no refresh token asks for a login without dialing", func(t *testing.T) { + seedCacheFile(t, map[string]any{"token": "stale-bearer", "expires": past}) + calls := fakeTokenEndpoint(t, func(w http.ResponseWriter, r *http.Request) {}) + if _, err := aiDCIBearer(); err == nil || !strings.Contains(err.Error(), "dci login") { + t.Fatalf("expected a dci login error, got %v", err) + } + if *calls != 0 { + t.Fatalf("token endpoint calls = %d, want 0", *calls) + } + }) + + t.Run("valid token is reused without a refresh", func(t *testing.T) { + seedCacheFile(t, map[string]any{"token": "good-bearer", "expires": future, "refresh": "refresh-1"}) + calls := fakeTokenEndpoint(t, func(w http.ResponseWriter, r *http.Request) {}) + got, err := aiDCIBearer() + if err != nil || got != "good-bearer" || *calls != 0 { + t.Fatalf("got %q, err %v, refresh calls %d", got, err, *calls) + } + }) + + t.Run("no recorded expiry sends the token as-is", func(t *testing.T) { + seedCacheFile(t, map[string]any{"token": "raw-bearer"}) + calls := fakeTokenEndpoint(t, func(w http.ResponseWriter, r *http.Request) {}) + got, err := aiDCIBearer() + if err != nil || got != "raw-bearer" || *calls != 0 { + t.Fatalf("got %q, err %v, refresh calls %d", got, err, *calls) + } + }) + + t.Run("a token a child process refreshed on disk is picked up", func(t *testing.T) { + path := seedCacheFile(t, map[string]any{"token": "stale-bearer", "expires": past, "refresh": "refresh-1"}) + // A command the model ran refreshed the session after this process + // loaded the cache. + writeCacheFile(t, path, map[string]any{"token": "child-bearer", "expires": future, "refresh": "refresh-2"}) + calls := fakeTokenEndpoint(t, func(w http.ResponseWriter, r *http.Request) {}) + got, err := aiDCIBearer() + if err != nil || got != "child-bearer" || *calls != 0 { + t.Fatalf("got %q, err %v, refresh calls %d", got, err, *calls) + } + }) + + t.Run("DCI_API_KEY is never refreshed", func(t *testing.T) { + seedCacheFile(t, map[string]any{"token": "x"}) + t.Setenv(apiKeyEnvName, "api-key-token") + oldProfile := viper.GetString("rsh-profile") + viper.Set("rsh-profile", "default") // restish's default; unset in tests + t.Cleanup(func() { viper.Set("rsh-profile", oldProfile) }) + applyAPIKeyAuth() + calls := fakeTokenEndpoint(t, func(w http.ResponseWriter, r *http.Request) {}) + got, err := aiDCIBearer() + if err != nil || got != "api-key-token" || *calls != 0 { + t.Fatalf("got %q, err %v, refresh calls %d", got, err, *calls) + } + }) +} diff --git a/main.go b/main.go index 863d872..418eeb2 100644 --- a/main.go +++ b/main.go @@ -584,6 +584,18 @@ func applyAPIBaseOverride(realConfigDir string, args []string) (cleanup func()) } } +// The DoiT Console OAuth client written into apis.json. Shared with the AI +// vend call (ai_credentials.go), which refreshes the session outside +// restish's request path and so cannot read these back from the profile — +// restish keeps its parsed API configs private. dciOAuthTokenURL is a var +// only so tests can point the refresh at an httptest server. +const ( + dciOAuthAuthorizeURL = "https://console.doit.com/sign-in/oauth" + dciOAuthClientID = "cli" +) + +var dciOAuthTokenURL = "https://console.doit.com/api/auth/token" + func writeConfig(configFile, base string) error { config := map[string]interface{}{ "$schema": "https://rest.sh/schemas/apis.json", @@ -594,9 +606,9 @@ func writeConfig(configFile, base string) error { "auth": map[string]interface{}{ "name": "oauth-authorization-code", "params": map[string]interface{}{ - "authorize_url": "https://console.doit.com/sign-in/oauth", - "client_id": "cli", - "token_url": "https://console.doit.com/api/auth/token", + "authorize_url": dciOAuthAuthorizeURL, + "client_id": dciOAuthClientID, + "token_url": dciOAuthTokenURL, }, }, },