Skip to content

Commit dddc674

Browse files
authored
Merge pull request #1032 from lidge-jun/codex/lane-10-kiro-profile-arn
fix(kiro): capture profileArn from whoami and classify profileArn-required 400s (#993)
2 parents 54dac6a + 0338d07 commit dddc674

5 files changed

Lines changed: 217 additions & 6 deletions

File tree

‎src/adapters/kiro-errors.ts‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -109,6 +109,17 @@ function classifyKiroFailure(
109109
retryable: false,
110110
};
111111
}
112+
// #993: a gated model demanding a profileArn gets a stable, actionable code
113+
// instead of the generic validation bucket. Non-retryable by definition.
114+
if (evidence.includes("profilearn") && evidence.includes("required")) {
115+
return {
116+
message: "kiro_profile_required: Kiro requires a CodeWhisperer profileArn for this account and model. Re-login or re-import the matching Kiro account (ocx account login kiro --reauth) so the profile is captured, then retry.",
117+
status: 400,
118+
errorType: "invalid_request_error",
119+
code: "kiro_profile_required",
120+
retryable: false,
121+
};
122+
}
112123
if (
113124
evidence.includes("insufficient_quota")
114125
|| evidence.includes("quota exhausted")

‎src/oauth/kiro.ts‎

Lines changed: 50 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -172,13 +172,37 @@ async function defaultKiroCliRunner(args: string[], signal?: AbortSignal): Promi
172172
}
173173
}
174174

