Merge pull request #7734 from continuedev/nate/cn-org-api-key

feat: auto-select scope for org api keys in cn
This commit is contained in:
Nate Sesti 2025-09-14 12:11:04 -07:00 • committed by GitHub
commit f5f1fcc98a
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 115 additions and 2 deletions

View file

@ -0,0 +1,58 @@
import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
import { ensureOrganization, isEnvironmentAuthConfig } from "./workos.js";
describe("ensureOrganization with API key org scope", () => {
const originalEnv = { ...process.env };
const originalFetch = global.fetch;
beforeEach(() => {
vi.restoreAllMocks();
});
afterEach(() => {
process.env = { ...originalEnv };
global.fetch = originalFetch as any;
});
it("resolves organizationId via auth/scope for API key auth", async () => {
const mockFetch = vi.fn().mockResolvedValue({
ok: true,
json: async () => ({ organizationId: "org_123" }),
});
(global as any).fetch = mockFetch;
const envAuthConfig = {
accessToken: "sk_test_api_key",
organizationId: null as string | null,
} as const;
const result = await ensureOrganization(envAuthConfig, true);
expect(result).not.toBeNull();
if (result && isEnvironmentAuthConfig(result)) {
expect(result.organizationId).toBe("org_123");
} else {
throw new Error("Expected environment auth config result");
}
expect(mockFetch).toHaveBeenCalledOnce();
});
it("keeps organizationId null if endpoint not available", async () => {
const mockFetch = vi.fn().mockResolvedValue({ ok: false });
(global as any).fetch = mockFetch;
const envAuthConfig = {
accessToken: "sk_test_api_key",
organizationId: null as string | null,
} as const;
const result = await ensureOrganization(envAuthConfig, true);
expect(result).not.toBeNull();
if (result && isEnvironmentAuthConfig(result)) {
expect(result.organizationId).toBeNull();
} else {
throw new Error("Expected environment auth config result");
}
expect(mockFetch).toHaveBeenCalledOnce();
});
});

View file

@ -540,8 +540,10 @@ export async function ensureOrganization(
);
}
} else if (isEnvironmentAuthConfig(authConfig)) {
// No CLI organization slug (or "personal" was specified) - return as-is
return authConfig;
// No CLI organization slug (or "personal" was specified)
// If using API key auth, attempt to resolve its organization scope once
const resolved = await resolveOrgScopeForApiKey(authConfig);
return resolved;
}
// If not authenticated, return as-is
@ -577,6 +579,59 @@ export async function ensureOrganization(
return autoSelectOrganization(authenticatedConfig);
}
/**
* Attempts to resolve the organization scope for API key auth (environment-based auth).
* Calls a lightweight backend endpoint to determine if the API key is an org-scoped key.
* If successful, returns a new EnvironmentAuthConfig with organizationId set; otherwise returns the original config.
*/
async function resolveOrgScopeForApiKey(
envConfig: EnvironmentAuthConfig,
): Promise<EnvironmentAuthConfig> {
// If already set (including explicit null), return as-is
if (envConfig.organizationId !== null) {
return envConfig;
}
const accessToken = envConfig.accessToken;
if (!accessToken) return envConfig;
try {
// Prefer a dedicated endpoint for scope discovery. This should return JSON like:
// { organizationId: string | null } (aka orgScopeId)
const url = new URL("auth/scope", env.apiBase);
const resp = await fetch(url, {
method: "GET",
headers: {
Authorization: `Bearer ${accessToken}`,
"Content-Type": "application/json",
},
});
if (!resp.ok) {
// Gracefully ignore if the endpoint isn't available yet (e.g., 404) or other non-2xx errors
return envConfig;
}
const data: any = await resp.json().catch(() => ({}));
const orgId =
data?.organizationId ??
data?.orgScopeId ??
data?.organization?.id ??
null;
if (orgId && typeof orgId === "string") {
return {
...envConfig,
organizationId: orgId,
};
}
} catch {
// Network or parsing issues: leave config unchanged
}
return envConfig;
}
/**
* Gets the list of available organizations for the user
*/