diff --git a/backend/internal/infra/config/config.go b/backend/internal/infra/config/config.go index 0b3629be..6b23bb68 100644 --- a/backend/internal/infra/config/config.go +++ b/backend/internal/infra/config/config.go @@ -26,7 +26,7 @@ const ( ClearanceModeFlareSolverr = "flaresolverr" DefaultStatsigSignerURL = "https://grok.wodf.de/sign" DefaultFlareSolverrURL = "http://flaresolverr:8191" - RecommendedBuildClientVersion = "0.2.110" + RecommendedBuildClientVersion = "0.2.111" RecommendedBuildUserAgent = "grok-shell/" + RecommendedBuildClientVersion + " (linux; x86_64)" maxServerBodyBytes = 256 << 20 diff --git a/backend/internal/infra/config/config_test.go b/backend/internal/infra/config/config_test.go index 7b1e8083..5b4f9da3 100644 --- a/backend/internal/infra/config/config_test.go +++ b/backend/internal/infra/config/config_test.go @@ -101,13 +101,13 @@ func TestBuildResponseHeaderTimeoutIsRuntimeOnly(t *testing.T) { func TestDefaultGrokBuildClientVersionMatchesLocalBaseline(t *testing.T) { build := defaultConfig().Provider.Build - if RecommendedBuildClientVersion != "0.2.110" { + if RecommendedBuildClientVersion != "0.2.111" { t.Fatalf("recommended clientVersion = %q", RecommendedBuildClientVersion) } if build.ClientVersion != RecommendedBuildClientVersion { t.Fatalf("clientVersion = %q", build.ClientVersion) } - if RecommendedBuildUserAgent != "grok-shell/0.2.110 (linux; x86_64)" { + if RecommendedBuildUserAgent != "grok-shell/0.2.111 (linux; x86_64)" { t.Fatalf("recommended userAgent = %q", RecommendedBuildUserAgent) } if build.UserAgent != RecommendedBuildUserAgent { diff --git a/backend/internal/infra/provider/cli/adapter.go b/backend/internal/infra/provider/cli/adapter.go index 3a52dc26..6630dcfc 100644 --- a/backend/internal/infra/provider/cli/adapter.go +++ b/backend/internal/infra/provider/cli/adapter.go @@ -70,10 +70,12 @@ func NewAdapter(cfg Config, cipher *security.Cipher) *Adapter { // The official CLI uses a persistent machine identity. The gateway does not collect machine fingerprints; // instead each backend process generates one random UUID for its lifetime as the Agent identity. agentID := uuid.NewString() - return &Adapter{ - cfg: cfg, http: httpClient, oauth: newOAuthClient(httpClient), cipher: cipher, base: transport, + adapter := &Adapter{ + cfg: cfg, http: httpClient, cipher: cipher, base: transport, agentID: agentID, modelsETags: make(map[uint64]string), compaction: newGatewayCompactionCodec(cipher), logger: slog.Default(), } + adapter.oauth = newOAuthClient(httpClient, func() string { return adapter.config().ClientVersion }) + return adapter } func (a *Adapter) SetLogger(logger *slog.Logger) { diff --git a/backend/internal/infra/provider/cli/oauth.go b/backend/internal/infra/provider/cli/oauth.go index 0d6e65cb..93ead869 100644 --- a/backend/internal/infra/provider/cli/oauth.go +++ b/backend/internal/infra/provider/cli/oauth.go @@ -17,9 +17,10 @@ import ( const ( defaultOAuthClientID = "b1a00492-073a-47ea-816f-4c329264a828" - defaultOAuthScope = "openid profile email offline_access grok-cli:access api:access" + defaultOAuthScope = "openid profile email offline_access grok-cli:access api:access conversations:read conversations:write workspaces:read workspaces:write" defaultDeviceURL = "https://auth.x.ai/oauth2/device/code" defaultTokenURL = "https://auth.x.ai/oauth2/token" + deviceClientSurface = "ui" ) type oauthClient struct { @@ -28,14 +29,15 @@ type oauthClient struct { scope string deviceURL string tokenURL string + version func() string } -func newOAuthClient(httpClient *http.Client) *oauthClient { - return &oauthClient{http: httpClient, clientID: defaultOAuthClientID, scope: defaultOAuthScope, deviceURL: defaultDeviceURL, tokenURL: defaultTokenURL} +func newOAuthClient(httpClient *http.Client, version func() string) *oauthClient { + return &oauthClient{http: httpClient, clientID: defaultOAuthClientID, scope: defaultOAuthScope, deviceURL: defaultDeviceURL, tokenURL: defaultTokenURL, version: version} } func (c *oauthClient) startDevice(ctx context.Context) (provider.DeviceAuthorization, error) { - form := url.Values{"client_id": {c.clientID}, "scope": {c.scope}} + form := url.Values{"client_id": {c.clientID}, "scope": {c.scope}, "referrer": {"grok-build"}} var payload struct { DeviceCode string `json:"device_code"` UserCode string `json:"user_code"` @@ -44,7 +46,7 @@ func (c *oauthClient) startDevice(ctx context.Context) (provider.DeviceAuthoriza Interval int `json:"interval"` ExpiresIn int `json:"expires_in"` } - if err := c.postForm(ctx, c.deviceURL, form, &payload); err != nil { + if err := c.postForm(ctx, c.deviceURL, form, &payload, true); err != nil { return provider.DeviceAuthorization{}, err } if payload.DeviceCode == "" || payload.UserCode == "" || payload.VerificationURI == "" { @@ -61,12 +63,12 @@ func (c *oauthClient) startDevice(ctx context.Context) (provider.DeviceAuthoriza func (c *oauthClient) pollDevice(ctx context.Context, deviceCode string) (tokenPayload, error) { form := url.Values{"grant_type": {"urn:ietf:params:oauth:grant-type:device_code"}, "client_id": {c.clientID}, "device_code": {deviceCode}} - return c.exchange(ctx, form, "") + return c.exchange(ctx, form, "", true) } func (c *oauthClient) refresh(ctx context.Context, refreshToken string) (tokenPayload, error) { form := url.Values{"grant_type": {"refresh_token"}, "client_id": {c.clientID}, "refresh_token": {refreshToken}} - value, err := c.exchange(ctx, form, refreshToken) + value, err := c.exchange(ctx, form, refreshToken, false) if errors.Is(err, provider.ErrAuthorizationDenied) { return tokenPayload{}, &provider.CredentialRefreshError{Code: "refresh_denied", Permanent: true, Cause: err} } @@ -80,13 +82,16 @@ type tokenPayload struct { IDToken string } -func (c *oauthClient) exchange(ctx context.Context, form url.Values, fallbackRefresh string) (tokenPayload, error) { +func (c *oauthClient) exchange(ctx context.Context, form url.Values, fallbackRefresh string, deviceFlow bool) (tokenPayload, error) { req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.tokenURL, strings.NewReader(form.Encode())) if err != nil { return tokenPayload{}, err } req.Header.Set("Content-Type", "application/x-www-form-urlencoded") req.Header.Set("Accept", "application/json") + if deviceFlow { + c.applyDeviceHeaders(req) + } resp, err := c.http.Do(req) if err != nil { return tokenPayload{}, err @@ -143,13 +148,16 @@ func parseOAuthRetryAfter(value string) time.Duration { return 0 } -func (c *oauthClient) postForm(ctx context.Context, endpoint string, form url.Values, output any) error { +func (c *oauthClient) postForm(ctx context.Context, endpoint string, form url.Values, output any, deviceFlow bool) error { req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, strings.NewReader(form.Encode())) if err != nil { return err } req.Header.Set("Content-Type", "application/x-www-form-urlencoded") req.Header.Set("Accept", "application/json") + if deviceFlow { + c.applyDeviceHeaders(req) + } resp, err := c.http.Do(req) if err != nil { return err @@ -165,6 +173,16 @@ func (c *oauthClient) postForm(ctx context.Context, endpoint string, form url.Va return json.Unmarshal(body, output) } +func (c *oauthClient) applyDeviceHeaders(req *http.Request) { + if c.version != nil { + if version := strings.TrimSpace(c.version()); version != "" { + req.Header.Set("x-grok-client-version", version) + } + } + // The management UI presents the verification URL and code to a human. + req.Header.Set("x-grok-client-surface", deviceClientSurface) +} + func firstNonEmpty(values ...string) string { for _, value := range values { if strings.TrimSpace(value) != "" { diff --git a/backend/internal/infra/provider/cli/oauth_test.go b/backend/internal/infra/provider/cli/oauth_test.go index ffcb1f08..4ae74b78 100644 --- a/backend/internal/infra/provider/cli/oauth_test.go +++ b/backend/internal/infra/provider/cli/oauth_test.go @@ -12,6 +12,71 @@ import ( "github.com/chenyme/grok2api/backend/internal/infra/provider" ) +func TestOAuthDeviceFlowMatchesOfficialWireContract(t *testing.T) { + version := "0.2.111" + requests := 0 + tokenPolls := 0 + httpClient := &http.Client{Transport: roundTripFunc(func(request *http.Request) (*http.Response, error) { + requests++ + if request.Header.Get("x-grok-client-version") != version { + t.Fatalf("client version = %q, want %q", request.Header.Get("x-grok-client-version"), version) + } + if request.Header.Get("x-grok-client-surface") != deviceClientSurface { + t.Fatalf("client surface = %q", request.Header.Get("x-grok-client-surface")) + } + if err := request.ParseForm(); err != nil { + t.Fatal(err) + } + switch request.URL.Path { + case "/oauth2/device/code": + if request.Form.Get("client_id") != defaultOAuthClientID || request.Form.Get("scope") != defaultOAuthScope || request.Form.Get("referrer") != "grok-build" { + t.Fatalf("device form = %v", request.Form) + } + return oauthResponse(http.StatusOK, `{"device_code":"device","user_code":"ABCD-EFGH","verification_uri":"https://auth.x.ai/activate","verification_uri_complete":"https://auth.x.ai/activate?user_code=ABCD-EFGH","interval":5,"expires_in":1800}`), nil + case "/oauth2/token": + if request.Form.Get("grant_type") != "urn:ietf:params:oauth:grant-type:device_code" || request.Form.Get("client_id") != defaultOAuthClientID || request.Form.Get("device_code") != "device" { + t.Fatalf("token form = %v", request.Form) + } + tokenPolls++ + if tokenPolls == 1 { + return oauthResponse(http.StatusBadRequest, `{"error":"authorization_pending"}`), nil + } + return oauthResponse(http.StatusOK, `{"access_token":"access","refresh_token":"refresh","id_token":"id","expires_in":3600}`), nil + default: + t.Fatalf("unexpected OAuth path %q", request.URL.Path) + return nil, nil + } + })} + client := newOAuthClient(httpClient, func() string { return version }) + + authorization, err := client.startDevice(context.Background()) + if err != nil { + t.Fatal(err) + } + if authorization.DeviceCode != "device" || authorization.UserCode != "ABCD-EFGH" || authorization.Interval != 5*time.Second || authorization.ExpiresIn != 30*time.Minute { + t.Fatalf("authorization = %#v", authorization) + } + + version = "0.2.112" + if _, err := client.pollDevice(context.Background(), authorization.DeviceCode); !errors.Is(err, provider.ErrAuthorizationPending) { + t.Fatalf("poll error = %v", err) + } + tokens, err := client.pollDevice(context.Background(), authorization.DeviceCode) + if err != nil { + t.Fatal(err) + } + if tokens.AccessToken != "access" || tokens.RefreshToken != "refresh" || tokens.IDToken != "id" || time.Until(tokens.ExpiresAt) < 59*time.Minute { + t.Fatalf("tokens = %#v", tokens) + } + if requests != 3 { + t.Fatalf("requests = %d, want 3", requests) + } +} + +func oauthResponse(status int, body string) *http.Response { + return &http.Response{StatusCode: status, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body))} +} + func TestOAuthRefreshClassifiesPermanentAndTransientFailures(t *testing.T) { tests := []struct { name string @@ -27,6 +92,9 @@ func TestOAuthRefreshClassifiesPermanentAndTransientFailures(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { httpClient := &http.Client{Transport: roundTripFunc(func(request *http.Request) (*http.Response, error) { + if request.Header.Get("x-grok-client-version") != "" || request.Header.Get("x-grok-client-surface") != "" { + t.Fatalf("refresh request unexpectedly included device headers: %v", request.Header) + } if request.FormValue("grant_type") != "refresh_token" || request.FormValue("refresh_token") != "refresh" { t.Fatalf("form = %#v", request.Form) } @@ -36,7 +104,7 @@ func TestOAuthRefreshClassifiesPermanentAndTransientFailures(t *testing.T) { } return &http.Response{StatusCode: test.status, Header: header, Body: io.NopCloser(strings.NewReader(test.body)), Request: request}, nil })} - client := newOAuthClient(httpClient) + client := newOAuthClient(httpClient, func() string { return "0.2.111" }) client.tokenURL = "https://auth.x.ai/oauth2/token" _, err := client.refresh(context.Background(), "refresh") var refreshErr *provider.CredentialRefreshError @@ -49,3 +117,19 @@ func TestOAuthRefreshClassifiesPermanentAndTransientFailures(t *testing.T) { }) } } + +func TestOAuthScopeMatchesOfficialPersonalAccountContract(t *testing.T) { + values := strings.Fields(defaultOAuthScope) + want := []string{ + "openid", "profile", "email", "offline_access", "grok-cli:access", "api:access", + "conversations:read", "conversations:write", "workspaces:read", "workspaces:write", + } + if len(values) != len(want) { + t.Fatalf("scope count = %d, want %d: %v", len(values), len(want), values) + } + for index := range want { + if values[index] != want[index] { + t.Fatalf("scope[%d] = %q, want %q", index, values[index], want[index]) + } + } +} diff --git a/backend/internal/transport/http/settings/security_test.go b/backend/internal/transport/http/settings/security_test.go index 83ca22a8..a2c5fb3b 100644 --- a/backend/internal/transport/http/settings/security_test.go +++ b/backend/internal/transport/http/settings/security_test.go @@ -47,9 +47,9 @@ func TestSettingsResponseIncludesBuildTokenAuth(t *testing.T) { func TestSettingsResponseIncludesRecommendedBuildBaseline(t *testing.T) { response := newSettingsResponse(settingsapp.Snapshot{RecommendedProviderBuild: settingsapp.ProviderBuildRecommendation{ - ClientVersion: "0.2.110", UserAgent: "grok-shell/0.2.110 (linux; x86_64)", + ClientVersion: "0.2.111", UserAgent: "grok-shell/0.2.111 (linux; x86_64)", }}) - if response.RecommendedProviderBuild.ClientVersion != "0.2.110" || response.RecommendedProviderBuild.UserAgent == "" { + if response.RecommendedProviderBuild.ClientVersion != "0.2.111" || response.RecommendedProviderBuild.UserAgent == "" { t.Fatalf("recommended build = %#v", response.RecommendedProviderBuild) } }