175-
async function readKiroCliIdentity(runner: KiroCliRunner, signal?: AbortSignal): Promise<{ email?: string }> {
175+
/** Kiro profile ARN structure: arn:<partition>:codewhisperer:<region>:<account>:profile/<id> */
176+
const KIRO_PROFILE_ARN_PATTERN = /^arn:[a-z0-9-]+:codewhisperer:[a-z0-9-]+:\d{12}:profile\/[A-Za-z0-9-]+$/;
177+
const KIRO_PROFILE_ARN_MAX_LENGTH = 256;
178+
179+
function parseKiroProfileArn(value: unknown): string | undefined {
180+
if (typeof value !== "string") return undefined;
181+
const trimmed = value.trim();
182+
if (trimmed.length === 0 || trimmed.length > KIRO_PROFILE_ARN_MAX_LENGTH) return undefined;
183+
return KIRO_PROFILE_ARN_PATTERN.test(trimmed) ? trimmed : undefined;
184+
}
185+
186+
function profileArnFromWhoami(parsed: Record<string, unknown>): string | undefined {
187+
// Only narrowly-named documented-ish shapes; never invent an ARN (#993).
188+
return parseKiroProfileArn(parsed.profileArn)
189+
?? parseKiroProfileArn(parsed.profile_arn)
190+
?? (parsed.profile && typeof parsed.profile === "object" && !Array.isArray(parsed.profile)
191+
? parseKiroProfileArn((parsed.profile as Record<string, unknown>).arn)
192+
: undefined);
193+
}
194+
195+
async function readKiroCliIdentity(runner: KiroCliRunner, signal?: AbortSignal): Promise<{ email?: string; profileArn?: string }> {
176196
try {
177197
const result = await runner(["whoami", "--format", "json"], signal);
178198
if (result.exitCode !== 0) return {};
179-
const parsed = JSON.parse(result.stdout) as { email?: unknown };
199+
const parsed = JSON.parse(result.stdout) as Record<string, unknown>;
180200
const email = typeof parsed.email === "string" ? parsed.email.trim().toLowerCase() : "";
181-
return email && email.length <= 320 ? { email } : {};
201+
const profileArn = profileArnFromWhoami(parsed);
202+
return {
203+
...(email && email.length <= 320 ? { email } : {}),
204+
...(profileArn ? { profileArn } : {}),
205+
};
182206
} catch {
183207
return {};
184208
}
@@ -251,14 +275,34 @@ async function oauthCredentialFromImported(
251275
runner: KiroCliRunner,
252276
signal?: AbortSignal,
253277
): Promise<OAuthCredentials> {
254-
const identity = imported.source === "sqlite" ? await readKiroCliIdentity(runner, signal) : {};
255-
const metadata = metadataFromImported(imported);
278+
let identity: { email?: string; profileArn?: string } = {};
279+
if (imported.source === "sqlite") {
280+
identity = await readKiroCliIdentity(runner, signal);
281+
// Session-switch race (#993 review): another process may have switched the
282+
// active Kiro CLI session between the SQLite read and whoami. Accept
283+
// whoami's identity only when the session token STILL matches the import —
284+
// refresh token, or access token when refresh is absent.
285+
if (identity.profileArn !== undefined) {
286+
const current = readKiroCliSqliteCredential();
287+
const importedKey = imported.refresh || imported.access;
288+
const currentKey = current ? current.refresh || current.access : "";
289+
if (!current || currentKey !== importedKey) identity = {};
290+
}
291+
}
292+
// Builder ID imports often lack a profileArn in SQLite; whoami against the
293+
// SAME active CLI session can supply it (#993). Imported stays authoritative.
294+
const resolvedProfileArn = imported.profileArn ?? identity.profileArn;
295+
const metadata: KiroOAuthMetadata | undefined = (() => {
296+
const base = metadataFromImported(imported) ?? {};
297+
if (resolvedProfileArn && !base.profileArn) base.profileArn = resolvedProfileArn;
298+
return Object.keys(base).length > 0 ? base : undefined;
299+
})();
256300
return {
257301
access: imported.access,
258302
refresh: imported.refresh,
259303
expires: imported.expires,
260304
source: imported.source === "json" ? "credential-file" : "local-cli",
261-
...(imported.profileArn ? { accountId: imported.profileArn } : {}),
305+
...(resolvedProfileArn ? { accountId: resolvedProfileArn } : {}),
262306
...(identity.email ? { email: identity.email } : {}),
263307
...(metadata ? { kiro: metadata } : {}),
264308
};

‎tests/kiro-oauth.test.ts‎

Lines changed: 125 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -425,6 +425,131 @@ describe("kiro oauth — import-first", () => {
425425
expect(existsSync(kiroCliRecoveryPath())).toBe(false);
426426
});
427427

428+
test("whoami supplies a valid profileArn when the SQLite import lacks one (#993)", async () => {
429+
const arn = "arn:aws:codewhisperer:us-east-1:123456789012:profile/ABCD1234";
430+
seedKiroCliDb({ access_token: "aoa-builder", refresh_token: "rt-builder" });
431+
const runner = async (args: string[]) => {
432+
if (args[0] === "whoami") {
433+
return { exitCode: 0, stdout: JSON.stringify({ email: "[email protected]", profileArn: arn }) };
434+
}
435+
throw new Error(`unexpected Kiro CLI command: ${args[0]}`);
436+
};
437+
438+
const cred = await loginKiro({}, { cliRunner: runner });
439+
440+
expect(cred).toMatchObject({
441+
access: "aoa-builder",
442+
accountId: arn,
443+
kiro: { profileArn: arn },
444+
});
445+
});
446+
447+
test("a nested profile.arn shape is accepted (#993)", async () => {
448+
const arn = "arn:aws:codewhisperer:eu-west-1:123456789012:profile/XY-99";
449+
seedKiroCliDb({ access_token: "aoa-nested", refresh_token: "rt-nested" });
450+
const nestedRunner = async (args: string[]) => {
451+
if (args[0] === "whoami") return { exitCode: 0, stdout: JSON.stringify({ profile: { arn } }) };
452+
throw new Error("unexpected");
453+
};
454+
const nested = await loginKiro({}, { cliRunner: nestedRunner });
455+
expect(nested.accountId).toBe(arn);
456+
});
457+
458+
test("a malformed whoami ARN is ignored without breaking the login (#993)", async () => {
459+
seedKiroCliDb({ access_token: "aoa-bad", refresh_token: "rt-bad" });
460+
const badRunner = async (args: string[]) => {
461+
if (args[0] === "whoami") {
462+
return { exitCode: 0, stdout: JSON.stringify({ profileArn: "not-an-arn", email: "[email protected]" }) };
463+
}
464+
throw new Error("unexpected");
465+
};
466+
const bad = await loginKiro({}, { cliRunner: badRunner });
467+
// Malformed ARN: login still succeeds for ungated models, but no ARN is borrowed.
468+
expect(bad.accountId).toBeUndefined();
469+
expect(bad.kiro?.profileArn).toBeUndefined();
470+
});
471+
472+
test("an imported SQLite profileArn stays authoritative over whoami (#993)", async () => {
473+
const sqliteArn = "arn:aws:codewhisperer:us-east-1:123456789012:profile/SQLITE";
474+
const whoamiArn = "arn:aws:codewhisperer:us-east-1:123456789012:profile/WHOAMI";
475+
seedKiroCliDb({ access_token: "aoa-both", refresh_token: "rt-both", profile_arn: sqliteArn });
476+
const runner = async (args: string[]) => {
477+
if (args[0] === "whoami") return { exitCode: 0, stdout: JSON.stringify({ profileArn: whoamiArn }) };
478+
throw new Error("unexpected");
479+
};
480+
const cred = await loginKiro({}, { cliRunner: runner });
481+
expect(cred.accountId).toBe(sqliteArn);
482+
});
483+
484+
test("a session switch between the SQLite read and whoami discards whoami's ARN (#993)", async () => {
485+
const arnB = "arn:aws:codewhisperer:us-east-1:123456789012:profile/OTHER-ACCOUNT";
486+
seedKiroCliDb({ access_token: "aoa-accountA", refresh_token: "rt-accountA" });
487+
const runner = async (args: string[]) => {
488+
if (args[0] === "whoami") {
489+
// Another process switches the active CLI session mid-flight.
490+
removeKiroCliDb();
491+
seedKiroCliDb({ access_token: "aoa-accountB", refresh_token: "rt-accountB" });
492+
return { exitCode: 0, stdout: JSON.stringify({ email: "[email protected]", profileArn: arnB }) };
493+
}
494+
throw new Error("unexpected");
495+
};
496+
const cred = await loginKiro({}, { cliRunner: runner });
497+
// Account A's token must never carry account B's ARN.
498+
expect(cred.accountId).toBeUndefined();
499+
expect(cred.kiro?.profileArn).toBeUndefined();
500+
});
501+
502+
test("the discarded whoami identity takes the email with it, not just the ARN (#993)", async () => {
503+
// Review finding: asserting only that the ARN is absent also passes against
504+
// pre-fix code, which ignored whoami's ARN entirely. The email is the part
505+
// that pre-fix code WOULD have kept, so it is the assertion that actually
506+
// proves the mismatch path clears the whole identity.
507+
const arnB = "arn:aws:codewhisperer:us-east-1:123456789012:profile/OTHER-ACCOUNT";
508+
seedKiroCliDb({ access_token: "aoa-accountA", refresh_token: "rt-accountA" });
509+
const runner = async (args: string[]) => {
510+
if (args[0] === "whoami") {
511+
removeKiroCliDb();
512+
seedKiroCliDb({ access_token: "aoa-accountB", refresh_token: "rt-accountB" });
513+
return { exitCode: 0, stdout: JSON.stringify({ email: "[email protected]", profileArn: arnB }) };
514+
}
515+
throw new Error("unexpected");
516+
};
517+
const cred = await loginKiro({}, { cliRunner: runner });
518+
expect(cred.email).toBeUndefined();
519+
expect(cred.kiro?.profileArn).toBeUndefined();
520+
});
521+
522+
test("with no refresh token the access token is the revalidation key (#993)", async () => {
523+
// The implementation falls back to the access token when refresh is absent.
524+
// Without this case that branch is unexercised in either direction.
525+
const arn = "arn:aws:codewhisperer:us-east-1:123456789012:profile/BUILDER";
526+
seedKiroCliDb({ access_token: "aoa-only" });
527+
const runner = async (args: string[]) => {
528+
if (args[0] === "whoami") {
529+
return { exitCode: 0, stdout: JSON.stringify({ email: "[email protected]", profileArn: arn }) };
530+
}
531+
throw new Error("unexpected");
532+
};
533+
const cred = await loginKiro({}, { cliRunner: runner });
534+
expect(cred.kiro?.profileArn).toBe(arn);
535+
});
536+
537+
test("an access-token-only session that changes under whoami is rejected (#993)", async () => {
538+
const arnB = "arn:aws:codewhisperer:us-east-1:123456789012:profile/OTHER-ACCOUNT";
539+
seedKiroCliDb({ access_token: "aoa-accountA" });
540+
const runner = async (args: string[]) => {
541+
if (args[0] === "whoami") {
542+
removeKiroCliDb();
543+
seedKiroCliDb({ access_token: "aoa-accountB" });
544+
return { exitCode: 0, stdout: JSON.stringify({ email: "[email protected]", profileArn: arnB }) };
545+
}
546+
throw new Error("unexpected");
547+
};
548+
const cred = await loginKiro({}, { cliRunner: runner });
549+
expect(cred.kiro?.profileArn).toBeUndefined();
550+
expect(cred.email).toBeUndefined();
551+
});
552+
428553
test("invalid recovery data names the file the operator must remove", async () => {
429554
seedKiroCliDb({ access_token: "aoa-prior", refresh_token: "rt-prior" });
430555
writeFileSync(kiroCliRecoveryPath(), "not a recovery database", { mode: 0o600 });

‎tests/kiro-retry.test.ts‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -330,6 +330,22 @@ describe("kiro retry fetch", () => {
330330
expect(mock.calls).toHaveLength(1);
331331
});
332332

333+
test("a profileArn-required 400 classifies as kiro_profile_required with actionable copy (#993)", async () => {
334+
const mock = mockFetch([
335+
new Response(JSON.stringify({
336+
__type: "ValidationException",
337+
message: "profileArn is required for this account",
338+
}), { status: 400 }),
339+
]);
340+
const res = await fetchKiroWithRetry(request, { timeoutMs: 5_000 });
341+
const text = await res.text();
342+
expect(res.status).toBe(400);
343+
expect(text).toContain("kiro_profile_required");
344+
expect(text).toContain("ocx account login kiro --reauth");
345+
// Non-retryable: exactly one upstream call.
346+
expect(mock.calls).toHaveLength(1);
347+
});
348+
333349
test("normalizes final transient 429 after bounded adapter retries", async () => {
334350
const mock = mockFetch([
335351
new Response("rate limited", { status: 429, headers: { "Retry-After": "0" } }),

‎tests/kiro-stream.test.ts‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1096,6 +1096,21 @@ describe("kiro adapter — parseStream", () => {
10961096
expect(errors[0]).not.toContain("{");
10971097
});
10981098

1099+
test("an event-stream profileArn-required exception classifies as kiro_profile_required (#993)", async () => {
1100+
const payload = JSON.stringify({
1101+
__type: "ValidationException",
1102+
message: "profileArn is required for this account",
1103+
});
1104+
const frame = encodeMessage({ ":message-type": "exception", ":exception-type": "ValidationException" }, enc.encode(payload));
1105+
const errors: string[] = [];
1106+
for await (const e of createKiroAdapter(provider).parseStream(new Response(streamOf(frame)))) {
1107+
if (e.type === "error") errors.push(e.message);
1108+
}
1109+
expect(errors).toHaveLength(1);
1110+
expect(errors[0]).toContain("kiro_profile_required");
1111+
expect(errors[0]).toContain("ocx account login kiro --reauth");
1112+
});
1113+
10991114
test("auth and model exceptions become actionable Kiro errors", async () => {
11001115
const authFrame = encodeMessage(
11011116
{ ":message-type": "exception", ":exception-type": "AccessDeniedException" },

0 commit comments

Comments
 (0)