mirror of
https://github.com/chenyme/grok2api.git
synced 2026-12-05 08:01:07 +00:00
Merge pull request #862 from buddhism5080/fix/console-dpop-date-skew
fix(console): align DPoP proof iat with mint response Date skew
This commit is contained in:
6 files changed
+241
-7
No files matched your search
@@ -146,7 +146,7 @@ func (a *Adapter) ForwardResponse(ctx context.Context, request provider.Response
|
||||
cancel()
|
||||
return nil, readErr
|
||||
}
|
||||
if !provider.IsDefinitiveAccountBlockBody(data) && !provider.IsDPoPProofRequiredBody(data) {
|
||||
if shouldInvalidateConsoleClearance(data) {
|
||||
lease.InvalidateClearance()
|
||||
a.egress.FeedbackForScope(context.WithoutCancel(ctx), egressdomain.ScopeConsole, lease.NodeID, response.StatusCode, nil)
|
||||
}
|
||||
@@ -220,6 +220,12 @@ func (a *Adapter) ForwardResponse(ctx context.Context, request provider.Response
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// shouldInvalidateConsoleClearance keeps account-level and protocol-level
|
||||
// rejections from being misclassified as a broken browser/egress binding.
|
||||
func shouldInvalidateConsoleClearance(body []byte) bool {
|
||||
return !provider.IsDefinitiveAccountBlockBody(body) && !provider.IsDPoPProofRequiredBody(body)
|
||||
}
|
||||
|
||||
func normalizeConversationError(data []byte, operation string, status int) []byte {
|
||||
var envelope struct {
|
||||
Error json.RawMessage `json:"error"`
|
||||
|
||||
@@ -614,6 +614,28 @@ func TestAdapterDoesNotPenalizeEgressForBlockedAccount(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestShouldInvalidateConsoleClearance(t *testing.T) {
|
||||
t.Parallel()
|
||||
tests := []struct {
|
||||
name string
|
||||
body string
|
||||
want bool
|
||||
}{
|
||||
{name: "dpop protocol rejection", body: `{"code":"unauthorized:dpop-required","error":"DPoP proof required"}`, want: false},
|
||||
{name: "blocked account", body: `{"code":"unauthorized:blocked-user","error":"User is blocked"}`, want: false},
|
||||
{name: "anti-bot rejection", body: `{"error":{"code":7,"message":"Request rejected by anti-bot rules."}}`, want: true},
|
||||
{name: "generic forbidden", body: `forbidden`, want: true},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
if got := shouldInvalidateConsoleClearance([]byte(test.body)); got != test.want {
|
||||
t.Fatalf("shouldInvalidateConsoleClearance() = %v, want %v", got, test.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdapterForwardsConsoleHeadersAndNormalizedBody(t *testing.T) {
|
||||
var received map[string]any
|
||||
server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
|
||||
|
||||
@@ -46,6 +46,11 @@ type dpopSession struct {
|
||||
privateKey *ecdsa.PrivateKey
|
||||
publicJWK dpopJWK
|
||||
expiresAt time.Time
|
||||
// clockSkew is (server time − local time) learned from the DPoP mint
|
||||
// response Date header. Zero is a valid value meaning "no correction".
|
||||
// Every session always carries an explicit skew so proof iat never depends
|
||||
// on an uninitialized field.
|
||||
clockSkew time.Duration
|
||||
}
|
||||
|
||||
type dpopSessionManager struct {
|
||||
@@ -210,18 +215,23 @@ func (a *Adapter) fetchDPoPSession(ctx context.Context, ssoToken string, lease *
|
||||
}
|
||||
applyBrowserHeaders(request, ssoToken, lease)
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
localBefore := time.Now().UTC()
|
||||
response, err := lease.DoDeferredForbidden(request)
|
||||
if err != nil {
|
||||
return dpopSession{}, err
|
||||
}
|
||||
localAfter := time.Now().UTC()
|
||||
data, truncated, readErr := provider.ReadDiagnosticBody(response.Body)
|
||||
_ = response.Body.Close()
|
||||
if readErr != nil {
|
||||
return dpopSession{}, readErr
|
||||
}
|
||||
// Always materialize a skew value for this session. Missing/unparseable Date
|
||||
// yields 0 (no correction) — still a defined, usable value for every proof.
|
||||
clockSkew := dpopClockSkewFromDateHeader(response.Header.Get("Date"), localBefore, localAfter)
|
||||
if response.StatusCode < 200 || response.StatusCode >= 300 {
|
||||
if response.StatusCode == http.StatusForbidden {
|
||||
if !provider.IsDefinitiveAccountBlockBody(data) && !provider.IsDPoPProofRequiredBody(data) {
|
||||
if shouldInvalidateConsoleClearance(data) {
|
||||
lease.InvalidateClearance()
|
||||
}
|
||||
}
|
||||
@@ -255,6 +265,8 @@ func (a *Adapter) fetchDPoPSession(ctx context.Context, ssoToken string, lease *
|
||||
if tokenThumbprint != thumbprint {
|
||||
return dpopSession{}, errors.New("Console DPoP token 与本地密钥不匹配")
|
||||
}
|
||||
// Expiry bookkeeping stays on the local monotonic wall clock so cache checks
|
||||
// remain self-consistent; proof iat alone is shifted by clockSkew.
|
||||
now := time.Now().UTC()
|
||||
expiresAt := now.Add(time.Duration(tokenResponse.ExpiresIn) * time.Second)
|
||||
if tokenExpiry.Before(expiresAt) {
|
||||
@@ -263,7 +275,13 @@ func (a *Adapter) fetchDPoPSession(ctx context.Context, ssoToken string, lease *
|
||||
if !expiresAt.After(now.Add(dpopRefreshSkew)) {
|
||||
return dpopSession{}, errors.New("Console DPoP token 已过期或即将过期")
|
||||
}
|
||||
return dpopSession{accessToken: tokenResponse.AccessToken, privateKey: privateKey, publicJWK: publicJWK, expiresAt: expiresAt}, nil
|
||||
return dpopSession{
|
||||
accessToken: tokenResponse.AccessToken,
|
||||
privateKey: privateKey,
|
||||
publicJWK: publicJWK,
|
||||
expiresAt: expiresAt,
|
||||
clockSkew: clockSkew,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (a *Adapter) doDPoPRequest(
|
||||
@@ -368,7 +386,7 @@ func applyDPoPAuthorization(request *http.Request, session dpopSession) error {
|
||||
"jti": uuid.NewString(),
|
||||
"htm": strings.ToUpper(request.Method),
|
||||
"htu": dpopHTU(request),
|
||||
"iat": time.Now().UTC().Unix(),
|
||||
"iat": dpopProofIAT(session, time.Now().UTC()),
|
||||
"ath": base64.RawURLEncoding.EncodeToString(digest[:]),
|
||||
}
|
||||
proof := jwt.NewWithClaims(jwt.SigningMethodES256, claims)
|
||||
@@ -383,6 +401,44 @@ func applyDPoPAuthorization(request *http.Request, session dpopSession) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// dpopProofIAT returns the Unix seconds used for DPoP proof iat.
|
||||
// session.clockSkew is always defined on minted sessions (0 if Date was absent).
|
||||
func dpopProofIAT(session dpopSession, localNow time.Time) int64 {
|
||||
if localNow.IsZero() {
|
||||
localNow = time.Now().UTC()
|
||||
}
|
||||
return localNow.Add(session.clockSkew).UTC().Unix()
|
||||
}
|
||||
|
||||
// dpopClockSkewFromDateHeader mirrors console.x.ai frontend behavior:
|
||||
// skewSeconds ≈ round((serverDate − localNow) / 1s), applied later as
|
||||
// iat = floor((localNow + skew) / 1s). localBefore/localAfter bound the RTT
|
||||
// around the mint response so we estimate local time at header receipt without
|
||||
// an extra time API call. Returns 0 when Date is missing or unparseable so
|
||||
// callers always receive a usable skew value.
|
||||
func dpopClockSkewFromDateHeader(dateHeader string, localBefore, localAfter time.Time) time.Duration {
|
||||
dateHeader = strings.TrimSpace(dateHeader)
|
||||
if dateHeader == "" {
|
||||
return 0
|
||||
}
|
||||
serverTime, err := http.ParseTime(dateHeader)
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
if localAfter.IsZero() || localAfter.Before(localBefore) {
|
||||
localAfter = localBefore
|
||||
}
|
||||
if localBefore.IsZero() {
|
||||
localBefore = time.Now().UTC()
|
||||
localAfter = localBefore
|
||||
}
|
||||
// Mid-point of the local observation window approximates "now" when Date was set.
|
||||
localMid := localBefore.Add(localAfter.Sub(localBefore) / 2)
|
||||
// Store whole seconds because DPoP iat has second precision. Duration.Round
|
||||
// makes the half-away-from-zero behavior explicit for both skew directions.
|
||||
return serverTime.UTC().Sub(localMid.UTC()).Round(time.Second)
|
||||
}
|
||||
|
||||
func dpopHTU(request *http.Request) string {
|
||||
path := request.URL.EscapedPath()
|
||||
if path == "" {
|
||||
|
||||
@@ -0,0 +1,150 @@
|
||||
package console
|
||||
|
||||
import (
|
||||
"crypto/ecdsa"
|
||||
"crypto/elliptic"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestDPoPClockSkewFromDateHeaderAlwaysUsable(t *testing.T) {
|
||||
local := time.Date(2026, 8, 5, 17, 0, 0, 0, time.UTC)
|
||||
|
||||
if got := dpopClockSkewFromDateHeader("", local, local); got != 0 {
|
||||
t.Fatalf("empty Date skew = %v, want 0", got)
|
||||
}
|
||||
if got := dpopClockSkewFromDateHeader("not-a-date", local, local); got != 0 {
|
||||
t.Fatalf("bad Date skew = %v, want 0", got)
|
||||
}
|
||||
|
||||
server := local.Add(-80 * time.Second)
|
||||
got := dpopClockSkewFromDateHeader(server.Format(http.TimeFormat), local, local)
|
||||
if got != -80*time.Second {
|
||||
t.Fatalf("skew = %v, want -80s", got)
|
||||
}
|
||||
|
||||
server = local.Add(90 * time.Second)
|
||||
got = dpopClockSkewFromDateHeader(server.Format(http.TimeFormat), local, local)
|
||||
if got != 90*time.Second {
|
||||
t.Fatalf("skew = %v, want 90s", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDPoPProofIATAppliesSessionClockSkew(t *testing.T) {
|
||||
local := time.Date(2026, 8, 5, 17, 0, 0, 0, time.UTC)
|
||||
session := dpopSession{clockSkew: -80 * time.Second}
|
||||
if got := dpopProofIAT(session, local); got != local.Add(-80*time.Second).Unix() {
|
||||
t.Fatalf("iat = %d, want skewed", got)
|
||||
}
|
||||
if got := dpopProofIAT(dpopSession{}, local); got != local.Unix() {
|
||||
t.Fatalf("zero skew iat = %d, want %d", got, local.Unix())
|
||||
}
|
||||
}
|
||||
|
||||
func TestFetchDPoPSessionStoresClockSkewFromDateHeader(t *testing.T) {
|
||||
var sawIAT int64
|
||||
server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
|
||||
switch {
|
||||
case request.URL.Path == "/v1/dpop/token":
|
||||
// Keep skew inside verifyTestDPoPProof's ±1m iat window.
|
||||
serverNow := time.Now().UTC().Add(-30 * time.Second)
|
||||
writer.Header().Set("Date", serverNow.Format(http.TimeFormat))
|
||||
if !serveTestDPoPToken(t, writer, request) {
|
||||
t.Fatalf("expected dpop token path")
|
||||
}
|
||||
case request.URL.Path == "/v1/usage":
|
||||
proof := strings.TrimSpace(request.Header.Get("DPoP"))
|
||||
parts := strings.Split(proof, ".")
|
||||
if len(parts) != 3 {
|
||||
t.Fatalf("bad DPoP proof")
|
||||
}
|
||||
payload, err := base64.RawURLEncoding.DecodeString(parts[1])
|
||||
if err != nil {
|
||||
t.Fatalf("decode proof payload: %v", err)
|
||||
}
|
||||
var claims map[string]any
|
||||
if err := json.Unmarshal(payload, &claims); err != nil {
|
||||
t.Fatalf("unmarshal proof claims: %v", err)
|
||||
}
|
||||
switch v := claims["iat"].(type) {
|
||||
case float64:
|
||||
sawIAT = int64(v)
|
||||
case json.Number:
|
||||
sawIAT, _ = v.Int64()
|
||||
default:
|
||||
t.Fatalf("iat type = %T", claims["iat"])
|
||||
}
|
||||
if request.Header.Get("Authorization") == "" || proof == "" {
|
||||
t.Fatalf("missing DPoP auth headers")
|
||||
}
|
||||
writer.Header().Set("Content-Type", "application/json")
|
||||
_, _ = io.WriteString(writer, `{"quotas":[{"kind":"chat","limit":10,"used":0,"remaining":10},{"kind":"image","limit":5,"used":0,"remaining":5},{"kind":"video","limit":2,"used":0,"remaining":2}]}`)
|
||||
default:
|
||||
http.NotFound(writer, request)
|
||||
}
|
||||
}))
|
||||
t.Cleanup(server.Close)
|
||||
|
||||
adapter, credential := newConsoleTestAdapter(t, server.URL)
|
||||
if _, err := adapter.SyncQuota(t.Context(), credential); err != nil {
|
||||
t.Fatalf("SyncQuota: %v", err)
|
||||
}
|
||||
|
||||
var sawSkew time.Duration
|
||||
adapter.dpop.mu.Lock()
|
||||
for _, entry := range adapter.dpop.sessions {
|
||||
sawSkew = entry.session.clockSkew
|
||||
break
|
||||
}
|
||||
adapter.dpop.mu.Unlock()
|
||||
if sawSkew > -20*time.Second || sawSkew < -40*time.Second {
|
||||
t.Fatalf("session clockSkew = %v, want about -30s", sawSkew)
|
||||
}
|
||||
if sawIAT == 0 {
|
||||
t.Fatal("did not capture iat")
|
||||
}
|
||||
localNow := time.Now().UTC().Unix()
|
||||
if delta := localNow - sawIAT; delta < 15 || delta > 45 {
|
||||
t.Fatalf("iat skew vs local: local=%d iat=%d delta=%d, want ~30s", localNow, sawIAT, delta)
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyDPoPAuthorizationUsesClockSkewInIAT(t *testing.T) {
|
||||
privateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
access := "test-access-token"
|
||||
session := dpopSession{
|
||||
accessToken: access,
|
||||
privateKey: privateKey,
|
||||
publicJWK: publicDPoPJWK(&privateKey.PublicKey),
|
||||
clockSkew: -80 * time.Second,
|
||||
}
|
||||
request := httptest.NewRequest(http.MethodGet, "https://console.x.ai/v1/usage", nil)
|
||||
if err := applyDPoPAuthorization(request, session); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
proof := request.Header.Get("DPoP")
|
||||
parts := strings.Split(proof, ".")
|
||||
payload, _ := base64.RawURLEncoding.DecodeString(parts[1])
|
||||
var claims map[string]any
|
||||
_ = json.Unmarshal(payload, &claims)
|
||||
iat := int64(claims["iat"].(float64))
|
||||
want := time.Now().UTC().Add(-80 * time.Second).Unix()
|
||||
if iat < want-2 || iat > want+2 {
|
||||
t.Fatalf("iat = %d, want ~%d", iat, want)
|
||||
}
|
||||
digest := sha256.Sum256([]byte(access))
|
||||
if claims["ath"] != base64.RawURLEncoding.EncodeToString(digest[:]) {
|
||||
t.Fatalf("ath mismatch: %#v", claims["ath"])
|
||||
}
|
||||
}
|
||||
@@ -175,7 +175,7 @@ func (a *Adapter) forwardConsoleMedia(ctx context.Context, credential account.Cr
|
||||
data, truncated, readErr := provider.ReadDiagnosticBody(response.Body)
|
||||
_ = response.Body.Close()
|
||||
dpopRequired := response.StatusCode == http.StatusForbidden && provider.IsDPoPProofRequiredBody(data)
|
||||
if response.StatusCode == http.StatusForbidden && !provider.IsDefinitiveAccountBlockBody(data) && !dpopRequired {
|
||||
if response.StatusCode == http.StatusForbidden && shouldInvalidateConsoleClearance(data) {
|
||||
lease.InvalidateClearance()
|
||||
}
|
||||
if !dpopRequired {
|
||||
@@ -503,7 +503,7 @@ func (a *Adapter) doConsoleVideoJSON(ctx context.Context, credential account.Cre
|
||||
}
|
||||
if response.StatusCode < 200 || response.StatusCode >= 300 {
|
||||
dpopRequired := response.StatusCode == http.StatusForbidden && provider.IsDPoPProofRequiredBody(data)
|
||||
if response.StatusCode == http.StatusForbidden && !provider.IsDefinitiveAccountBlockBody(data) && !dpopRequired {
|
||||
if response.StatusCode == http.StatusForbidden && shouldInvalidateConsoleClearance(data) {
|
||||
lease.InvalidateClearance()
|
||||
}
|
||||
if !dpopRequired {
|
||||
|
||||
@@ -71,7 +71,7 @@ func (a *Adapter) syncConsoleQuotas(ctx context.Context, credential account.Cred
|
||||
return nil, time.Time{}, fmt.Errorf("%w: Console usage rejected", provider.ErrUnauthorized)
|
||||
}
|
||||
dpopRequired := response.StatusCode == http.StatusForbidden && provider.IsDPoPProofRequiredBody(data)
|
||||
if response.StatusCode == http.StatusForbidden && !dpopRequired {
|
||||
if response.StatusCode == http.StatusForbidden && shouldInvalidateConsoleClearance(data) {
|
||||
lease.InvalidateClearance()
|
||||
}
|
||||
if !dpopRequired {
|
||||
|
||||
Reference in new issue
Block a user