Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(providers): enforce live model grants on Pi proxy requests

DavidShen2a540f6891bf
diff --git a/apps/desktop/src/main/maker-host/__tests__/claudeProxyGuestRoute.test.ts b/apps/desktop/src/main/maker-host/__tests__/claudeProxyGuestRoute.test.ts
index 3237aeec65..cc7c8ca7c5 100644
--- a/apps/desktop/src/main/maker-host/__tests__/claudeProxyGuestRoute.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/claudeProxyGuestRoute.test.ts
@@ -29,6 +29,13 @@ vi.mock('../claude-fast-mode-log', () => ({
createClaudeFastModeRequestTransform: () => () => null,
createClaudeFastModeResponseObserver: () => () => undefined,
}));
+vi.mock('../anthropic-responses-bridge-host', () => ({
+ getResponsesBridgeHandler: () => null,
+ getPiNativeSubscriptionHandler: () => async ({ res }: { res: { writeHead(status: number): void; end(): void } }) => {
+ res.writeHead(204);
+ res.end();
+ },
+}));
import { DEVICE_HOSTED_GUEST_ROUTE_HEADER } from '@cindy/maker-core';
import { buildRegistry, buildUserProvider } from '@cindy/model-providers';
@@ -39,7 +46,7 @@ import {
setClaudeProxyGatewayKeyReader,
setClaudeProxySessionIdResolver,
} from '../anthropic-compat-proxy-host';
-import { getActiveCatalog, setCustomProviders } from '../active-catalog';
+import { getActiveCatalog, setCustomProviders, setXdGatewayModels } from '../active-catalog';
import {
GUEST_ROUTE_HEADER,
guestProviderOffersModel,
@@ -62,7 +69,7 @@ const SHARED_UPSTREAM = 'https://shared.example/api/anthropic';
const OTHER_UPSTREAM = 'https://other.example/api/anthropic';
function ctxWith(headers: Record<string, string>) {
- return { reqId: 1, method: 'POST', url: '/v1/messages', headers } as never;
+ return { reqId: 1, method: 'POST', url: '/v1/messages', headers };
}
async function statusOf(decision: RoutingDecision | null): Promise<number | undefined> {
@@ -83,6 +90,11 @@ function installProviders(): void {
wireProtocol: 'anthropic-messages',
models: [{ id: model, name: model }],
},
+ pi: {
+ baseUrl,
+ wireProtocol: 'anthropic-messages',
+ models: [{ id: model, name: model }, { id: `${model}-private`, name: `${model}-private` }],
+ },
},
});
setCustomProviders([
@@ -101,6 +113,7 @@ describe('Claude proxy routing for shared-provider guests', () => {
setClaudeProxySessionIdResolver(() => null);
setPendingCredentialSwitchReader(() => undefined);
setProviderOAuthTokenReader(() => null);
+ setXdGatewayModels(['google/gemini-3.7-flash', 'gemini-3.6-flash'].map(id => ({ id, agents: ['pi'] })));
installProviders();
transform = createModelRoutingTransform();
});
@@ -109,6 +122,7 @@ describe('Claude proxy routing for shared-provider guests', () => {
resetGuestProviderRoutesForTest();
clearAllSessionProviders();
setCustomProviders([]);
+ setXdGatewayModels([]);
setCustomProviderKeyReader(() => null);
setProviderViewsReader(async () => []);
});
@@ -203,14 +217,78 @@ describe('Claude proxy routing for shared-provider guests', () => {
'x-cindy-pi-session-token': 'root-token',
'x-cindy-pi-provider-id': 'shared-a',
})));
- // 分享的供应商:受邀者守门放行,照常按会话来源路由(这里的 fixture 没有 Pi 运行时)。
- expect(await statusOf(shared)).not.toBe(403);
+ expect(shared?.upstreamOverride).toBe(SHARED_UPSTREAM);
} finally {
disposeRoot();
disposeChild();
}
});
+ // Unit regression for #6592 / provider-sharing §12: the production routing transform must
+ // deny an ungranted Pi model before any upstream/native handler. Earlier coverage only
+ // changed providers. Minimal failure: two models at one provider, only the first granted.
+ it.each(['shared-a', 'openai', 'xai', 'xd'])('rechecks live Pi model grants for %s root and child routes', async providerId => {
+ const models = getActiveCatalog().providers.find(provider => provider.id === providerId)!.models.pi!;
+ const [first, second] = models.filter(model => !model.disabled);
+ expect(first).toBeDefined();
+ expect(second).toBeDefined();
+ const wireId = (id: string) => providerId === 'openai' ? id.replace(/^chatgpt\//, '')
+ : providerId === 'xai' ? id.replace(/^xai\//, '') : id;
+ let allowedModel = first.id;
+ registerGuestProviderRoute('pi-model-guest', providerId, model => model === allowedModel);
+ registerGuestProviderRoute('other-person', providerId, () => false);
+ const disposers = [
+ registerPiProxySession('pi-model-guest', 'root-token', () => providerId),
+ registerPiProxySession('pi-model-guest', 'child-token', () => providerId, { scope: 'subagent-route' }),
+ registerPiProxySession('other-person', 'other-token', () => providerId),
+ registerPiProxySession('local-pi', 'local-token', () => providerId),
+ ];
+ const request = (model: string, token: string, sessionId = 'pi-model-guest') => Promise.resolve(transform(
+ providerId === 'xd' ? { contents: [] } : { model: wireId(model) }, { ...ctxWith({
+ 'x-cindy-pi-session-id': sessionId,
+ 'x-cindy-pi-session-token': token,
+ 'x-cindy-pi-provider-id': providerId,
+ }), ...(providerId === 'xd' ? { url: `/v1beta/models/${encodeURIComponent(model)}:streamGenerateContent?alt=sse` } : {}) },
+ ));
+ const expectAllowed = async (decision: RoutingDecision | null) => {
+ if (providerId === 'openai' || providerId === 'xai') expect(await statusOf(decision)).toBe(204);
+ else if (providerId === 'xd') expect(decision?.headerOverride?.authorization).toBe('Bearer sk-gw');
+ else expect(decision?.upstreamOverride).toBe(SHARED_UPSTREAM);
+ };
+ try {
+ for (const token of ['root-token', 'child-token']) {
+ await expectAllowed(await request(first.id, token));
+ expect(await statusOf(await request(second.id, token))).toBe(403);
+ expect(await statusOf(await request('unknown-model', token))).toBe(403);
+ expect(await statusOf(await request('', token))).toBe(403);
+ }
+ expect(await statusOf(await request(first.id, 'other-token', 'other-person'))).toBe(403);
+ const forgedPath = { ...ctxWith({
+ 'x-cindy-pi-session-id': 'pi-model-guest',
+ 'x-cindy-pi-session-token': 'root-token',
+ 'x-cindy-pi-provider-id': providerId,
+ }), url: `/v1beta/models/${encodeURIComponent(first.id)}:streamGenerateContent` };
+ // A URL naming an allowed model cannot hide a different/opaque subscription body.
+ expect(await statusOf(await transform({ model: wireId(second.id) }, forgedPath))).toBe(403);
+ expect(await statusOf(await transform(undefined, forgedPath))).toBe(403);
+ if (providerId === 'xd') {
+ expect(await statusOf(await transform({ model: first.id }, {
+ ...forgedPath, url: `/v1beta/models/${encodeURIComponent(second.id)}:streamGenerateContent`,
+ }))).toBe(403);
+ }
+ // A live change must revoke the old model and allow the newly granted model without restart.
+ allowedModel = second.id;
+ for (const token of ['root-token', 'child-token']) {
+ expect(await statusOf(await request(first.id, token))).toBe(403);
+ await expectAllowed(await request(second.id, token));
+ }
+ // Local Pi is independent of restrictions on guests sharing the same provider.
+ await expectAllowed(await request(first.id, 'local-token', 'local-pi'));
+ } finally {
+ for (const dispose of disposers) dispose();
+ }
+ });
+
it('keeps requests without a route token on the existing routing (same-account unchanged)', async () => {
const decision = await Promise.resolve(transform({ model: 'other-model' }, ctxWith({ 'x-api-key': 'sk-gw' })));
expect(decision).toMatchObject({
diff --git a/apps/desktop/src/main/maker-host/anthropic-compat-proxy-host.ts b/apps/desktop/src/main/maker-host/anthropic-compat-proxy-host.ts
index e7e8b43f61..27922a5358 100644
--- a/apps/desktop/src/main/maker-host/anthropic-compat-proxy-host.ts
+++ b/apps/desktop/src/main/maker-host/anthropic-compat-proxy-host.ts
@@ -687,6 +687,25 @@ export function createModelRoutingTransform(): RoutingTransform {
if (piGuest && !piRequestStaysOnGuestProvider(piGuest, piProviderId, registeredPiProviderId)) {
return refuseGuestProviderRoute(403, 'shared_provider_only', 'This request is outside the provider shared with you.');
}
+ if (piGuest) {
+ // Check the live member grant before native handlers and all other Pi routing branches.
+ // Google's native API puts the authoritative model in the URL instead of body.model.
+ const requestModels: string[] = [];
+ if (isPlainObject(body)) {
+ if (typeof body.model === 'string' && body.model) requestModels.push(body.model);
+ // Subscription forwarders use body.model and rebuild their own URL; a forged Google
+ // path cannot stand in for a missing/opaque subscription request body.
+ if (!isOpenAiSubscriptionProviderId(piGuest.providerId) && !isXaiSubscriptionProviderId(piGuest.providerId)) {
+ const pathname = new URL(ctx.url, 'http://127.0.0.1').pathname;
+ const pathModel = /\/models\/(.+):(?:streamGenerateContent|generateContent|countTokens)$/.exec(pathname);
+ if (pathModel) requestModels.push(decodeURIComponent(pathModel[1]));
+ }
+ }
+ const deniedModel = requestModels.find(model => !guestProviderOffersModel(piGuest.providerId, 'pi', model, piGuest.sessionId));
+ if (requestModels.length === 0 || deniedModel !== undefined) {
+ return refuseGuestForeignRoute(deniedModel ?? '');
+ }
+ }
if (piSessionId && piProviderId && (isOpenAiSubscriptionProviderId(piProviderId) || isXaiSubscriptionProviderId(piProviderId))) {
return {
// PI has already built the provider-native request. The local handler
diff --git a/apps/desktop/src/main/maker-host/guest-provider-route-store.ts b/apps/desktop/src/main/maker-host/guest-provider-route-store.ts
index 072851b370..847884426b 100644
--- a/apps/desktop/src/main/maker-host/guest-provider-route-store.ts
+++ b/apps/desktop/src/main/maker-host/guest-provider-route-store.ts
@@ -10,7 +10,7 @@
*/
import { randomBytes } from 'node:crypto';
-import type { AgentKind } from '@cindy/model-providers';
+import { findCatalogModel, type AgentKind } from '@cindy/model-providers';
import { getActiveCatalog } from './active-catalog.js';
import { clearSessionProvider, getSessionProvider, setSessionProvider } from './session-provider-store.js';
@@ -90,12 +90,18 @@ function bareModelId(model: string): string {
return model.trim().replace(/\[1m\]$/i, '');
}
-/** 分享的供应商是否为这个 Agent 提供这个模型(请求里的模型串,忽略 1M 通道后缀)。 */
+/** 按请求模型核对目录与授权;Claude Code 忽略 1M 通道后缀,Pi 保留精确的窗口档位。 */
export function guestProviderOffersModel(providerId: string, agent: AgentKind, wireModel: string, sessionId?: string): boolean {
const requested = bareModelId(wireModel);
if (!requested) return false;
const provider = getActiveCatalog().providers.find((candidate) => candidate.id === providerId);
const binding = sessionId ? bySession.get(sessionId) : undefined;
+ if (agent === 'pi') {
+ // Pi native subscriptions send bare wire ids; grants use the catalog's namespaced ids.
+ // Keep distinct context profiles exact so one profile cannot borrow another's grant.
+ const model = findCatalogModel(provider, wireModel, agent, { exact: true });
+ return Boolean(model && !model.disabled && (!binding?.allowsModel || binding.allowsModel(model.id)));
+ }
return (provider?.models[agent] ?? []).some((model) => !model.disabled && bareModelId(model.id) === requested
&& (!binding?.allowsModel || binding.allowsModel(model.id)));
}