Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 36 additions & 1 deletion open-sse/executors/kiro.ts
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,37 @@ function ensureKiroUsage(state: KiroStreamState) {
};
}

/**
* Resolve the AWS region for a Kiro/CodeWhisperer connection. Enterprise AWS IAM Identity
* Center accounts are region-bound: the access token, the Q Developer profile ARN and the
* runtime endpoint must all match the region the IdC instance lives in (e.g. eu-central-1).
* A request signed for one region is rejected by another ("bearer token is invalid"), and a
* regional profileArn sent to us-east-1 fails with "Improperly formed request". Falls back to
* the region embedded in the profileArn, then us-east-1 (the AWS Builder ID default).
*/
export function resolveKiroRegion(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

According to the Repository Style Guide (Rule 9), tests must be included when changing production code in open-sse/ or src/. Please add unit tests (e.g., in tests/) to cover the new resolveKiroRegion and kiroRuntimeHost functions, verifying correct region resolution and host mapping.

References
  1. Always include tests when changing production code (src/, open-sse/, electron/, bin/). (link)

credentials: { providerSpecificData?: unknown } | null | undefined
): string {
const psd = (credentials?.providerSpecificData || {}) as Record<string, unknown>;
const region = typeof psd.region === "string" ? psd.region.trim() : "";

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The region string retrieved from providerSpecificData is trimmed but not normalized to lowercase. If the region is stored in uppercase or mixed case (e.g., EU-CENTRAL-1), comparison checks like region === "us-east-1" will fail, and the regional host will be constructed with uppercase letters (e.g., https://q.EU-CENTRAL-1.amazonaws.com), which can cause issues with host resolution or signature verification. Normalize the region to lowercase.

Suggested change
const region = typeof psd.region === "string" ? psd.region.trim() : "";
const region = typeof psd.region === "string" ? psd.region.trim().toLowerCase() : "";

if (region) return region;
const arn = typeof psd.profileArn === "string" ? psd.profileArn : "";
const match = arn.match(/^arn:aws:codewhisperer:([a-z0-9-]+):/);
return match ? match[1] : "us-east-1";
}

/**
* CodeWhisperer/Amazon Q runtime host for a region. us-east-1 keeps the legacy
* codewhisperer.us-east-1 host (AWS Builder ID); other regions use the regional Amazon Q
* endpoint q.{region}.amazonaws.com — codewhisperer.{region}.amazonaws.com does not resolve
* for non-us-east-1 regions.
*/
export function kiroRuntimeHost(region: string): string {
return region === "us-east-1"
? "https://codewhisperer.us-east-1.amazonaws.com"
: `https://q.${region}.amazonaws.com`;
}

/**
* KiroExecutor - Executor for Kiro AI (AWS CodeWhisperer)
* Uses AWS CodeWhisperer streaming API with AWS EventStream binary format
Expand Down Expand Up @@ -228,7 +259,11 @@ export class KiroExecutor extends BaseExecutor {
log,
upstreamExtraHeaders,
}: ExecuteInput) {
const url = this.buildUrl(model, stream, 0);
// Route to the region-specific CodeWhisperer/Amazon Q endpoint. Enterprise IAM Identity
// Center accounts (e.g. eu-central-1) are rejected by the default us-east-1 host; only the
// regional endpoint accepts the region-bound token + profileArn.
const region = resolveKiroRegion(credentials);
const url = `${kiroRuntimeHost(region)}/generateAssistantResponse`;
const headers = this.buildHeaders(credentials, stream);
mergeUpstreamExtraHeaders(headers, upstreamExtraHeaders);
const transformedBody = await this.transformRequest(model, body, stream, credentials);
Expand Down
17 changes: 16 additions & 1 deletion open-sse/services/usage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3005,14 +3005,29 @@ async function getKiroUsage(accessToken?: string, providerSpecificData?: JsonRec
return { message: "Kiro connected. Profile ARN not available for quota tracking." };
}

// Enterprise IAM Identity Center accounts are region-bound: the profileArn, token and
// endpoint must all match the region. Derive the region from the stored region (preferred)
// or the profileArn, then route to the regional Amazon Q endpoint (us-east-1 keeps the
// legacy codewhisperer host; codewhisperer.{region} does not resolve for other regions).
const regionFromArn =
typeof profileArn === "string"
? profileArn.match(/^arn:aws:codewhisperer:([a-z0-9-]+):/)?.[1]
: undefined;
const region =
(typeof providerSpecificData?.region === "string" && providerSpecificData.region.trim()) ||
regionFromArn ||
"us-east-1";
Comment on lines +3016 to +3020

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Similar to the executor, the region retrieved from providerSpecificData here is not normalized to lowercase. If it contains uppercase characters, the comparison region === "us-east-1" will fail, routing us-east-1 requests to https://q.US-EAST-1.amazonaws.com instead of CODEWHISPERER_BASE_URL. Normalize the region to lowercase.

Suggested change
const region =
(typeof providerSpecificData?.region === "string" && providerSpecificData.region.trim()) ||
regionFromArn ||
"us-east-1";
const region =
(typeof providerSpecificData?.region === "string" && providerSpecificData.region.trim().toLowerCase()) ||
regionFromArn ||
"us-east-1";

const usageBaseUrl =
region === "us-east-1" ? CODEWHISPERER_BASE_URL : `https://q.${region}.amazonaws.com`;

// Kiro uses AWS CodeWhisperer GetUsageLimits API
const payload = {
origin: "AI_EDITOR",
profileArn: profileArn,
resourceType: "AGENTIC_REQUEST",
};

const response = await fetch(CODEWHISPERER_BASE_URL, {
const response = await fetch(usageBaseUrl, {
method: "POST",
headers: {
Authorization: `Bearer ${accessToken}`,
Expand Down
14 changes: 10 additions & 4 deletions scripts/build/pack-artifact-policy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,10 +101,16 @@ export const PACK_ARTIFACT_ROOT_ALLOWED_PATH_PREFIXES: string[] = [
"@omniroute/opencode-plugin/",
"@omniroute/opencode-provider/",
"bin/cli/",
"open-sse/mcp-server/schemas/",
"open-sse/mcp-server/tools/",
"src/lib/cli-helper/",
"src/shared/contracts/",
// Broad open-sse + src source dirs added to package.json "files" in v3.8.21
// to allow TypeScript-first imports from the published package.
"open-sse/",
"src/domain/",
"src/lib/",
"src/mitm/",
"src/server/",
"src/shared/",
"src/sse/",
"src/types/",
];

export const PACK_ARTIFACT_REQUIRED_PATHS: string[] = [
Expand Down
37 changes: 37 additions & 0 deletions src/lib/oauth/providers/kiro.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,41 @@ export const kiro = {
}

if (data.accessToken) {
// Enterprise IAM Identity Center accounts require a region-bound Q Developer profileArn on
// every CodeWhisperer call; without it AWS returns 403 "User is not authorized to make this
// call". The device-code flow does not return one, so discover it via ListAvailableProfiles
// against the same regional endpoint the token was issued for (best-effort; AWS Builder ID
// accounts legitimately have no profile and this simply yields none).
let profileArn: string | undefined;
try {
const runtimeHost =
tokenRegion === "us-east-1"
? "https://codewhisperer.us-east-1.amazonaws.com"
: `https://q.${tokenRegion}.amazonaws.com`;
const profRes = await fetch(`${runtimeHost}/`, {
method: "POST",
headers: {
"Content-Type": "application/x-amz-json-1.0",
Accept: "application/json",
"x-amz-target": "AmazonCodeWhispererService.ListAvailableProfiles",
Authorization: `Bearer ${data.accessToken}`,
},
body: JSON.stringify({ maxResults: 10 }),
});
if (profRes.ok) {
const profData = await profRes.json();
const profiles = Array.isArray(profData?.profiles) ? profData.profiles : [];
const matched =
profiles.find(
(p: { arn?: string }) =>
typeof p?.arn === "string" && p.arn.includes(`:${tokenRegion}:`)
) || profiles[0];
if (matched && typeof matched.arn === "string") profileArn = matched.arn;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

There are two issues here:

  1. The fetch call to ListAvailableProfiles does not have a timeout. If the network hangs or AWS is slow, this fetch will block the device-code polling/login flow indefinitely. Adding a timeout (e.g., 10 seconds) ensures the login flow remains responsive.
  2. tokenRegion is not normalized to lowercase. If it contains uppercase characters, the comparison tokenRegion === "us-east-1" will fail, and the profile ARN lookup p.arn.includes(":${tokenRegion}:") might also fail since ARNs typically use lowercase regions. Normalize the region to lowercase before using it.
      try {
        const normalizedRegion = tokenRegion.toLowerCase();
        const runtimeHost =
          normalizedRegion === "us-east-1"
            ? "https://codewhisperer.us-east-1.amazonaws.com"
            : `https://q.${normalizedRegion}.amazonaws.com`;
        const profRes = await fetch(`${runtimeHost}/`, {
          method: "POST",
          headers: {
            "Content-Type": "application/x-amz-json-1.0",
            Accept: "application/json",
            "x-amz-target": "AmazonCodeWhispererService.ListAvailableProfiles",
            Authorization: `Bearer ${data.accessToken}`
          },
          body: JSON.stringify({ maxResults: 10 }),
          signal: AbortSignal.timeout(10000)
        });
        if (profRes.ok) {
          const profData = await profRes.json();
          const profiles = Array.isArray(profData?.profiles) ? profData.profiles : [];
          const matched =
            profiles.find(
              (p: { arn?: string }) =>
                typeof p?.arn === "string" && p.arn.includes(`:${normalizedRegion}:`)
            ) || profiles[0];
          if (matched && typeof matched.arn === "string") profileArn = matched.arn;
        }

} catch {
// Best-effort profile discovery — never block login on it.
}

return {
ok: true,
data: {
Expand All @@ -111,6 +146,7 @@ export const kiro = {
_clientId: extraData?._clientId,
_clientSecret: extraData?._clientSecret,
_region: tokenRegion,
_profileArn: profileArn,
},
};
}
Expand All @@ -131,6 +167,7 @@ export const kiro = {
clientId: tokens._clientId,
clientSecret: tokens._clientSecret,
region: tokens._region,
...(tokens._profileArn ? { profileArn: tokens._profileArn } : {}),
},
}),
};