provider: a balance query's header takes the key as {token} too, and the key pasted as its token goes as a Bearer (lx_78654 on Discord)

A key usage query that takes only "Authorization: Bearer <key>"
answered magpie's Check balance with {"code":"INVALID_AUTH_HEADER",
"message":"Authorization header format must be 'Bearer {token}'"}. Two
ways got there:
- a header written as the vendor's own error names it, "Authorization:
  Bearer {token}", went with "{token}" in it as written: only {key},
  {apiKey} and {api_key} were put in;
- the key pasted into the Account balance (token) field went bare in
  Authorization, the way a new-api access token goes.

The key is now put in for {token} as well, for any case of key, apikey,
api_key, api-key and token, and in {{…}} or ${…}. A balance token that
is the provider's own key (with or without "Bearer ") is taken as no
token, so the query is asked as a chat request is, with the key as a
Bearer. A token of the account's own still goes as it is. Without a
header or a token the key already went as a Bearer.

Run:
- TestBalanceKeyAsBearer: an httptest server that answers only
  "Bearer <key>"; no header, Bearer {token}/{key}/{API_KEY}/{{apikey}}/
  ${API_KEY}, the key and "Bearer <key>" as the token all read $8.50;
  {TOKEN} in the URL is escaped; an access token still goes bare. On the
  old code it fails with the reporter's INVALID_AUTH_HEADER for {token},
  {API_KEY}, {{apikey}}, ${API_KEY} and the key as token.
- go test -tags nogui ./internal/provider/ ./internal/cli/.
- gofmt -l; go vet darwin, GOOS=linux -tags nogui, GOOS=windows.

Not tried: the vendor's real endpoint (a relay, not contacted). Chat
requests still send Headers exactly as typed (provider.go's Headers
doc); only the balance query puts the key in.
This commit is contained in:
yetone
2026-10-14 19:47:17 +08:00
parent 8ea4fec90a
commit 4048ead7fa
2 changed files with 82 additions and 6 deletions
+26 -6
View File
@@ -17,6 +17,7 @@ import (
"math"
"net/http"
"net/url"
"regexp"
"slices"
"strconv"
"strings"
@@ -151,6 +152,7 @@ var tokenQueries = []struct{ account, key, field string }{
// again asks the account query again. One with an Authorization or Cookie
// header of the user's own still asks it as they set it.
func keyQueryOf(p Provider) Provider {
p = keyNotToken(p)
if p.BalanceURL == "" || strings.TrimSpace(p.BalanceToken) != "" {
return p
}
@@ -1219,9 +1221,14 @@ func sub2APIKeyLimits(p Provider) bool {
// balanceKeyNames are what a Balance URL or a header's value names the
// key by, for a vendor that wants it somewhere of its own, in the query
// most often (…/balance?key={key}): each key the provider has on is put in
// its own ask, so each card tells that key's balance.
var balanceKeyNames = []string{"{key}", "{apiKey}", "{api_key}"}
// most often (…/balance?key={key}) or a header (Authorization: Bearer
// {token}): each key the provider has on is put in its own ask, so each
// card tells that key's balance. Any case, in one or two braces or as
// ${…}: {key}, {apiKey}, {api_key}, {API_KEY}, {token}, {{key}}, ${API_KEY}.
// {token} is the key too: it is what a vendor's own error names the value
// in "Authorization: Bearer {token}" (lx_78654 on Discord, whose header
// went with "{token}" in it as written, and the vendor refused it).
var balanceKeyNames = regexp.MustCompile(`(?i)\$?\{\{?\s*(?:key|api[_-]?key|token)\s*\}?\}`)
// withBalanceKey is s with the key in place of its names, escaped for a
// URL's query when inURL.
@@ -1229,10 +1236,23 @@ func withBalanceKey(s, key string, inURL bool) string {
if inURL {
key = url.QueryEscape(key)
}
for _, n := range balanceKeyNames {
s = strings.ReplaceAll(s, n, key)
return balanceKeyNames.ReplaceAllLiteralString(s, key)
}
// keyNotToken is p without a balance token that is only its own key
// pasted there: the query is asked as with no token, the key as a Bearer
// the way a chat request sends it, not the key bare in Authorization as
// a new-api access token goes, which a vendor that wants "Bearer <key>"
// refuses (lx_78654 on Discord).
func keyNotToken(p Provider) Provider {
t := strings.TrimSpace(p.BalanceToken)
if len(t) > 7 && strings.EqualFold(t[:7], "bearer ") {
t = strings.TrimSpace(t[7:])
}
return s
if t != "" && t == strings.TrimSpace(p.Key) {
p.BalanceToken = ""
}
return p
}
var keyBalanceCache struct {
+56
View File
@@ -567,3 +567,59 @@ func TestSiliconFlowRetiredBalanceQuery(t *testing.T) {
}
}
}
// A key usage query that takes only "Authorization: Bearer <key>"
// (lx_78654 on Discord: a header of "Bearer {token}" went as written, and
// the vendor said "Authorization header format must be 'Bearer {token}'").
// The key is put in for each of its names, and the key pasted as the
// balance token goes as a Bearer too, not bare as an access token.
func TestBalanceKeyAsBearer(t *testing.T) {
const key = "sk-tt-1"
var got []string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
got = append(got, r.Header.Get("Authorization"))
if r.Header.Get("Authorization") != "Bearer "+key {
w.WriteHeader(http.StatusUnauthorized)
w.Write([]byte(`{"code":"INVALID_AUTH_HEADER","message":"Authorization header format must be 'Bearer {token}'"}`))
return
}
w.Write([]byte(`{"data":{"remain":8.5}}`))
}))
defer srv.Close()
base := Provider{ID: "relay", Chat: srv.URL + "/v1", Key: key, BalanceURL: srv.URL + "/key/usage", BalancePath: "$data.remain"}
for _, c := range []struct {
name string
headers map[string]string
token string
}{
{name: "no header"},
{name: "{token}", headers: map[string]string{"Authorization": "Bearer {token}"}},
{name: "{key}", headers: map[string]string{"Authorization": "Bearer {key}"}},
{name: "{API_KEY}", headers: map[string]string{"authorization": "Bearer {API_KEY}"}},
{name: "{{apikey}}", headers: map[string]string{"Authorization": "Bearer {{apikey}}"}},
{name: "${API_KEY}", headers: map[string]string{"Authorization": "Bearer ${API_KEY}"}},
{name: "key as token", token: key},
{name: "Bearer key as token", token: "Bearer " + key},
} {
p := base
p.Headers, p.BalanceToken = c.headers, c.token
got = nil
if amount, ok, err := Balance(context.Background(), p); err != nil || !ok || amount != "$8.50" {
t.Errorf("%s: balance = %q %v %v, sent %q", c.name, amount, ok, err, got)
}
}
// the key in the URL is escaped there, under any of its names
p := base
p.BalanceURL = srv.URL + "/key/usage?k={TOKEN}"
p.Key = "sk-tt 1"
if u := withBalanceKey(p.BalanceURL, p.Key, true); !strings.HasSuffix(u, "?k=sk-tt+1") {
t.Fatalf("url = %q", u)
}
// a token of the account's own, not the key, still goes as it is
p = base
p.BalanceToken = "tok"
got = nil
if _, _, err := Balance(context.Background(), p); err == nil || len(got) != 1 || got[0] != "tok" {
t.Fatalf("an access token went as %q (%v)", got, err)
}
}