feat(kiro): add external_idp CLIProxyAPI import for Microsoft SSO

Import Kiro accounts authenticated via Microsoft Entra/365 SSO using
CLIProxyAPI JSON. Adds external_idp refresh path (form-encoded OAuth2,
Microsoft login host allowlist), TokenType: EXTERNAL_IDP header for
runtime and usage/quota requests, dashboard import UI, and unit tests.
Scoped to authMethod === "external_idp"; existing Kiro auth unchanged.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Stevanus Pangau
2026-06-26 11:39:33 +07:00
committed by decolua
parent 49a3ec7a72
commit a4f44e3e12
7 changed files with 554 additions and 5 deletions

View File

@@ -26,7 +26,11 @@ export class KiroExecutor extends BaseExecutor {
// exactly like an OAuth access token, but with an extra `tokentype: API_KEY`
// header so CodeWhisperer treats it as a long-lived API key rather than an
// OIDC/social access token. Mirrors the Kiro IDE headless-auth behavior.
const isApiKey = credentials?.providerSpecificData?.authMethod === "api_key";
// Enterprise / Microsoft Entra (external_idp) tokens are OAuth access tokens,
// but CodeWhisperer requires TokenType=EXTERNAL_IDP to bind them to profiles.
const authMethod = credentials?.providerSpecificData?.authMethod;
const isApiKey = authMethod === "api_key";
const isExternalIdp = authMethod === "external_idp";
const apiKey = credentials?.apiKey || (isApiKey ? credentials?.accessToken : null);
if (isApiKey && apiKey) {
@@ -34,6 +38,9 @@ export class KiroExecutor extends BaseExecutor {
headers["tokentype"] = "API_KEY";
} else if (credentials.accessToken) {
headers["Authorization"] = `Bearer ${credentials.accessToken}`;
if (isExternalIdp) {
headers["TokenType"] = "EXTERNAL_IDP";
}
}
return headers;
@@ -49,13 +56,16 @@ export class KiroExecutor extends BaseExecutor {
* BaseExecutor.execute() returns immediately (only 429 / network errors fall
* through to the next host). So for api-key auth we must try the *.amazonaws.com
* CodeWhisperer hosts FIRST, mirroring the Kiro-Go reference fork which never
* routes api-key traffic through kiro.dev. OAuth keeps the default order
* (kiro.dev first) since its token is what that gateway accepts.
* routes api-key traffic through kiro.dev. External IdP enterprise tokens also
* use the CodeWhisperer surface, with the `TokenType: EXTERNAL_IDP` header.
* Other OAuth methods keep the default order (kiro.dev first) since their
* tokens are what that gateway accepts.
*/
getOrderedBaseUrls(credentials) {
const baseUrls = this.getBaseUrls();
const isApiKey = credentials?.providerSpecificData?.authMethod === "api_key";
if (!isApiKey) return baseUrls;
const authMethod = credentials?.providerSpecificData?.authMethod;
const isCodeWhispererSurface = authMethod === "api_key" || authMethod === "external_idp";
if (!isCodeWhispererSurface) return baseUrls;
const amazon = baseUrls.filter((u) => u.includes("amazonaws.com"));
const others = baseUrls.filter((u) => !u.includes("amazonaws.com"));
return amazon.length > 0 ? [...amazon, ...others] : baseUrls;

View File

@@ -2,6 +2,7 @@ import { PROVIDERS, PROVIDER_OAUTH } from "../../config/providers.js";
import { OAUTH_ENDPOINTS, GITHUB_COPILOT } from "../../config/appConstants.js";
import { proxyAwareFetch } from "../../utils/proxyFetch.js";
import { dedupRefresh } from "./dedup.js";
import { buildExternalIdpRefreshParams } from "../../../src/lib/oauth/kiroExternalIdp.js";
let _xaiServiceSingleton = null;
export async function refreshXaiToken(refreshToken, log) {
@@ -309,6 +310,49 @@ export async function refreshKiroToken(refreshToken, providerSpecificData, log,
const clientSecret = providerSpecificData?.clientSecret;
const region = providerSpecificData?.region;
if (authMethod === "external_idp") {
let refreshRequest;
try {
refreshRequest = buildExternalIdpRefreshParams(refreshToken, providerSpecificData);
} catch (error) {
log?.warn?.("TOKEN_REFRESH", `Invalid Kiro external_idp refresh config: ${error.message}`);
return null;
}
const response = await proxyAwareFetch(refreshRequest.tokenEndpoint, {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
Accept: "application/json",
},
body: refreshRequest.body,
}, proxyOptions);
if (!response.ok) {
const errorText = await response.text();
log?.error?.("TOKEN_REFRESH", "Failed to refresh Kiro external_idp token", {
status: response.status,
error: errorText,
});
return null;
}
const tokens = await response.json();
log?.info?.("TOKEN_REFRESH", "Successfully refreshed Kiro external_idp token", {
hasNewAccessToken: !!tokens.access_token,
hasNewRefreshToken: !!tokens.refresh_token,
expiresIn: tokens.expires_in,
});
return {
accessToken: tokens.access_token,
refreshToken: tokens.refresh_token || refreshToken,
expiresIn: tokens.expires_in,
providerSpecificData: refreshRequest.providerSpecificData,
};
}
if (clientId && clientSecret) {
const isIDC = authMethod === "idc";
const endpoint = isIDC && region

View File

@@ -55,7 +55,9 @@ export async function getKiroUsage(accessToken, providerSpecificData, proxyOptio
// CodeWhisperer treats it as a long-lived API key rather than an OIDC token.
// Without this header the GetUsageLimits call is rejected (401/403).
const isApiKey = authMethod === "api_key";
const isExternalIdp = authMethod === "external_idp";
const apiKeyHeaders = isApiKey ? { tokentype: "API_KEY" } : {};
const externalIdpHeaders = isExternalIdp ? { TokenType: "EXTERNAL_IDP" } : {};
// For api-key auth, never inject the shared default placeholder profileArn —
// CodeWhisperer 403s a request whose profileArn isn't owned by the key's
@@ -84,6 +86,7 @@ export async function getKiroUsage(accessToken, providerSpecificData, proxyOptio
"x-amz-user-agent": "aws-sdk-js/1.0.0 KiroIDE",
"user-agent": "aws-sdk-js/1.0.0 KiroIDE",
...apiKeyHeaders,
...externalIdpHeaders,
},
},
proxyOptions
@@ -99,6 +102,7 @@ export async function getKiroUsage(accessToken, providerSpecificData, proxyOptio
"x-amz-target": "AmazonCodeWhispererService.GetUsageLimits",
"Accept": "application/json",
...apiKeyHeaders,
...externalIdpHeaders,
},
body: JSON.stringify({
origin: "AI_EDITOR",
@@ -121,6 +125,7 @@ export async function getKiroUsage(accessToken, providerSpecificData, proxyOptio
"Authorization": `Bearer ${accessToken}`,
"Accept": "application/json",
...apiKeyHeaders,
...externalIdpHeaders,
},
}, proxyOptions);
},

View File

@@ -0,0 +1,40 @@
import { NextResponse } from "next/server";
import { createProviderConnection } from "@/models";
import { normalizeKiroExternalIdpAuth } from "@/lib/oauth/kiroExternalIdp";
/**
* POST /api/oauth/kiro/import-cli-proxy
* Import Kiro CLIProxyAPI auth JSON for Microsoft external_idp accounts.
*/
export async function POST(request) {
try {
const body = await request.json();
const rawAuth = body?.cliProxyAuth ?? body?.auth ?? body?.json ?? body;
const tokenData = normalizeKiroExternalIdpAuth(rawAuth);
const connection = await createProviderConnection({
provider: "kiro",
authType: "oauth",
accessToken: tokenData.accessToken,
refreshToken: tokenData.refreshToken,
expiresAt: tokenData.expiresAt,
email: tokenData.email || null,
providerSpecificData: tokenData.providerSpecificData,
testStatus: "active",
});
return NextResponse.json({
success: true,
connection: {
id: connection.id,
provider: connection.provider,
email: connection.email,
},
});
} catch (error) {
return NextResponse.json(
{ error: error?.message || "CLIProxyAPI import failed" },
{ status: 400 }
);
}
}

View File

@@ -0,0 +1,155 @@
const MICROSOFT_TOKEN_ENDPOINT_HOSTS = new Set([
"login.microsoftonline.com",
"login.microsoft.com",
"login.windows.net",
]);
const DEFAULT_REGION = "us-east-1";
const DEFAULT_EXPIRES_IN = 3600;
function normalizeString(value) {
return typeof value === "string" ? value.trim() : "";
}
export function validateMicrosoftTokenEndpoint(rawEndpoint) {
const tokenEndpoint = normalizeString(rawEndpoint);
if (!tokenEndpoint) throw new Error("token_endpoint is required");
let parsed;
try {
parsed = new URL(tokenEndpoint);
} catch {
throw new Error("token_endpoint must be a valid URL");
}
if (parsed.protocol !== "https:") {
throw new Error("token_endpoint must use https");
}
const host = parsed.hostname.toLowerCase();
if (!MICROSOFT_TOKEN_ENDPOINT_HOSTS.has(host)) {
throw new Error("token_endpoint must be a Microsoft login endpoint");
}
return parsed.toString();
}
export function normalizeScope(scopes) {
if (Array.isArray(scopes)) {
return scopes.map(normalizeString).filter(Boolean).join(" ");
}
return normalizeString(scopes);
}
export function decodeJwtPayload(jwt) {
try {
if (!jwt || typeof jwt !== "string") return null;
const parts = jwt.split(".");
if (parts.length !== 3) return null;
const base64 = parts[1].replace(/-/g, "+").replace(/_/g, "/");
const padding = (4 - (base64.length % 4)) % 4;
return JSON.parse(Buffer.from(`${base64}${"=".repeat(padding)}`, "base64").toString("utf8"));
} catch {
return null;
}
}
function resolveExpiresAt(input) {
const explicit = input.expired || input.expires_at || input.expiresAt;
if (explicit) {
const ms = new Date(explicit).getTime();
if (Number.isFinite(ms)) return new Date(ms).toISOString();
}
const expiresIn = Number(input.expires_in || input.expiresIn || 0);
if (Number.isFinite(expiresIn) && expiresIn > 0) {
return new Date(Date.now() + expiresIn * 1000).toISOString();
}
const payload = decodeJwtPayload(input.access_token || input.accessToken);
if (payload?.exp) {
return new Date(payload.exp * 1000).toISOString();
}
return new Date(Date.now() + DEFAULT_EXPIRES_IN * 1000).toISOString();
}
export function normalizeKiroExternalIdpAuth(rawAuth) {
let input = rawAuth;
if (typeof input === "string") {
try {
input = JSON.parse(input);
} catch {
throw new Error("CLIProxyAPI auth JSON is invalid");
}
}
if (!input || typeof input !== "object") {
throw new Error("CLIProxyAPI auth JSON is required");
}
const authMethod = normalizeString(input.auth_method || input.authMethod);
if (authMethod && authMethod !== "external_idp") {
throw new Error("Only external_idp Kiro auth is supported by this importer");
}
const accessToken = normalizeString(input.access_token || input.accessToken);
const refreshToken = normalizeString(input.refresh_token || input.refreshToken);
const clientId = normalizeString(input.client_id || input.clientId);
const tokenEndpoint = validateMicrosoftTokenEndpoint(input.token_endpoint || input.tokenEndpoint);
const profileArn = normalizeString(input.profile_arn || input.profileArn);
const region = normalizeString(input.region) || DEFAULT_REGION;
const scope = normalizeScope(input.scopes || input.scope);
if (!accessToken) throw new Error("access_token is required");
if (!refreshToken) throw new Error("refresh_token is required");
if (!clientId) throw new Error("client_id is required");
if (!scope) throw new Error("scopes is required");
if (!profileArn) throw new Error("profile_arn is required");
const payload = decodeJwtPayload(accessToken);
const email = input.email || payload?.email || payload?.preferred_username || payload?.upn || payload?.sub || null;
return {
accessToken,
refreshToken,
expiresAt: resolveExpiresAt(input),
email,
providerSpecificData: {
profileArn,
region,
authMethod: "external_idp",
provider: "CLIProxyAPI",
clientId,
tokenEndpoint,
scope,
},
};
}
export function buildExternalIdpRefreshParams(refreshToken, providerSpecificData = {}) {
const clientId = normalizeString(providerSpecificData.clientId || providerSpecificData.client_id);
const tokenEndpoint = validateMicrosoftTokenEndpoint(providerSpecificData.tokenEndpoint || providerSpecificData.token_endpoint);
const scope = normalizeScope(providerSpecificData.scope || providerSpecificData.scopes);
if (!refreshToken) throw new Error("refresh token is required");
if (!clientId) throw new Error("clientId is required for external_idp refresh");
if (!scope) throw new Error("scope is required for external_idp refresh");
return {
tokenEndpoint,
body: new URLSearchParams({
grant_type: "refresh_token",
client_id: clientId,
refresh_token: refreshToken,
scope,
}),
providerSpecificData: {
...providerSpecificData,
authMethod: "external_idp",
clientId,
tokenEndpoint,
scope,
},
};
}

View File

@@ -13,6 +13,7 @@ export default function KiroAuthModal({ isOpen, onMethodSelect, onClose }) {
const [idcStartUrl, setIdcStartUrl] = useState("");
const [idcRegion, setIdcRegion] = useState("us-east-1");
const [refreshToken, setRefreshToken] = useState("");
const [cliProxyJson, setCliProxyJson] = useState("");
const [apiKey, setApiKey] = useState("");
const [apiKeyRegion, setApiKeyRegion] = useState("us-east-1");
const [error, setError] = useState(null);
@@ -105,6 +106,36 @@ export default function KiroAuthModal({ isOpen, onMethodSelect, onClose }) {
}
};
const handleImportCliProxyJson = async () => {
if (!cliProxyJson.trim()) {
setError("Please paste CLIProxyAPI auth JSON");
return;
}
setImporting(true);
setError(null);
try {
const res = await fetch("/api/oauth/kiro/import-cli-proxy", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ json: cliProxyJson.trim() }),
});
const data = await res.json();
if (!res.ok) {
throw new Error(data.error || "CLIProxyAPI import failed");
}
onMethodSelect("import-cli-proxy");
} catch (err) {
setError(err.message);
} finally {
setImporting(false);
}
};
const handleIdcContinue = () => {
if (!idcStartUrl.trim()) {
setError("Please enter your IDC start URL");
@@ -256,6 +287,22 @@ export default function KiroAuthModal({ isOpen, onMethodSelect, onClose }) {
</div>
</div>
</button>
{/* Import CLIProxyAPI JSON */}
<button
onClick={() => handleMethodSelect("import-cli-proxy")}
className="w-full p-4 text-left border border-border rounded-lg hover:bg-sidebar transition-colors"
>
<div className="flex items-start gap-3">
<span className="material-symbols-outlined text-primary mt-0.5">data_object</span>
<div className="flex-1">
<h3 className="font-semibold mb-1">Import CLIProxyAPI JSON</h3>
<p className="text-sm text-text-muted">
Paste external_idp auth JSON from CLIProxyAPI/Kiro Microsoft login.
</p>
</div>
</div>
</button>
</div>
)}
@@ -495,6 +542,47 @@ export default function KiroAuthModal({ isOpen, onMethodSelect, onClose }) {
)}
</div>
)}
{/* Import CLIProxyAPI JSON */}
{selectedMethod === "import-cli-proxy" && (
<div className="space-y-4">
<div className="bg-blue-50 dark:bg-blue-900/20 p-3 rounded-lg border border-blue-200 dark:border-blue-800">
<div className="flex gap-2">
<span className="material-symbols-outlined text-blue-600 dark:text-blue-400">info</span>
<p className="text-sm text-blue-800 dark:text-blue-200">
Paste the Kiro CLIProxyAPI auth JSON containing auth_method=external_idp. Only Microsoft login token endpoints are accepted.
</p>
</div>
</div>
<div>
<label className="block text-sm font-medium mb-2">
CLIProxyAPI Auth JSON <span className="text-red-500">*</span>
</label>
<textarea
value={cliProxyJson}
onChange={(e) => setCliProxyJson(e.target.value)}
placeholder={'{"auth_method":"external_idp","access_token":"...","refresh_token":"...","client_id":"...","token_endpoint":"https://login.microsoftonline.com/.../oauth2/v2.0/token","profile_arn":"...","scopes":"..."}'}
className="min-h-40 w-full rounded-md border border-border bg-background p-3 font-mono text-sm outline-none focus:border-primary"
/>
</div>
{error && (
<div className="bg-red-50 dark:bg-red-900/20 p-3 rounded-lg border border-red-200 dark:border-red-800">
<p className="text-sm text-red-600 dark:text-red-400">{error}</p>
</div>
)}
<div className="flex gap-2">
<Button onClick={handleImportCliProxyJson} fullWidth disabled={importing || !cliProxyJson.trim()}>
{importing ? "Importing..." : "Import CLIProxyAPI JSON"}
</Button>
<Button onClick={handleBack} variant="ghost" fullWidth>
Back
</Button>
</div>
</div>
)}
</div>
</Modal>
);

