zane668 got 401 {"error":"Authentication required"} a few times a day on
tokens not near their end. grok models left the same token, so the
plugin said "couldn't renew the sign-in ... add the account in magpie
again", yet the same token answered 2-5 minutes later.
What tells the two apart: cli-chat-proxy answers a token it doesn't take
at once with "Invalid or expired credentials (auth_kind=..., upstream=
Unauthenticated|PermissionDenied, reason=...)" (curl'd 11-07 with made-up
tokens, signed and unsigned, on /models, /responses, /chat/completions,
/billing: each in under 1.5s). "Authentication required" after 78-114s
is not that verdict.
Now, after a 401 on a request, model list or usage read whose renewal
leaves the token as it was:
- the body is not "Invalid or expired credentials", the token is not
past its end, and grok models didn't exit with an error (it ran, or
was still running): a 503 with Retry-After: 60, X-Magpie-Sign-In: kept,
code auth_refused_transient, saying what Grok said, how long it took
to answer, and that no new sign-in is needed. magpie's gateway reads a
503 as before (failOther: a short backoff rest, the next account
asked), so routing is unchanged; only the advice and status change. A
model list or usage read gives the same words, with no sign-in mark.
- otherwise as before: "couldn't renew the sign-in", sign in again.
- the wait on Grok Build's renewal after a 401 is capped at 15s; the run
goes on and the next asker takes what it gave. The message names
grok models' own run time when it is 1s or more.
Where the 78-114s went: the plugin's own part is grok models, capped at
30s by execFile before and at 15s now. grok models "ran" (exit 0) in the
report, so it took under 30s; the rest, at least ~50s, was Grok's answer
to the request. zane668 saw "no first token in 120s" and ECONNRESET on
other vendors in the same windows, so the wait is upstream/network and
the plugin doesn't bound it. The message now says both times, so the
next report shows the split. Not done: the report's suggestion to resend
after a few seconds; the refusal lasted minutes and each try waited
over a minute, so handing over at once is faster.
Left ambiguous: a token xAI revoked but answered with words other than
"Invalid or expired credentials" would now read as passing and keep
being retried with short rests; a revoked real token was not available
to see its words.
Run at this tree:
- packages/grok bun test on mote: 96 pass, 0 fail.
- repo bun test (HOME=$(mktemp -d)) on the Linux VM (wsl-run,
magpie-desktop): 6571 pass, 19 skip, 0 fail. Not on mote: its suite
lock had a 3h GUI run and four Go suites queued.
- bun scripts/check.mjs grok on mote and Linux: ok.
- Real: the plugin against the real cli-chat-proxy with a made-up token
and a fake grok models leaving it: 401 sign_in_unrenewed, Grok's
"Invalid or expired credentials (... upstream=PermissionDenied ...)"
quoted, after 1s.
Broken by hand (renew.test.mjs, 15 tests): old index.mjs fails the 503,
bounded-wait, model-list and usage tests (4); passing() without the
TURNED_AWAY check fails 3 (two old tests and the new verdict test); the
CLI's failure ignored fails the exit-1 test; no 15s bound fails the
bounded-wait test (2013ms); models and usage not passing Grok's words
each fail their test.
Not tried: a real "Authentication required" 401 (it can't be called up),
a revoked real token, a real Grok Build slower than 15s.
Reported-by: zane668
302 lines
13 KiB
JavaScript
302 lines
13 KiB
JavaScript
// A token Grok turns away before its time (plugins#324): Grok can reject a
|
|
// token hours ahead of its expires_at, so a 401 has Grok Build renew it in
|
|
// the account's home and the request, model list or usage read asks once
|
|
// more. Where the CLI's run leaves the token as it was, the failure says
|
|
// Grok Build couldn't renew it, and what helps: opening Grok Build for its
|
|
// own home, signing in through magpie for a home of the plugin's. Never
|
|
// "run `grok login`", which renews neither.
|
|
//
|
|
// auth.json caught while the CLI rewrites it is unknown, not "not signed
|
|
// in": it is read again, else the last sign-in read whole there stands.
|
|
//
|
|
// The CLI is a fake as in refresh.test.mjs: /bin/sh under grok's name,
|
|
// `grok models` being `sh models` reading the script below. FAKE_GROK says
|
|
// what the run does: renew writes a new token, same exits 0 leaving the
|
|
// token as it was (the CLI saying "Renewed" with pre_key == post_key), fail
|
|
// exits 1 as a failed silent refresh. PATH is emptied so no real grok is
|
|
// ever found, and fetch is a stand-in: nothing reaches the network.
|
|
import { noRealGrok } from "./nocli.mjs"
|
|
import { afterAll, afterEach, beforeEach, expect, test } from "bun:test"
|
|
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs"
|
|
import { tmpdir } from "node:os"
|
|
import { join } from "node:path"
|
|
import { GrokAuthPlugin } from "./index.mjs"
|
|
|
|
noRealGrok()
|
|
|
|
const real = globalThis.fetch
|
|
const env = { ...process.env }
|
|
const root = mkdtempSync(join(tmpdir(), "grok-renew-"))
|
|
afterAll(() => rmSync(root, { recursive: true, force: true }))
|
|
|
|
const bin = join(root, "bin")
|
|
const later = new Date(Date.now() + 24 * 3600_000).toISOString()
|
|
mkdirSync(bin)
|
|
symlinkSync("/bin/sh", join(bin, "grok"))
|
|
writeFileSync(
|
|
join(root, "models"),
|
|
`n=$(( $(cat "$GROK_HOME/runs" 2>/dev/null || echo 0) + 1 ))
|
|
echo $n > "$GROK_HOME/runs"
|
|
case "$FAKE_GROK" in
|
|
renew) printf '{"a":{"key":"tok-%s","email":"g@x.ai","expires_at":"${later}"}}' $n > "$GROK_HOME/auth.json" ;;
|
|
same) ;;
|
|
slow) /bin/sleep 2; echo done > "$GROK_HOME/slow" ;;
|
|
*) echo "silent refresh outcome=Failed(SelfHealing)" >&2; exit 1 ;;
|
|
esac
|
|
`,
|
|
)
|
|
|
|
let home
|
|
beforeEach(() => {
|
|
home = mkdtempSync(join(root, "home-"))
|
|
process.env.GROK_BIN_DIR = bin
|
|
process.env.PATH = ""
|
|
// the CLI's own home is elsewhere unless a test says it is this one
|
|
process.env.GROK_HOME = join(root, "cli-home")
|
|
process.env.FAKE_GROK = "renew"
|
|
})
|
|
afterEach(() => {
|
|
globalThis.fetch = real
|
|
for (const k of Object.keys(process.env)) if (!(k in env)) delete process.env[k]
|
|
Object.assign(process.env, env)
|
|
})
|
|
|
|
// signedIn writes the CLI's sign-in in home, good for a day by its own say
|
|
function signedIn(key) {
|
|
writeFileSync(join(home, "auth.json"), JSON.stringify({ a: { key, email: "g@x.ai", expires_at: later } }))
|
|
return { type: "oauth", refresh: home, access: key, expires: Date.parse(later), accountId: "g@x.ai" }
|
|
}
|
|
const runs = () => {
|
|
try {
|
|
return Number(readFileSync(join(home, "runs"), "utf8").trim() || 0)
|
|
} catch {
|
|
return 0
|
|
}
|
|
}
|
|
|
|
// grok answers 401 to tok-0 and serves any other token; refused is the
|
|
// 401's body, by default what cli-chat-proxy says of a token it doesn't
|
|
// take (curl'd 11-07 with a made-up token)
|
|
const TURNED_AWAY = { error: "Invalid or expired credentials (auth_kind=none, x_xai_token_auth=none, upstream=Unauthenticated, reason=no auth context)" }
|
|
// and the 401 zane668 got on a token that worked again minutes later
|
|
const PASSING = { error: "Authentication required" }
|
|
function grok(ok, refused = TURNED_AWAY, delay = 0) {
|
|
const sent = []
|
|
globalThis.fetch = async (url, init) => {
|
|
const auth = new Headers(init?.headers).get("Authorization")
|
|
sent.push(auth)
|
|
if (delay) await new Promise((r) => setTimeout(r, delay))
|
|
if (auth === "Bearer tok-0") return Response.json(refused, { status: 401 })
|
|
return ok(String(url))
|
|
}
|
|
return sent
|
|
}
|
|
|
|
async function plugin() {
|
|
const saved = []
|
|
const hooks = await GrokAuthPlugin({ client: { auth: { set: async (x) => saved.push(x) } } })
|
|
return { hooks, saved }
|
|
}
|
|
|
|
async function chat(auth) {
|
|
const { hooks, saved } = await plugin()
|
|
const opts = await hooks.auth.loader(async () => auth)
|
|
const res = await opts.fetch("https://cli-chat-proxy.grok.com/v1/responses", { method: "POST", body: '{"model":"grok-4.7","input":"hi"}' })
|
|
return { res, saved }
|
|
}
|
|
|
|
const MODELS = { data: [{ id: "grok-4.7", name: "Grok 4.7", api_backend: "responses", context_window: 256000 }] }
|
|
|
|
test("a request Grok turns away is sent once more with the token Grok Build renewed", async () => {
|
|
const auth = signedIn("tok-0")
|
|
const sent = grok(() => Response.json({ ok: true }))
|
|
const { res, saved } = await chat(auth)
|
|
expect(res.status).toBe(200)
|
|
expect(await res.json()).toEqual({ ok: true })
|
|
expect(sent).toEqual(["Bearer tok-0", "Bearer tok-1"])
|
|
expect(runs()).toBe(1)
|
|
expect(saved.at(-1).body.access).toBe("tok-1")
|
|
})
|
|
|
|
test("a request whose token Grok Build couldn't renew says so, and to add the account again for a home of the plugin's", async () => {
|
|
process.env.FAKE_GROK = "same"
|
|
const auth = signedIn("tok-0")
|
|
const sent = grok(() => Response.json({ ok: true }))
|
|
const { res } = await chat(auth)
|
|
expect(res.status).toBe(401)
|
|
expect(res.headers.get("X-Magpie-Sign-In")).toBe("kept")
|
|
const msg = (await res.json()).error.message
|
|
expect(msg).toContain("Grok Build couldn't renew the sign-in (grok models ran and left the same token)")
|
|
expect(msg).toContain("add the account in magpie again")
|
|
expect(msg).toContain("Invalid or expired credentials")
|
|
expect(msg).not.toContain("grok login")
|
|
expect(msg).not.toMatch(/sign-in has expired/)
|
|
expect(sent).toEqual(["Bearer tok-0"])
|
|
expect(runs()).toBe(1)
|
|
})
|
|
|
|
test("for Grok Build's own home, a token it couldn't renew says to open Grok Build, with what the CLI said", async () => {
|
|
process.env.FAKE_GROK = "fail"
|
|
const auth = signedIn("tok-0")
|
|
process.env.GROK_HOME = home
|
|
grok(() => Response.json({ ok: true }))
|
|
const { res } = await chat(auth)
|
|
expect(res.status).toBe(401)
|
|
const msg = (await res.json()).error.message
|
|
expect(msg).toContain("Grok Build couldn't renew the sign-in (grok models exited 1: silent refresh outcome=Failed(SelfHealing))")
|
|
expect(msg).toContain("open Grok Build and send it a message")
|
|
expect(msg).not.toContain("grok login")
|
|
})
|
|
|
|
test("a model list Grok turns away is asked again with the renewed token", async () => {
|
|
const auth = signedIn("tok-0")
|
|
const sent = grok(() => Response.json(MODELS))
|
|
const { hooks } = await plugin()
|
|
const got = await hooks.provider.models({ id: "grok", models: {} }, { auth })
|
|
expect(Object.keys(got)).toEqual(["grok-4.7"])
|
|
expect(sent).toEqual(["Bearer tok-0", "Bearer tok-1"])
|
|
expect(runs()).toBe(1)
|
|
})
|
|
|
|
test("a model list whose token Grok Build couldn't renew says so, not that the sign-in expired", async () => {
|
|
process.env.FAKE_GROK = "same"
|
|
const auth = signedIn("tok-0")
|
|
grok(() => Response.json(MODELS))
|
|
const { hooks } = await plugin()
|
|
const e = await hooks.provider.models({ id: "grok", models: {} }, { auth }).catch((e) => e)
|
|
expect(e).toBeInstanceOf(Error)
|
|
expect(e.message).toContain("Grok Build couldn't renew the sign-in")
|
|
expect(e.message).not.toMatch(/sign-in has expired|grok login/)
|
|
expect(e.signIn).toBeUndefined()
|
|
})
|
|
|
|
test("a usage read Grok turns away is read again with the renewed token", async () => {
|
|
const auth = signedIn("tok-0")
|
|
const sent = grok(() => Response.json({ config: { creditUsagePercent: 10 } }))
|
|
const { hooks } = await plugin()
|
|
const u = await hooks.auth.usage(async () => auth)
|
|
expect(u).toEqual({ signIn: "kept", windows: [{ name: "Allowance", used: 10 }] })
|
|
expect(sent).toEqual(["Bearer tok-0", "Bearer tok-1"])
|
|
})
|
|
|
|
test("auth.json caught mid-write is read again, not taken as signed out", async () => {
|
|
const auth = signedIn("tok-5")
|
|
writeFileSync(join(home, "auth.json"), '{"a":{"key":"tok-5","em')
|
|
setTimeout(() => signedIn("tok-5"), 150)
|
|
const sent = grok(() => Response.json({ ok: true }))
|
|
const { res } = await chat(auth)
|
|
expect(res.status).toBe(200)
|
|
expect(sent).toEqual(["Bearer tok-5"])
|
|
})
|
|
|
|
test("auth.json that stays torn is the last sign-in read whole there", async () => {
|
|
const auth = signedIn("tok-6")
|
|
const sent = grok(() => Response.json({ ok: true }))
|
|
expect((await chat(auth)).res.status).toBe(200)
|
|
writeFileSync(join(home, "auth.json"), "")
|
|
expect((await chat(auth)).res.status).toBe(200)
|
|
expect(sent).toEqual(["Bearer tok-6", "Bearer tok-6"])
|
|
})
|
|
|
|
test("auth.json torn with nothing read before is unknown: no account is marked signed out", async () => {
|
|
writeFileSync(join(home, "auth.json"), '{"a":{"key":"tok-7"')
|
|
const auth = { type: "oauth", refresh: home, access: "tok-7", expires: Date.now() + 60_000, accountId: "g@x.ai" }
|
|
const { hooks } = await plugin()
|
|
const e = await hooks.auth.refresh(structuredClone(auth)).catch((e) => e)
|
|
expect(e).toBeInstanceOf(Error)
|
|
expect(e.signIn).toBeUndefined()
|
|
expect(e.message).toContain("couldn't be read")
|
|
expect(e.message).not.toContain("not signed in")
|
|
})
|
|
|
|
// plugins#818: a 401 that isn't Grok's judgement of the token, on one
|
|
// Grok Build left as it was and still good, passed by itself minutes later.
|
|
// It is a 503 with Retry-After that keeps the sign-in, never "add the
|
|
// account in magpie again".
|
|
test("a 401 that isn't Grok judging the token, on a token Grok Build left good, is a 503 that passes, not a new sign-in", async () => {
|
|
process.env.FAKE_GROK = "same"
|
|
const auth = signedIn("tok-0")
|
|
const sent = grok(() => Response.json({ ok: true }), PASSING, 1100)
|
|
const { res } = await chat(auth)
|
|
expect(res.status).toBe(503)
|
|
expect(res.headers.get("Retry-After")).toBe("60")
|
|
expect(res.headers.get("X-Magpie-Sign-In")).toBe("kept")
|
|
const err = (await res.json()).error
|
|
expect(err.code).toBe("auth_refused_transient")
|
|
expect(err.message).toContain("Authentication required")
|
|
expect(err.message).toContain("grok models ran and left the same token")
|
|
expect(err.message).toContain(`good till ${later}`)
|
|
expect(err.message).toContain("Grok answered 401 after 1s")
|
|
expect(err.message).not.toMatch(/add the account|grok login|open Grok Build|couldn't renew/)
|
|
expect(sent).toEqual(["Bearer tok-0"])
|
|
expect(runs()).toBe(1)
|
|
})
|
|
|
|
test("Grok judging the token on a 401 still says to sign in again, though the CLI left it good", async () => {
|
|
process.env.FAKE_GROK = "same"
|
|
const auth = signedIn("tok-0")
|
|
grok(() => Response.json({ ok: true }))
|
|
const { res } = await chat(auth)
|
|
expect(res.status).toBe(401)
|
|
const err = (await res.json()).error
|
|
expect(err.code).toBe("sign_in_unrenewed")
|
|
expect(err.message).toContain("add the account in magpie again")
|
|
})
|
|
|
|
test("a passing-looking 401 the CLI failed to renew is still a sign-in it couldn't renew", async () => {
|
|
process.env.FAKE_GROK = "fail"
|
|
const auth = signedIn("tok-0")
|
|
grok(() => Response.json({ ok: true }), PASSING)
|
|
const { res } = await chat(auth)
|
|
expect(res.status).toBe(401)
|
|
const err = (await res.json()).error
|
|
expect(err.code).toBe("sign_in_unrenewed")
|
|
expect(err.message).toContain("grok models exited 1")
|
|
})
|
|
|
|
test("a refused request waits on Grok Build's renewal a bounded time, and the run's end is still waited for", async () => {
|
|
process.env.FAKE_GROK = "slow"
|
|
const { waits } = (await import("./index.mjs"))._internal
|
|
const was = waits.renew
|
|
waits.renew = 300
|
|
try {
|
|
const auth = signedIn("tok-0")
|
|
grok(() => Response.json({ ok: true }), PASSING)
|
|
const at = Date.now()
|
|
const { res } = await chat(auth)
|
|
const took = Date.now() - at
|
|
expect(res.status).toBe(503)
|
|
expect((await res.json()).error.message).toContain("grok models was still running after 0.3s")
|
|
expect(took).toBeLessThan(1900)
|
|
} finally {
|
|
waits.renew = was
|
|
// the fake CLI ends before the test does
|
|
for (let i = 0; i < 100 && !existsSync(join(home, "slow")); i++) await new Promise((r) => setTimeout(r, 50))
|
|
}
|
|
expect(existsSync(join(home, "slow"))).toBe(true)
|
|
})
|
|
|
|
test("a model list refused that way says it passes, and leaves the sign-in be", async () => {
|
|
process.env.FAKE_GROK = "same"
|
|
const auth = signedIn("tok-0")
|
|
grok(() => Response.json(MODELS), PASSING)
|
|
const { hooks } = await plugin()
|
|
const e = await hooks.provider.models({ id: "grok", models: {} }, { auth }).catch((e) => e)
|
|
expect(e).toBeInstanceOf(Error)
|
|
expect(e.message).toContain("Authentication required")
|
|
expect(e.message).not.toMatch(/add the account|couldn't renew/)
|
|
expect(e.signIn).toBeUndefined()
|
|
})
|
|
|
|
test("a usage read refused that way says it passes", async () => {
|
|
process.env.FAKE_GROK = "same"
|
|
const auth = signedIn("tok-0")
|
|
grok(() => Response.json({ config: { creditUsagePercent: 10 } }), PASSING)
|
|
const { hooks } = await plugin()
|
|
const u = await hooks.auth.usage(async () => auth)
|
|
expect(u.signIn).toBe("kept")
|
|
expect(u.error).toContain("Authentication required")
|
|
expect(u.error).not.toMatch(/add the account|couldn't renew/)
|
|
expect(u.said).toBeUndefined()
|
|
})
|