mirror of
https://github.com/chenyme/grok2api.git
synced 2026-12-06 08:02:14 +00:00
fix: keep SSO-to-Build device flow on auth.x.ai
This commit is contained in:
1 parent
ecf070ba42
commit
2ae101f431
3 files changed
+83
-205
No files matched your search
@@ -435,31 +435,6 @@ func (m *Manager) UpdateClearanceConfig(value ClearanceConfig) {
|
||||
m.clearanceMu.Unlock()
|
||||
}
|
||||
|
||||
// SolveClearance 通过已配置的 FlareSolverr 为指定目标 URL 现解 Cloudflare Clearance。
|
||||
// 结果不写节点缓存也不持久化,避免与节点既有 Clearance(如 grok.com)互相覆盖;
|
||||
// 调用方必须通过同一 proxyURL 出口发送后续请求,保证 Clearance 与出口 IP 一致。
|
||||
func (m *Manager) SolveClearance(ctx context.Context, proxyURL, targetURL string) (string, string, error) {
|
||||
m.clearanceMu.Lock()
|
||||
cfg := m.clearanceConfig
|
||||
solver := m.solver
|
||||
m.clearanceMu.Unlock()
|
||||
if cfg.Mode != "flaresolverr" && cfg.Mode != "on_demand" {
|
||||
return "", "", errors.New("FlareSolverr Clearance 未启用")
|
||||
}
|
||||
cfg.TargetURL = strings.TrimRight(strings.TrimSpace(targetURL), "/")
|
||||
if cfg.TargetURL == "" {
|
||||
cfg.TargetURL = "https://grok.com"
|
||||
}
|
||||
if cfg.Timeout <= 0 {
|
||||
cfg.Timeout = time.Minute
|
||||
}
|
||||
solution, err := solver.Solve(ctx, cfg, proxyURL)
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
return solution.Cookies, solution.UserAgent, nil
|
||||
}
|
||||
|
||||
func (m *Manager) Acquire(ctx context.Context, scope domain.Scope, affinity string) (*Lease, error) {
|
||||
lease, _, err := m.acquire(ctx, scope, affinity, true, "", egressNodeFromContext(ctx))
|
||||
return lease, err
|
||||
|
||||
@@ -7,7 +7,6 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"sort"
|
||||
@@ -25,7 +24,6 @@ import (
|
||||
const (
|
||||
ssoBuildClientID = "b1a00492-073a-47ea-816f-4c329264a828"
|
||||
ssoBuildScope = "openid profile email offline_access grok-cli:access api:access conversations:read conversations:write"
|
||||
ssoAccountsURL = "https://accounts.x.ai/"
|
||||
ssoDeviceURL = "https://auth.x.ai/oauth2/device/code"
|
||||
ssoVerifyURL = "https://auth.x.ai/oauth2/device/verify"
|
||||
ssoApproveURL = "https://auth.x.ai/oauth2/device/approve"
|
||||
@@ -37,16 +35,10 @@ type ssoBuildHTTPClient interface {
|
||||
Do(*http.Request) (*http.Response, error)
|
||||
}
|
||||
|
||||
// ssoClearanceResolver 为 SSO 转换目标(accounts.x.ai)现解 Cloudflare Clearance。
|
||||
// 求解失败时返回 error,调用方降级为无 Clearance 的现有行为。
|
||||
type ssoClearanceResolver func(ctx context.Context) (cookies, userAgent string, err error)
|
||||
|
||||
type ssoBuildFlow struct {
|
||||
client ssoBuildHTTPClient
|
||||
userAgent string
|
||||
cookies map[string]string
|
||||
clearance ssoClearanceResolver // 可选
|
||||
logger *slog.Logger // 可选,用于降级告警
|
||||
}
|
||||
|
||||
func (a *Adapter) ConvertToBuild(ctx context.Context, credential accountdomain.Credential) (provider.CredentialSeed, error) {
|
||||
@@ -69,17 +61,8 @@ func (a *Adapter) ConvertToBuild(ctx context.Context, credential accountdomain.C
|
||||
requestCtx, cancel := context.WithTimeout(ctx, 90*time.Second)
|
||||
defer cancel()
|
||||
flow := &ssoBuildFlow{
|
||||
client: lease, userAgent: lease.UserAgent, logger: a.logger,
|
||||
client: lease, userAgent: lease.UserAgent,
|
||||
cookies: map[string]string{"sso": token, "sso-rw": token},
|
||||
// 节点缓存的 Clearance 是 grok.com 域,对 accounts.x.ai 无效;
|
||||
// 转换流程通过同一出口现解目标域的 Clearance。
|
||||
clearance: func(solveCtx context.Context) (string, string, error) {
|
||||
cookies, userAgent, err := a.egress.SolveClearance(solveCtx, lease.ProxyURL, ssoAccountsURL)
|
||||
if err != nil {
|
||||
a.logger.Warn("web_sso_build_clearance_failed", "account_id", credential.ID, "error", err)
|
||||
}
|
||||
return cookies, userAgent, err
|
||||
},
|
||||
}
|
||||
seed, err := flow.convert(requestCtx, credential)
|
||||
if err != nil {
|
||||
@@ -91,28 +74,6 @@ func (a *Adapter) ConvertToBuild(ctx context.Context, credential accountdomain.C
|
||||
}
|
||||
|
||||
func (f *ssoBuildFlow) convert(ctx context.Context, credential accountdomain.Credential) (provider.CredentialSeed, error) {
|
||||
if f.clearance != nil {
|
||||
if cookies, userAgent, err := f.clearance(ctx); err == nil {
|
||||
mergeCookieHeader(f.cookies, cookies)
|
||||
if ua := strings.TrimSpace(userAgent); ua != "" {
|
||||
f.userAgent = ua
|
||||
}
|
||||
}
|
||||
}
|
||||
status, finalURL, _, err := f.do(ctx, http.MethodGet, ssoAccountsURL, nil)
|
||||
if err != nil {
|
||||
return provider.CredentialSeed{}, err
|
||||
}
|
||||
if status == http.StatusUnauthorized || strings.Contains(finalURL, "sign-in") || strings.Contains(finalURL, "sign-up") {
|
||||
return provider.CredentialSeed{}, provider.ErrUnauthorized
|
||||
}
|
||||
if status < 200 || status >= 400 {
|
||||
// accounts.x.ai 对非浏览器客户端启用严格 Cloudflare 拦截(HTTP 403),
|
||||
// 该预检仅用于提前识别失效 SSO,并非 Device Flow 必需步骤;
|
||||
// 被拦截时降级跳过,凭据有效性交给 verify 步判断。
|
||||
f.warn("web_sso_build_precheck_blocked", "status", status)
|
||||
}
|
||||
|
||||
form := url.Values{"client_id": {ssoBuildClientID}, "scope": {ssoBuildScope}}
|
||||
status, _, body, err := f.do(ctx, http.MethodPost, ssoDeviceURL, form)
|
||||
if err != nil {
|
||||
@@ -122,16 +83,15 @@ func (f *ssoBuildFlow) convert(ctx context.Context, credential accountdomain.Cre
|
||||
return provider.CredentialSeed{}, fmt.Errorf("xAI Device Flow 启动失败: %w", conversionHTTPError{status: status})
|
||||
}
|
||||
var device struct {
|
||||
DeviceCode string `json:"device_code"`
|
||||
UserCode string `json:"user_code"`
|
||||
VerificationURIComplete string `json:"verification_uri_complete"`
|
||||
Interval int `json:"interval"`
|
||||
ExpiresIn int `json:"expires_in"`
|
||||
DeviceCode string `json:"device_code"`
|
||||
UserCode string `json:"user_code"`
|
||||
Interval int `json:"interval"`
|
||||
ExpiresIn int `json:"expires_in"`
|
||||
}
|
||||
if err := json.Unmarshal(body, &device); err != nil {
|
||||
return provider.CredentialSeed{}, fmt.Errorf("解析 xAI Device Flow: %w", err)
|
||||
}
|
||||
if device.DeviceCode == "" || device.UserCode == "" || !safeXAIURL(device.VerificationURIComplete) {
|
||||
if device.DeviceCode == "" || device.UserCode == "" {
|
||||
return provider.CredentialSeed{}, fmt.Errorf("xAI Device Flow 返回字段不完整")
|
||||
}
|
||||
if device.Interval <= 0 {
|
||||
@@ -141,18 +101,9 @@ func (f *ssoBuildFlow) convert(ctx context.Context, credential accountdomain.Cre
|
||||
device.ExpiresIn = 1800
|
||||
}
|
||||
|
||||
status, finalURL, _, err = f.do(ctx, http.MethodGet, device.VerificationURIComplete, nil)
|
||||
if err != nil {
|
||||
return provider.CredentialSeed{}, err
|
||||
}
|
||||
if status < 200 || status >= 400 {
|
||||
// 打开验证页只是模拟浏览器预热,xAI 不要求必须先访问该页;
|
||||
// 与预检一致,被 Cloudflare 拦截时降级跳过。
|
||||
f.warn("web_sso_build_verify_page_blocked", "status", status)
|
||||
}
|
||||
// verify/approve 的重定向目标是 accounts.x.ai,该域对非浏览器客户端严格拦截;
|
||||
// 不跟随重定向,直接读 Location 判定结果,整个流程保持在 auth.x.ai 上完成。
|
||||
status, finalURL, _, err = f.doWithFollow(ctx, http.MethodPost, ssoVerifyURL, url.Values{"user_code": {device.UserCode}}, false)
|
||||
// verify/approve 已在 auth.x.ai 完成状态变更。重定向目标只是结果页,
|
||||
// 因此不访问 accounts.x.ai,直接解析首个 3xx Location 的状态路径。
|
||||
status, finalURL, _, err := f.doWithFollow(ctx, http.MethodPost, ssoVerifyURL, url.Values{"user_code": {device.UserCode}}, false)
|
||||
if err != nil {
|
||||
return provider.CredentialSeed{}, err
|
||||
}
|
||||
@@ -162,8 +113,8 @@ func (f *ssoBuildFlow) convert(ctx context.Context, credential accountdomain.Cre
|
||||
if status < 200 || status >= 400 {
|
||||
return provider.CredentialSeed{}, fmt.Errorf("SSO 自动验证 Device Flow 失败: %w", conversionHTTPError{status: status})
|
||||
}
|
||||
if !strings.Contains(finalURL, "consent") {
|
||||
if strings.Contains(finalURL, "sign-in") || strings.Contains(finalURL, "sign-up") {
|
||||
if redirectState := ssoDeviceRedirectState(finalURL); redirectState != "consent" {
|
||||
if redirectState == "sign-in" {
|
||||
return provider.CredentialSeed{}, provider.ErrUnauthorized
|
||||
}
|
||||
return provider.CredentialSeed{}, fmt.Errorf("SSO 自动验证 Device Flow 失败")
|
||||
@@ -177,7 +128,10 @@ func (f *ssoBuildFlow) convert(ctx context.Context, credential accountdomain.Cre
|
||||
if status < 200 || status >= 400 {
|
||||
return provider.CredentialSeed{}, fmt.Errorf("SSO 自动批准 Device Flow 失败: %w", conversionHTTPError{status: status})
|
||||
}
|
||||
if !strings.Contains(finalURL, "done") {
|
||||
if redirectState := ssoDeviceRedirectState(finalURL); redirectState != "done" {
|
||||
if redirectState == "sign-in" {
|
||||
return provider.CredentialSeed{}, provider.ErrUnauthorized
|
||||
}
|
||||
return provider.CredentialSeed{}, fmt.Errorf("SSO 自动批准 Device Flow 失败")
|
||||
}
|
||||
|
||||
@@ -331,29 +285,6 @@ func (f *ssoBuildFlow) doWithFollow(ctx context.Context, method, endpoint string
|
||||
return 0, currentURL, nil, fmt.Errorf("xAI OAuth 重定向次数过多")
|
||||
}
|
||||
|
||||
// warn 记录降级告警;logger 未注入时静默。
|
||||
func (f *ssoBuildFlow) warn(message string, args ...any) {
|
||||
if f.logger != nil {
|
||||
f.logger.Warn(message, args...)
|
||||
}
|
||||
}
|
||||
|
||||
// mergeCookieHeader 将 Clearance 求解返回的 Cookie 串合并进 cookie 集合,
|
||||
// 校验规则与 captureCookies 一致,避免注入非法 Cookie 头。
|
||||
func mergeCookieHeader(cookies map[string]string, header string) {
|
||||
for _, part := range strings.Split(header, ";") {
|
||||
name, value, found := strings.Cut(part, "=")
|
||||
if !found {
|
||||
continue
|
||||
}
|
||||
name, value = strings.TrimSpace(name), strings.TrimSpace(value)
|
||||
if name == "" || len(name) > 128 || len(value) > 16384 || strings.ContainsAny(name+value, "\r\n\x00") {
|
||||
continue
|
||||
}
|
||||
cookies[name] = value
|
||||
}
|
||||
}
|
||||
|
||||
func (f *ssoBuildFlow) captureCookies(response *http.Response) {
|
||||
for _, cookie := range response.Cookies() {
|
||||
name := strings.TrimSpace(cookie.Name)
|
||||
@@ -369,6 +300,24 @@ func (f *ssoBuildFlow) captureCookies(response *http.Response) {
|
||||
}
|
||||
}
|
||||
|
||||
func ssoDeviceRedirectState(raw string) string {
|
||||
parsed, err := url.Parse(raw)
|
||||
if err != nil || !safeXAIURL(raw) {
|
||||
return ""
|
||||
}
|
||||
path := strings.TrimRight(parsed.EscapedPath(), "/")
|
||||
switch path {
|
||||
case "/oauth2/device/consent":
|
||||
return "consent"
|
||||
case "/oauth2/device/done":
|
||||
return "done"
|
||||
case "/sign-in", "/sign-up":
|
||||
return "sign-in"
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
func (f *ssoBuildFlow) cookieHeader() string {
|
||||
keys := make([]string, 0, len(f.cookies))
|
||||
for key := range f.cookies {
|
||||
|
||||
@@ -31,7 +31,7 @@ func TestSSOBuildFlowFollowsOnlyTrustedXAIHTTPSRedirects(t *testing.T) {
|
||||
{StatusCode: http.StatusOK, Header: http.Header{}, Body: io.NopCloser(strings.NewReader("ok"))},
|
||||
}}
|
||||
flow := &ssoBuildFlow{client: client, userAgent: "test-agent", cookies: map[string]string{"sso": "secret"}}
|
||||
status, finalURL, body, err := flow.do(context.Background(), http.MethodGet, ssoAccountsURL, nil)
|
||||
status, finalURL, body, err := flow.do(context.Background(), http.MethodGet, ssoDeviceURL, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -48,126 +48,64 @@ func TestSSOBuildFlowFollowsOnlyTrustedXAIHTTPSRedirects(t *testing.T) {
|
||||
|
||||
unsafe := &scriptedSSOClient{responses: []*http.Response{{StatusCode: http.StatusFound, Header: http.Header{"Location": []string{"https://example.com/steal"}}, Body: io.NopCloser(strings.NewReader(""))}}}
|
||||
flow = &ssoBuildFlow{client: unsafe, userAgent: "test-agent", cookies: map[string]string{"sso": "secret"}}
|
||||
if _, _, _, err := flow.do(context.Background(), http.MethodGet, ssoAccountsURL, nil); err == nil {
|
||||
if _, _, _, err := flow.do(context.Background(), http.MethodGet, ssoDeviceURL, nil); err == nil {
|
||||
t.Fatal("unsafe redirect was accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMergeCookieHeader(t *testing.T) {
|
||||
cookies := map[string]string{"sso": "secret"}
|
||||
mergeCookieHeader(cookies, "cf_clearance=abc.123; __cuid=id=with-equals; bad\x00name=x; =novalue; long="+strings.Repeat("a", 16385)+"; sso=hijack")
|
||||
if cookies["cf_clearance"] != "abc.123" {
|
||||
t.Fatalf("cf_clearance = %q", cookies["cf_clearance"])
|
||||
}
|
||||
if cookies["__cuid"] != "id=with-equals" {
|
||||
t.Fatalf("__cuid = %q", cookies["__cuid"])
|
||||
}
|
||||
if _, ok := cookies["bad\x00name"]; ok {
|
||||
t.Fatal("cookie with NUL in name was accepted")
|
||||
}
|
||||
if _, ok := cookies[""]; ok {
|
||||
t.Fatal("cookie with empty name was accepted")
|
||||
}
|
||||
if _, ok := cookies["long"]; ok {
|
||||
t.Fatal("oversized cookie value was accepted")
|
||||
}
|
||||
if cookies["sso"] != "hijack" {
|
||||
t.Fatalf("existing cookie should be overridden, got %q", cookies["sso"])
|
||||
}
|
||||
}
|
||||
|
||||
// blockedPrecheckScript 模拟 accounts.x.ai 预检被 Cloudflare 403 拦截,
|
||||
// 随后 Device Flow 启动返回 500 使流程在第 2 步终止。
|
||||
func blockedPrecheckScript() *scriptedSSOClient {
|
||||
return &scriptedSSOClient{responses: []*http.Response{
|
||||
{StatusCode: http.StatusForbidden, Header: http.Header{}, Body: io.NopCloser(strings.NewReader("challenge"))},
|
||||
{StatusCode: http.StatusInternalServerError, Header: http.Header{}, Body: io.NopCloser(strings.NewReader("boom"))},
|
||||
}}
|
||||
}
|
||||
|
||||
func TestSSOBuildFlowAttachesClearanceToFirstRequest(t *testing.T) {
|
||||
client := blockedPrecheckScript()
|
||||
flow := &ssoBuildFlow{
|
||||
client: client, userAgent: "lease-agent",
|
||||
cookies: map[string]string{"sso": "secret"},
|
||||
clearance: func(context.Context) (string, string, error) {
|
||||
return "cf_clearance=abc.123; __cf_bm=xyz", "solver-agent", nil
|
||||
},
|
||||
}
|
||||
_, err := flow.convert(context.Background(), fakeCredential())
|
||||
if err == nil {
|
||||
t.Fatal("expected conversion to fail after scripted 500")
|
||||
}
|
||||
if len(client.requests) == 0 {
|
||||
t.Fatal("no request was issued")
|
||||
}
|
||||
first := client.requests[0]
|
||||
if ua := first.Header.Get("User-Agent"); ua != "solver-agent" {
|
||||
t.Fatalf("User-Agent = %q, want solver-agent", ua)
|
||||
}
|
||||
cookie := first.Header.Get("Cookie")
|
||||
if !strings.Contains(cookie, "sso=secret") || !strings.Contains(cookie, "cf_clearance=abc.123") || !strings.Contains(cookie, "__cf_bm=xyz") {
|
||||
t.Fatalf("Cookie = %q", cookie)
|
||||
}
|
||||
if len(client.requests) != 2 {
|
||||
t.Fatalf("blocked precheck must be degraded, requests = %d", len(client.requests))
|
||||
}
|
||||
}
|
||||
|
||||
func TestSSOBuildFlowClearanceFailureFallsBack(t *testing.T) {
|
||||
client := blockedPrecheckScript()
|
||||
flow := &ssoBuildFlow{
|
||||
client: client, userAgent: "lease-agent",
|
||||
cookies: map[string]string{"sso": "secret"},
|
||||
clearance: func(context.Context) (string, string, error) {
|
||||
return "", "", io.ErrUnexpectedEOF
|
||||
},
|
||||
}
|
||||
_, _ = flow.convert(context.Background(), fakeCredential())
|
||||
if len(client.requests) == 0 {
|
||||
t.Fatal("no request was issued")
|
||||
}
|
||||
first := client.requests[0]
|
||||
if ua := first.Header.Get("User-Agent"); ua != "lease-agent" {
|
||||
t.Fatalf("User-Agent = %q, want lease-agent", ua)
|
||||
}
|
||||
cookie := first.Header.Get("Cookie")
|
||||
if strings.Contains(cookie, "cf_clearance") || !strings.Contains(cookie, "sso=secret") {
|
||||
t.Fatalf("Cookie = %q", cookie)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSSOBuildFlowMapsDeadSSOToUnauthorized(t *testing.T) {
|
||||
client := &scriptedSSOClient{responses: []*http.Response{
|
||||
{StatusCode: http.StatusForbidden, Header: http.Header{}, Body: io.NopCloser(strings.NewReader("challenge"))},
|
||||
{StatusCode: http.StatusOK, Header: http.Header{}, Body: io.NopCloser(strings.NewReader(
|
||||
`{"device_code":"dc","user_code":"uc","verification_uri_complete":"https://accounts.x.ai/oauth2/device?code=abc","interval":1,"expires_in":1800}`))},
|
||||
{StatusCode: http.StatusForbidden, Header: http.Header{}, Body: io.NopCloser(strings.NewReader("challenge"))},
|
||||
{StatusCode: http.StatusFound, Header: http.Header{"Location": []string{"https://accounts.x.ai/sign-in"}}, Body: io.NopCloser(strings.NewReader(""))},
|
||||
`{"device_code":"dc","user_code":"uc","interval":1,"expires_in":1800}`))},
|
||||
{StatusCode: http.StatusSeeOther, Header: http.Header{"Location": []string{"https://accounts.x.ai/sign-in"}}, Body: io.NopCloser(strings.NewReader(""))},
|
||||
}}
|
||||
flow := &ssoBuildFlow{client: client, userAgent: "lease-agent", cookies: map[string]string{"sso": "dead"}}
|
||||
_, err := flow.convert(context.Background(), fakeCredential())
|
||||
if !errors.Is(err, provider.ErrUnauthorized) {
|
||||
t.Fatalf("err = %v, want ErrUnauthorized", err)
|
||||
}
|
||||
if len(client.requests) != 4 {
|
||||
t.Fatalf("requests = %d, want 4 (precheck, device, verify page, verify 不跟随重定向)", len(client.requests))
|
||||
if len(client.requests) != 2 {
|
||||
t.Fatalf("requests = %d, want 2 (device, verify)", len(client.requests))
|
||||
}
|
||||
}
|
||||
|
||||
func TestSSOBuildFlowUsesAuthEndpointsOnly(t *testing.T) {
|
||||
client := &scriptedSSOClient{responses: []*http.Response{
|
||||
{StatusCode: http.StatusOK, Header: http.Header{}, Body: io.NopCloser(strings.NewReader(
|
||||
`{"device_code":"dc","user_code":"uc","interval":1,"expires_in":1800}`))},
|
||||
{StatusCode: http.StatusSeeOther, Header: http.Header{"Location": []string{"https://accounts.x.ai/oauth2/device/consent"}}, Body: io.NopCloser(strings.NewReader(""))},
|
||||
{StatusCode: http.StatusSeeOther, Header: http.Header{"Location": []string{"https://accounts.x.ai/oauth2/device/done"}}, Body: io.NopCloser(strings.NewReader(""))},
|
||||
{StatusCode: http.StatusOK, Header: http.Header{}, Body: io.NopCloser(strings.NewReader(
|
||||
`{"access_token":"access","refresh_token":"refresh","expires_in":3600}`))},
|
||||
}}
|
||||
flow := &ssoBuildFlow{client: client, userAgent: "lease-agent", cookies: map[string]string{"sso": "live", "sso-rw": "live"}}
|
||||
seed, err := flow.convert(context.Background(), fakeCredential())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if seed.AccessToken != "access" || seed.RefreshToken != "refresh" || len(client.requests) != 4 {
|
||||
t.Fatalf("seed=%#v requests=%d", seed, len(client.requests))
|
||||
}
|
||||
for _, request := range client.requests {
|
||||
if request.URL.Hostname() != "auth.x.ai" {
|
||||
t.Fatalf("device flow visited unexpected host %q", request.URL.Hostname())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSSOBuildFlowVerifyDoesNotFollowRedirect(t *testing.T) {
|
||||
client := &scriptedSSOClient{responses: []*http.Response{
|
||||
{StatusCode: http.StatusFound, Header: http.Header{"Location": []string{"https://accounts.x.ai/oauth2/device?code=abc&consent=1"}}, Body: io.NopCloser(strings.NewReader(""))},
|
||||
{StatusCode: http.StatusSeeOther, Header: http.Header{"Location": []string{"https://accounts.x.ai/oauth2/device/consent"}}, Body: io.NopCloser(strings.NewReader(""))},
|
||||
}}
|
||||
flow := &ssoBuildFlow{client: client, userAgent: "lease-agent", cookies: map[string]string{"sso": "live"}}
|
||||
status, finalURL, _, err := flow.doWithFollow(context.Background(), http.MethodPost, ssoVerifyURL, url.Values{"user_code": {"uc"}}, false)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if status != http.StatusFound {
|
||||
t.Fatalf("status = %d, want 302", status)
|
||||
if status != http.StatusSeeOther {
|
||||
t.Fatalf("status = %d, want 303", status)
|
||||
}
|
||||
if finalURL != "https://accounts.x.ai/oauth2/device?code=abc&consent=1" {
|
||||
if finalURL != "https://accounts.x.ai/oauth2/device/consent" {
|
||||
t.Fatalf("finalURL = %q", finalURL)
|
||||
}
|
||||
if len(client.requests) != 1 {
|
||||
@@ -175,6 +113,22 @@ func TestSSOBuildFlowVerifyDoesNotFollowRedirect(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestSSODeviceRedirectStateRequiresExactTrustedPath(t *testing.T) {
|
||||
tests := map[string]string{
|
||||
"https://accounts.x.ai/oauth2/device/consent": "consent",
|
||||
"https://accounts.x.ai/oauth2/device/done/": "done",
|
||||
"https://accounts.x.ai/sign-in?returnTo=%2Foauth2": "sign-in",
|
||||
"https://accounts.x.ai/other?next=consent": "",
|
||||
"https://accounts.x.ai/oauth2/device/consent-untrusted": "",
|
||||
"https://example.com/oauth2/device/consent": "",
|
||||
}
|
||||
for raw, wanted := range tests {
|
||||
if actual := ssoDeviceRedirectState(raw); actual != wanted {
|
||||
t.Fatalf("ssoDeviceRedirectState(%q)=%q want=%q", raw, actual, wanted)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func fakeCredential() accountdomain.Credential { return accountdomain.Credential{} }
|
||||
|
||||
func TestSSOBuildConversionSanitizesTokenAndURLs(t *testing.T) {
|
||||
|
||||
Reference in new issue
Block a user