View File

@@ -0,0 +1,207 @@
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
const originalFetch = global.fetch;
const TEST_CLIENT_ID = "00000000-0000-4000-8000-000000000000";
const TEST_SCOPE = `api://${TEST_CLIENT_ID}/codewhisperer:conversations offline_access`;
const TEST_EMAIL = "user@example.com";
function makeJwt(payload) {
const encoded = Buffer.from(JSON.stringify(payload)).toString("base64url");
return `header.${encoded}.signature`;
}
describe("Kiro external_idp (CLIProxyAPI) import and refresh", () => {
beforeEach(() => {
vi.clearAllMocks();
vi.resetModules();
global.fetch = originalFetch;
});
afterEach(() => {
vi.doUnmock("next/server");
vi.doUnmock("@/models");
vi.doUnmock("../../open-sse/utils/proxyFetch.js");
global.fetch = originalFetch;
});
it("refreshes Microsoft external_idp tokens with form-encoded OAuth body", async () => {
const fetchMock = vi.fn().mockResolvedValue({
ok: true,
json: () => Promise.resolve({
access_token: "new-access-token",
refresh_token: "rotated-refresh-token",
expires_in: 3600,
}),
});
global.fetch = fetchMock;
const { refreshKiroToken } = await import("../../open-sse/services/tokenRefresh.js");
const result = await refreshKiroToken("old-refresh-token", {
authMethod: "external_idp",
clientId: TEST_CLIENT_ID,
tokenEndpoint: "https://login.microsoftonline.com/tenant-id/oauth2/v2.0/token",
scope: TEST_SCOPE,
profileArn: "arn:aws:codewhisperer:us-east-1:123456789012:profile/ABC",
region: "us-east-1",
});
expect(result).toMatchObject({
accessToken: "new-access-token",
refreshToken: "rotated-refresh-token",
expiresIn: 3600,
providerSpecificData: {
profileArn: "arn:aws:codewhisperer:us-east-1:123456789012:profile/ABC",
authMethod: "external_idp",
clientId: TEST_CLIENT_ID,
tokenEndpoint: "https://login.microsoftonline.com/tenant-id/oauth2/v2.0/token",
scope: TEST_SCOPE,
region: "us-east-1",
},
});
expect(fetchMock).toHaveBeenCalledTimes(1);
const [url, init] = fetchMock.mock.calls[0];
expect(url).toBe("https://login.microsoftonline.com/tenant-id/oauth2/v2.0/token");
expect(init.method).toBe("POST");
expect(init.headers).toMatchObject({
"Content-Type": "application/x-www-form-urlencoded",
Accept: "application/json",
});
expect(init.body).toBeInstanceOf(URLSearchParams);
expect(Object.fromEntries(init.body.entries())).toEqual({
grant_type: "refresh_token",
client_id: TEST_CLIENT_ID,
refresh_token: "old-refresh-token",
scope: TEST_SCOPE,
});
});
it("rejects external_idp refresh endpoints outside Microsoft login", async () => {
const { refreshKiroToken } = await import("../../open-sse/services/tokenRefresh.js");
const fetchMock = vi.fn();
global.fetch = fetchMock;
const result = await refreshKiroToken("old-refresh-token", {
authMethod: "external_idp",
clientId: "client-id",
tokenEndpoint: "https://evil.example.com/token",
scope: "offline_access",
});
expect(result).toBeNull();
expect(fetchMock).not.toHaveBeenCalled();
});
it("adds CodeWhisperer external IdP headers and endpoint ordering", async () => {
const { KiroExecutor } = await import("../../open-sse/executors/kiro.js");
const executor = new KiroExecutor();
const credentials = {
accessToken: "microsoft-access-token",
providerSpecificData: { authMethod: "external_idp" },
};
const headers = executor.buildHeaders(credentials, true);
expect(headers.Authorization).toBe("Bearer microsoft-access-token");
expect(headers.TokenType).toBe("EXTERNAL_IDP");
expect(headers.tokentype).toBeUndefined();
expect(executor.buildUrl("claude-sonnet-4.5", true, 0, credentials)).toBe(
"https://codewhisperer.us-east-1.amazonaws.com/generateAssistantResponse"
);
});
it("sends TokenType for external_idp Kiro usage probes", async () => {
const calls = [];
vi.doMock("../../open-sse/utils/proxyFetch.js", () => ({
proxyAwareFetch: vi.fn(async (url, init) => {
calls.push({ url, init });
return {
ok: true,
json: async () => ({
subscriptionInfo: { subscriptionTitle: "Kiro Enterprise" },
usageBreakdownList: [],
}),
};
}),
}));
const { getKiroUsage } = await import("../../open-sse/services/usage/kiro.js");
const result = await getKiroUsage("microsoft-access-token", {
authMethod: "external_idp",
profileArn: "arn:aws:codewhisperer:us-east-1:123456789012:profile/ABC",
});
expect(result.plan).toBe("Kiro Enterprise");
expect(calls).toHaveLength(1);
expect(calls[0].init.headers.Authorization).toBe("Bearer microsoft-access-token");
expect(calls[0].init.headers.TokenType).toBe("EXTERNAL_IDP");
expect(calls[0].init.headers.tokentype).toBeUndefined();
});
it("imports CLIProxyAPI external_idp JSON as a Kiro OAuth connection", async () => {
const createdConnections = [];
vi.doMock("next/server", () => ({
NextResponse: {
json(body, init = {}) {
return new Response(JSON.stringify(body), {
status: init.status || 200,
headers: { "Content-Type": "application/json" },
});
},
},
}));
vi.doMock("@/models", () => ({
createProviderConnection: vi.fn(async (data) => {
const connection = { id: "conn-1", ...data };
createdConnections.push(connection);
return connection;
}),
}));
const { POST } = await import("../../src/app/api/oauth/kiro/import-cli-proxy/route.js");
const accessToken = makeJwt({
preferred_username: TEST_EMAIL,
exp: Math.floor(Date.now() / 1000) + 3600,
});
const cliProxyAuth = {
type: "kiro",
auth_method: "external_idp",
access_token: accessToken,
refresh_token: "1.AcY-refresh-token",
client_id: TEST_CLIENT_ID,
token_endpoint: "https://login.microsoftonline.com/tenant-id/oauth2/v2.0/token",
profile_arn: "arn:aws:codewhisperer:us-east-1:123456789012:profile/ABC",
region: "us-east-1",
scopes: TEST_SCOPE,
expired: new Date(Date.now() + 3600_000).toISOString(),
};
const response = await POST(new Request("https://9router.local/api/oauth/kiro/import-cli-proxy", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ cliProxyAuth }),
}));
const body = await response.json();
expect(response.status).toBe(200);
expect(body.success).toBe(true);
expect(createdConnections).toHaveLength(1);
expect(createdConnections[0]).toMatchObject({
provider: "kiro",
authType: "oauth",
accessToken,
refreshToken: "1.AcY-refresh-token",
email: TEST_EMAIL,
providerSpecificData: {
authMethod: "external_idp",
provider: "CLIProxyAPI",
profileArn: "arn:aws:codewhisperer:us-east-1:123456789012:profile/ABC",
region: "us-east-1",
clientId: TEST_CLIENT_ID,
tokenEndpoint: "https://login.microsoftonline.com/tenant-id/oauth2/v2.0/token",
scope: TEST_SCOPE,
},
testStatus: "active",
});
});
});