fix(kiro): canonicalize tool history and route API keys correctly

Route API-key inference through Amazon Q first, enforce adjacent
one-to-one tool use/result pairs after session replay, and treat
payload-invalid HTTP 400 as terminal.
This commit is contained in:
nguyenha935
2026-07-29 19:27:41 +07:00
parent 44c7b34837
commit 16cb40fda1
14 changed files with 1050 additions and 465 deletions
+4 -4
View File
@@ -5,8 +5,8 @@ import { createProviderConnection } from "@/models";
/**
* POST /api/oauth/kiro/api-key
* Import a Kiro API key (headless auth). The key is a long-lived bearer
* credential — there is no refresh token. It is validated by listing
* CodeWhisperer profiles, then stored with authMethod="api_key".
* credential — there is no refresh token. It is validated against the Amazon
* Q model catalog, then stored with authMethod="api_key".
*/
export async function POST(request) {
try {
@@ -21,7 +21,7 @@ export async function POST(request) {
const kiroService = new KiroService();
// Validate the key and resolve its profileArn via ListAvailableProfiles
// Validate the key against the same Amazon Q surface used for inference.
const credential = await kiroService.validateApiKey(
apiKey,
region || "us-east-1"
@@ -40,7 +40,7 @@ export async function POST(request) {
expiresAt: new Date(Date.now() + 365 * 24 * 60 * 60 * 1000).toISOString(),
email: email || null,
providerSpecificData: {
profileArn: credential.profileArn,
...(credential.profileArn ? { profileArn: credential.profileArn } : {}),
region: credential.region,
authMethod: "api_key",
provider: "API Key",
+40 -12
View File
@@ -260,11 +260,9 @@ export class KiroService {
}
/**
* List available CodeWhisperer profiles for a token (or API key) and return
* the best-matching profileArn. AWS SSO OIDC logins return no profileArn, so
* it must be fetched separately — the same call works for API-key auth.
* Accepts both `arn` and `profileArn` response field names (the API-key
* JSON-1.0 surface returns `arn`).
* List available CodeWhisperer profiles for OAuth/IDC tokens and return the
* best-matching profileArn. API keys use the Amazon Q model catalog instead;
* ListAvailableProfiles does not support TokenType=API_KEY.
*/
async listAvailableProfiles(accessToken, region = "us-east-1") {
assertValidAwsRegion(region);
@@ -294,10 +292,41 @@ export class KiroService {
}
/**
* Validate an API-key credential by listing profiles with it. API keys are
* long-lived bearer tokens (no refresh), so the only way to validate one is
* to make an authenticated CodeWhisperer call. Returns a credential object
* ready to persist as a "kiro" connection with authMethod="api_key".
* Validate an API key against the Amazon Q model catalog. A bearer-only call
* to ListAvailableProfiles can return HTTP 200 with an empty list for an
* arbitrary key, so it is not proof that the key can run inference.
*/
async listAvailableApiKeyModels(apiKey, region = "us-east-1") {
assertValidAwsRegion(region);
const params = new URLSearchParams({ origin: "AI_EDITOR" });
const endpoint = `https://q.${region}.amazonaws.com/ListAvailableModels?${params}`;
const response = await fetch(endpoint, {
method: "GET",
headers: {
"Authorization": `Bearer ${apiKey}`,
"TokenType": "API_KEY",
"Accept": "application/json",
"User-Agent": "AWS-SDK-JS/3.0.0 kiro-ide/1.0.0",
"X-Amz-User-Agent": "aws-sdk-js/3.0.0 kiro-ide/1.0.0",
},
});
if (!response.ok) {
const error = await response.text();
throw new Error(`Failed to list API-key models: ${error}`);
}
const data = await response.json();
const models = Array.isArray(data?.models) ? data.models : [];
if (models.length === 0) {
throw new Error("API key returned no available models");
}
return models;
}
/**
* Validate an API-key credential through the same Amazon Q surface used for
* inference. API keys are account-bound but do not require a profileArn.
*/
async validateApiKey(apiKey, region = "us-east-1") {
if (!apiKey || typeof apiKey !== "string" || !apiKey.trim()) {
@@ -305,9 +334,8 @@ export class KiroService {
}
const trimmed = apiKey.trim();
let profileArn = null;
try {
profileArn = await this.listAvailableProfiles(trimmed, region);
await this.listAvailableApiKeyModels(trimmed, region);
} catch (error) {
throw new Error(`API key validation failed: ${error.message}`);
}
@@ -315,7 +343,7 @@ export class KiroService {
return {
accessToken: trimmed,
refreshToken: null,
profileArn,
profileArn: null,
region,
authMethod: "api_key",
};