Files
stringke 13a6f4c226 kiro 0.1.40: Kiro sign-ins made elsewhere are imported from a JSON file or paste by their refresh token (#1132)
Accounts signed in to Kiro elsewhere (Kiro Account Manager lists and
exports, kiro2api, the Kiro IDE's kiro-auth-token.json with its
<clientIdHash>.json client, kiro-cli's tokens) are imported in magpie's
"Import accounts from a file…" by their refresh token. Each is renewed
where its kind is renewed (Google/GitHub at prod.us-east-1.auth.desktop.kiro.dev,
Builder ID / Identity Center at oidc.<region>.amazonaws.com with its client)
and named by the email Kiro has for it. Other providers' entries in a
sign-in store are skipped, duplicates are renewed once, at most 100 a time.

A region or profile ARN read from a file can't pick a host any more, on
every route (import, the IDE's file, kiro-cli's DB, a saved sign-in):
regionOf takes only Kiro's API regions (us-east-1, eu-central-1) from a
profile, arnOf keeps only arn:aws:codewhisperer:<region>:<12 digits>:profile/<id>
(else Kiro is asked for it), and oidc/runtime/management/refreshURL refuse
a region that isn't an AWS region's shape.

Version 0.1.40: #1156 published 0.1.39 first, so main was merged into the
branch and the version raised (f8af341f). With arnOf, #1156's test fixture
ARN (account "1") was dropped and its reasoning-replay test went red on
the merge; every test fixture ARN now has a 12-digit account (0b899428).

What was run, on mote with HOME=$(mktemp -d) as CI:
- PR head 41938ff0, packages/kiro: bun test, 202 pass, 0 fail.
- The earlier review's repro (imported Google sign-in, fresh access
  token, profileArn arn:aws:codewhisperer:attacker.example/#:1:profile/X):
  at 41938ff0 every request goes to *.kiro.dev, nothing saved with the
  crafted ARN. With 5dd9e682's index.mjs put back it and all five
  profile-host.test.mjs tests are red (hosts [management.attacker.example]).
- Merged head f8af341f (main at baeb95a4): root bun test, 8771 pass,
  1 fail (reasoning-replay's fixture, above).
- Reviewed head 0b899428: root bun test, 8772 pass, 0 fail, 613 files.
  Main since gained only 2523b43a (packages/agy-cli/test/smoke.mjs).

Read for credential safety: no logging; errors carry no token; refresh
tokens and client secrets go only to Kiro's auth service and AWS OIDC;
an imported sign-in has no dbKey/idePath, so renewing it writes back to
no kiro-cli or IDE file. No .github, dependency or new host.

Not tried: a real Kiro account imported from a real export.
2026-11-15 13:58:11 +08:00

178 lines
7.5 KiB
JavaScript

import { test, expect } from "bun:test"
const model = "glm-5"
const request = { model, output_config: { effort: "high" }, messages: [{ role: "user", content: "hi" }] }
const account = { accountId: "account-a", uid: "enterprise" }
const credentials = { token: "t", tokenType: "SSO_OIDC", idc: true, profile: "arn:aws:codewhisperer:us-east-1:123456789012:profile/P", region: "us-east-1" }
function answer() {
const header = Buffer.concat(Object.entries({ ":message-type": "event", ":event-type": "assistantResponseEvent" }).map(([key, value]) =>
Buffer.concat([Buffer.from([Buffer.byteLength(key)]), Buffer.from(key), Buffer.from([7, 0, Buffer.byteLength(value)]), Buffer.from(value)])))
const payload = Buffer.from(JSON.stringify({ content: "OK" }))
const frame = Buffer.alloc(16 + header.length + payload.length)
frame.writeUInt32BE(frame.length, 0)
frame.writeUInt32BE(header.length, 4)
header.copy(frame, 12)
payload.copy(frame, 12 + header.length)
return new Response(frame)
}
async function setup(name, catalogResponse) {
const { _internal } = await import(`./index.mjs?catalog-${name}`)
const originalFetch = globalThis.fetch
const reads = [], calls = [], statuses = []
globalThis.fetch = async (input, init) => {
const url = new URL(String(input))
if (url.pathname === "/List-Available-Models") {
reads.push(url)
return catalogResponse(url, init)
}
if (url.pathname === "/featureConfiguration") return Response.json({})
if (url.pathname !== "/generateAssistantResponse") throw new Error("unexpected " + url.pathname)
calls.push(JSON.parse(init.body))
const status = statuses.shift()
return status ? new Response("expired", { status }) : answer()
}
return { reads, calls, statuses, generate: _internal.generate, restore: () => { globalThis.fetch = originalFetch } }
}
for (const kind of ["http-error", "empty"]) {
test(`an optional catalog ${kind} still sends the chat request`, async () => {
const s = await setup(kind, () => kind === "http-error" ? Response.json({ message: "Internal Server Error" }, { status: 500 }) : Response.json({ models: [] }))
try {
const res = await s.generate(async () => credentials, account, { ...request, model: "deepseek-3.2" }, undefined, "session")
expect(res.status).toBe(200)
expect((await res.json()).content).toEqual([{ type: "text", text: "OK" }])
expect(s.reads).toHaveLength(1)
expect(s.calls).toHaveLength(1)
expect(s.calls[0].additionalModelRequestFields).toBeUndefined()
} finally {
s.restore()
}
})
}
test("an unlisted model shares one catalog lookup across consecutive requests", async () => {
const s = await setup("absent", () => Response.json({ models: [{ modelId: "claude-sonnet-4.5" }] }))
try {
for (let i = 0; i < 3; i++) {
const res = await s.generate(async () => credentials, account, request, undefined, "session")
expect(res.status).toBe(200)
await res.text()
}
expect(s.reads).toHaveLength(1)
expect(s.calls).toHaveLength(3)
} finally {
s.restore()
}
})
test("concurrent requests share one optional catalog lookup", async () => {
let release, started
const pending = new Promise(resolve => { release = resolve })
const reading = new Promise(resolve => { started = resolve })
const s = await setup("concurrent", () => { started(); return pending })
try {
const requests = Array.from({ length: 3 }, () => s.generate(async () => credentials, account, request, undefined, "session"))
await reading
expect(s.calls).toHaveLength(0)
release(Response.json({ models: [{ modelId: "claude-sonnet-4.5" }] }))
for (const res of await Promise.all(requests)) {
expect(res.status).toBe(200)
await res.text()
}
expect(s.reads).toHaveLength(1)
expect(s.calls).toHaveLength(3)
} finally {
s.restore()
}
})
test("failed catalog lookups expire and are separate for each account and region", async () => {
const originalNow = Date.now
let now = Date.now()
Date.now = () => now
const s = await setup("scope", () => Response.json({ message: "Internal Server Error" }, { status: 500 }))
const call = async (owner, a) => {
const res = await s.generate(async () => a, owner, request, undefined, "session")
expect(res.status).toBe(200)
await res.text()
}
try {
await call(account, credentials)
await call(account, { ...credentials, token: "refreshed" })
expect(s.reads).toHaveLength(1)
await call({ ...account, accountId: "account-b" }, credentials)
await call(account, { ...credentials, region: "eu-central-1", profile: "arn:aws:codewhisperer:eu-central-1:123456789012:profile/P" })
expect(s.reads).toHaveLength(3)
now += 10 * 60 * 1000 + 1
await call(account, credentials)
expect(s.reads).toHaveLength(4)
} finally {
Date.now = originalNow
s.restore()
}
})
const nativeModel = () => ({ modelId: "gpt-5.6-luna", additionalModelRequestFieldsSchema: { properties: { reasoning: { properties: { effort: { enum: ["low", "high"] } } } } } })
test("native fields use the selected account's regional catalog", async () => {
const s = await setup("native-scope", (url, init) => Response.json({ models: [
init.headers.Authorization === "Bearer t" && url.hostname.includes("us-east-1") ? nativeModel() : { modelId: "gpt-5.6-luna" },
] }))
const call = async (owner, a) => {
const res = await s.generate(async () => a, owner, { ...request, model: "gpt-5.6-luna" }, undefined, "session")
expect(res.status).toBe(200)
await res.text()
}
try {
await call(account, credentials)
await call({ ...account, accountId: "account-b" }, { ...credentials, token: "other" })
await call(account, { ...credentials, region: "eu-central-1", profile: "arn:aws:codewhisperer:eu-central-1:123456789012:profile/P" })
await call(account, credentials)
expect(s.reads).toHaveLength(3)
expect(s.calls.map(body => body.additionalModelRequestFields)).toEqual([
{ reasoning: { effort: "high" } }, undefined, undefined, { reasoning: { effort: "high" } },
])
} finally {
s.restore()
}
})
test("a failed catalog refresh retains the account's last successful native fields", async () => {
const originalNow = Date.now
let now = Date.now(), reads = 0
Date.now = () => now
const s = await setup("last-good", () => ++reads === 1 ? Response.json({ models: [nativeModel()] }) : new Response("unavailable", { status: 500 }))
const call = async () => {
const res = await s.generate(async () => credentials, account, { ...request, model: "gpt-5.6-luna" }, undefined, "session")
expect(res.status).toBe(200)
await res.text()
}
try {
await call()
now += 10 * 60 * 1000 + 1
await call()
await call()
expect(s.reads).toHaveLength(2)
expect(s.calls.map(body => body.additionalModelRequestFields)).toEqual(Array.from({ length: 3 }, () => ({ reasoning: { effort: "high" } })))
} finally {
Date.now = originalNow
s.restore()
}
})
test("a token refresh keeps the failed catalog lookup cached", async () => {
const s = await setup("refresh", () => Response.json({ message: "Internal Server Error" }, { status: 500 }))
s.statuses.push(403)
try {
const res = await s.generate(async (_, stale) => ({ ...credentials, token: stale ? "refreshed" : "t" }), account, request, undefined, "session")
expect(res.status).toBe(200)
expect((await res.json()).content).toEqual([{ type: "text", text: "OK" }])
expect(s.reads).toHaveLength(1)
expect(s.calls).toHaveLength(2)
} finally {
s.restore()
}
})