diff --git a/.github/issue-evidence/11586-credential-pool-followups.md b/.github/issue-evidence/11586-credential-pool-followups.md new file mode 100644 index 0000000000000..89afddf23ec79 --- /dev/null +++ b/.github/issue-evidence/11586-credential-pool-followups.md @@ -0,0 +1,50 @@ +# Issue #11586 — credential-pool follow-ups + +Date: 2026-07-02 +Branch: `fix/11586-credential-pool-followups` + +## What Changed + +- Added org-scoped repository WHERE paths for pooled credential read/update/delete and pool metadata writes. +- Wired Worker chat completions to select org pooled direct-provider keys for supported direct models, with strict fallback to platform env on pool miss. +- Added 401/403/429 provider outcome writeback to pooled credential health. +- Suppressed affiliate markup/earnings on zero-rated pooled BYO-key completions while still recording pool usage. +- Kept monetized app-credit billing ahead of pooled BYO-key no-op reservations so contributed provider keys cannot bypass app-owner pricing. +- Added source-condition package exports/imports needed for cloud source typechecks to resolve `@elizaos/app-core/account-pool` and `@elizaos/agent/utils/atomic-json`. +- Applied `RATE_LIMIT_MULTIPLIER` to the Hono/Cloudflare limiter in non-production only. +- Mapped `pooled_credential` audit denials to `secret.access`. + +## Human Follow-Up Split + +- Staging-only provisioning proof was split to #11622 (`needs-human`) because it requires deployed staging access and logs/artifacts from the real provisioning topology. + +## Verification + +- `bunx @biomejs/biome check packages/cloud/shared/src/db/repositories/pooled-credentials.ts packages/cloud/shared/src/lib/services/team-credential-pool/service.ts packages/cloud/shared/src/lib/services/team-credential-pool/pool-deps.ts packages/cloud/shared/src/lib/services/team-credential-pool/registry.ts packages/cloud/shared/src/lib/services/__tests__/team-credential-pool.test.ts packages/cloud/shared/src/lib/middleware/rate-limit-hono-cloudflare.ts packages/cloud/shared/src/lib/middleware/rate-limit-config-verdict.test.ts packages/cloud/shared/src/lib/providers/language-model.ts packages/cloud/shared/src/lib/providers/language-model-cerebras-fallback.test.ts packages/cloud/api/src/middleware/org-membership.ts packages/cloud/api/__tests__/org-credentials-routes.test.ts packages/cloud/api/v1/chat/completions/route.ts packages/cloud/api/__tests__/chat-completions-streaming-credit-leak.test.ts packages/agent/package.json packages/agent/src/auth/credentials.ts packages/app-core/package.json packages/app-core/src/services/account-pool.ts packages/app-core/src/services/account-usage.ts packages/app-core/src/services/coding-account-bridge.ts` + - Passed. +- `bun test --coverage-reporter=lcov --conditions eliza-source packages/cloud/shared/src/lib/services/__tests__/team-credential-pool.test.ts packages/cloud/shared/src/lib/middleware/rate-limit-config-verdict.test.ts packages/cloud/shared/src/lib/middleware/rate-limit-orphaned-counter.test.ts packages/cloud/shared/src/lib/middleware/rate-limit-default-key.test.ts packages/cloud/shared/src/lib/providers/language-model-cerebras-fallback.test.ts` + - Passed: 36 tests, 136 assertions. +- `bun test --coverage-reporter=lcov --conditions eliza-source packages/cloud/api/__tests__/org-credentials-routes.test.ts` + - Passed: 12 tests, 34 assertions. +- `bun run --cwd packages/cloud/shared typecheck` + - Passed. +- `bun run --cwd packages/cloud/api typecheck` + - Passed. +- `bun test --coverage-reporter=lcov --conditions eliza-source packages/cloud/api/__tests__/chat-completions-streaming-credit-leak.test.ts` + - Passed: 11 tests, 76 assertions, including pooled BYO-key success suppressing affiliate markup while recording pool use and pooled BYO-key not bypassing monetized app billing. +- `git diff --check` + - Passed. +- `bun install` + - Passed after rebasing onto `origin/develop`; no lockfile change remained. +- `bun run verify` + - Passed after rebasing onto `origin/develop` at `390c89e6fe4`. + - Workspace phase: 483 successful tasks. + - Final dist-path check: 28 consumer configs checked. + +## Evidence Matrix + +- UI screenshots/video: N/A — backend/provider/middleware changes only. +- Real-LLM trajectories: N/A — no agent prompt/action/model behavior change; provider selection is covered by direct provider-request tests. +- Backend logs: N/A locally — route tests exercise the code paths without a deployed service log sink. +- Domain artifacts: covered by DB-backed pooled credential tests that inspect rows, ciphertext preservation, usage rollups, and health metadata. +- Staging provisioning proof: N/A for this PR; split to #11622. diff --git a/packages/agent/package.json b/packages/agent/package.json index 0b435e9455f6a..8ea5545b376f8 100644 --- a/packages/agent/package.json +++ b/packages/agent/package.json @@ -149,6 +149,21 @@ "import": "./dist/auth/*.js", "default": "./dist/auth/*.js" }, + "./utils/atomic-json": { + "types": "./src/utils/atomic-json.ts", + "eliza-source": { + "types": "./src/utils/atomic-json.ts", + "import": "./src/utils/atomic-json.ts", + "default": "./src/utils/atomic-json.ts" + }, + "bun": { + "types": "./src/utils/atomic-json.ts", + "import": "./src/utils/atomic-json.ts", + "default": "./src/utils/atomic-json.ts" + }, + "import": "./dist/utils/atomic-json.js", + "default": "./dist/utils/atomic-json.js" + }, "./services/app-session-gate": { "eliza-source": { "types": "./src/services/app-session-gate.ts", diff --git a/packages/agent/src/auth/credentials.ts b/packages/agent/src/auth/credentials.ts index d0f38a8a2ac2e..6feec3c65d44b 100644 --- a/packages/agent/src/auth/credentials.ts +++ b/packages/agent/src/auth/credentials.ts @@ -19,7 +19,7 @@ import { resolveStateDir, resolveUserPath, } from "@elizaos/core"; -import type { SubscriptionCredentialSource } from "@elizaos/shared"; +import type { SubscriptionCredentialSource } from "@elizaos/shared/contracts/first-run-options"; import { type AccountCredentialRecord, deleteAccount, @@ -297,7 +297,7 @@ function hasCodexCliSubscriptionAuth(): boolean { } } -export type { SubscriptionCredentialSource } from "@elizaos/shared"; +export type { SubscriptionCredentialSource } from "@elizaos/shared/contracts/first-run-options"; /** * Per-account subscription status row used by the dashboard / API. diff --git a/packages/app-core/package.json b/packages/app-core/package.json index 74af3bbb270c6..a02b5cb00792f 100644 --- a/packages/app-core/package.json +++ b/packages/app-core/package.json @@ -97,7 +97,17 @@ "default": "./dist/agent-bridge.js" }, "./account-pool": { - "types": "./dist/account-pool.d.ts", + "types": "./src/account-pool.ts", + "eliza-source": { + "types": "./src/account-pool.ts", + "import": "./src/account-pool.ts", + "default": "./src/account-pool.ts" + }, + "bun": { + "types": "./src/account-pool.ts", + "import": "./src/account-pool.ts", + "default": "./src/account-pool.ts" + }, "import": "./dist/account-pool.js", "default": "./dist/account-pool.js" }, diff --git a/packages/app-core/src/services/account-pool.ts b/packages/app-core/src/services/account-pool.ts index 1612fd8b662f7..cacd098df9eab 100644 --- a/packages/app-core/src/services/account-pool.ts +++ b/packages/app-core/src/services/account-pool.ts @@ -45,7 +45,7 @@ import type { LinkedAccountProviderId, LinkedAccountsConfig, LinkedAccountUsage, -} from "@elizaos/shared"; +} from "@elizaos/shared/contracts/service-routing"; import { pollAnthropicUsage, pollCodexUsage, diff --git a/packages/app-core/src/services/account-usage.ts b/packages/app-core/src/services/account-usage.ts index 15ac1cb6d9edc..06f4276e41183 100644 --- a/packages/app-core/src/services/account-usage.ts +++ b/packages/app-core/src/services/account-usage.ts @@ -16,7 +16,7 @@ import { appendFileSync, existsSync, mkdirSync, readFileSync } from "node:fs"; import path from "node:path"; import { resolveStateDir } from "@elizaos/core"; -import type { LinkedAccountUsage } from "@elizaos/shared"; +import type { LinkedAccountUsage } from "@elizaos/shared/contracts/service-routing"; /** * Snapshot returned by the provider usage probes. Mirrors diff --git a/packages/app-core/src/services/coding-account-bridge.ts b/packages/app-core/src/services/coding-account-bridge.ts index 1714d3ddf14ce..1e7f6d8ca942a 100644 --- a/packages/app-core/src/services/coding-account-bridge.ts +++ b/packages/app-core/src/services/coding-account-bridge.ts @@ -44,7 +44,7 @@ import { logger, resolveStateDir } from "@elizaos/core"; import type { LinkedAccountProviderId, LinkedAccountUsage, -} from "@elizaos/shared"; +} from "@elizaos/shared/contracts/service-routing"; import type { AccountPool, Strategy } from "./account-pool.js"; const CODING_AGENT_SELECTOR_BRIDGE_SYMBOL: unique symbol = Symbol.for( @@ -240,7 +240,10 @@ export async function adoptRotatedCodexTokens( // Only adopt when the CLI's copy is NEWER than the canonical record. An // older materialized copy (e.g. the account was re-linked via OAuth after // that session ran) would clobber a fresh login with dead tokens. - const materializedAt = Date.parse(parsed.last_refresh ?? ""); + const materializedAt = + typeof parsed.last_refresh === "string" + ? Date.parse(parsed.last_refresh) + : Number.NaN; if ( !Number.isFinite(materializedAt) || materializedAt <= record.updatedAt @@ -280,7 +283,12 @@ function materializeCodexHome(accountId: string, accessToken: string): string { mkdirSync(dir, { recursive: true, mode: 0o700 }); } const record = loadAccount("openai-codex", accountId); - const refreshToken = record?.credentials.refresh ?? ""; + const refreshToken = record?.credentials.refresh; + if (!refreshToken) { + throw new Error( + `openai-codex account "${accountId}" is missing a refresh token`, + ); + } const chatgptAccountId = record?.organizationId; // Codex's chatgpt-mode auth loader requires `tokens.id_token`; omitting it // fails with "Authentication required" even when access_token is valid (an diff --git a/packages/cloud/api/__tests__/chat-completions-streaming-credit-leak.test.ts b/packages/cloud/api/__tests__/chat-completions-streaming-credit-leak.test.ts index 0bb3a8858fc9f..91b94c01a06fa 100644 --- a/packages/cloud/api/__tests__/chat-completions-streaming-credit-leak.test.ts +++ b/packages/cloud/api/__tests__/chat-completions-streaming-credit-leak.test.ts @@ -34,6 +34,7 @@ import { estimateTokens } from "@/lib/pricing"; import * as languageModelActual from "@/lib/providers/language-model"; import * as aiBillingActual from "@/lib/services/ai-billing"; import * as aiBillingRecordsActual from "@/lib/services/ai-billing-records"; +import * as teamCredentialPoolActual from "@/lib/services/team-credential-pool"; // The REAL settler — explicitly NOT mocked. This is the component under test. import { createCreditReservationSettler } from "@/lib/utils/credit-reservation"; @@ -105,11 +106,22 @@ mock.module("@/lib/services/ai-billing-records", () => ({ }, })); +const poolRecordUse = mock(async () => {}); +const poolRecordProviderFailure = mock(async () => {}); +mock.module("@/lib/services/team-credential-pool", () => ({ + ...teamCredentialPoolActual, + getTeamPoolRegistry: () => ({ + recordUse: poolRecordUse, + recordProviderFailure: poolRecordProviderFailure, + }), +})); + // Import the route AFTER the mocks so it binds to the stubs. -const { __streamingCreditTestHooks } = await import( +const { __billingBranchTestHooks, __streamingCreditTestHooks } = await import( "../v1/chat/completions/route" ); const { handleStreamingRequest } = __streamingCreditTestHooks; +const { shouldUsePooledNoopReservation } = __billingBranchTestHooks; afterAll(() => { mock.module("ai", () => aiActual); @@ -119,6 +131,10 @@ afterAll(() => { "@/lib/services/ai-billing-records", () => aiBillingRecordsActual, ); + mock.module( + "@/lib/services/team-credential-pool", + () => teamCredentialPoolActual, + ); }); /** @@ -174,7 +190,18 @@ const REQUEST = { /** Invoke handleStreamingRequest with the test's settler and a fixed shape. */ function callStreaming( settleReservation: (actualCost: number) => Promise | unknown, - options: { estimatedInputTokens?: number; signal?: AbortSignal } = {}, + options: { + affiliateCode?: string | null; + estimatedInputTokens?: number; + pooledCredential?: { + organizationId: string; + credentialId: string; + providerId: "openai-api" | "anthropic-api" | "cerebras-api"; + apiKey: string; + label: string; + } | null; + signal?: AbortSignal; + } = {}, ) { return handleStreamingRequest( MODEL, @@ -183,7 +210,7 @@ function callStreaming( REQUEST, { id: USER, organization_id: ORG }, null, - null, + options.affiliateCode ?? null, "idem-1", "req-1", null, @@ -196,6 +223,7 @@ function callStreaming( undefined, {} as never, "gateway" as never, + options.pooledCredential ?? null, ); } @@ -204,6 +232,8 @@ beforeEach(() => { billUsage.mockClear(); recordUsageAnalytics.mockClear(); aiBillingRecord.mockClear(); + poolRecordUse.mockClear(); + poolRecordProviderFailure.mockClear(); streamTextImpl = null; }); @@ -443,6 +473,87 @@ describe("streaming chat — client abort settles delivered usage", () => { }); describe("streaming chat — success settles once, no double-refund", () => { + test("pooled BYO key does not bypass monetized app billing reservation", () => { + const pooledCredential = { + organizationId: ORG, + credentialId: "pooled-credential-1", + providerId: "openai-api" as const, + apiKey: "sk-pooled", + label: "Team OpenAI key", + }; + + expect( + shouldUsePooledNoopReservation({ + pooledCredential, + useMonetizedAppBilling: false, + }), + ).toBe(true); + expect( + shouldUsePooledNoopReservation({ + pooledCredential, + useMonetizedAppBilling: true, + }), + ).toBe(false); + }); + + test("pooled BYO-key success suppresses affiliate markup while recording pool use", async () => { + const settle = mock(async () => null); + let onFinishPromise: Promise | undefined; + + streamTextImpl = (config) => { + const onFinish = config.onFinish as + | ((event: { + text: string; + usage: { + inputTokens: number; + outputTokens: number; + totalTokens: number; + }; + }) => Promise | unknown) + | undefined; + + return { + fullStream: (async function* () { + yield { type: "text-delta", id: "text-1", text: "pooled ok" }; + onFinishPromise = Promise.resolve( + onFinish?.({ + text: "pooled ok", + usage: { inputTokens: 2, outputTokens: 3, totalTokens: 5 }, + }), + ); + yield { type: "finish", finishReason: "stop" }; + })(), + }; + }; + + const res = await callStreaming(settle, { + affiliateCode: "SHOULD_NOT_PAY", + pooledCredential: { + organizationId: ORG, + credentialId: "pooled-credential-1", + providerId: "openai-api", + apiKey: "sk-pooled", + label: "Team OpenAI key", + }, + }); + const body = await res.text(); + expect(onFinishPromise).toBeDefined(); + await onFinishPromise; + + expect(body).toContain("pooled ok"); + expect(billUsage).toHaveBeenCalledTimes(1); + expect( + (billUsage.mock.calls[0][0] as { affiliateCode?: string | null }) + .affiliateCode, + ).toBe(null); + expect(settle).toHaveBeenCalledTimes(1); + expect(poolRecordUse).toHaveBeenCalledWith({ + organizationId: ORG, + credentialId: "pooled-credential-1", + userId: USER, + }); + }); + test("settler reconciles to actual cost exactly once; a stray onError cannot re-refund", async () => { const ledger = makeLedgerReservation(100, 0.015); const settle = createCreditReservationSettler(ledger.reservation); diff --git a/packages/cloud/api/__tests__/org-credentials-routes.test.ts b/packages/cloud/api/__tests__/org-credentials-routes.test.ts index 5725404da1970..0e882d570efa7 100644 --- a/packages/cloud/api/__tests__/org-credentials-routes.test.ts +++ b/packages/cloud/api/__tests__/org-credentials-routes.test.ts @@ -358,11 +358,14 @@ describe("PATCH/DELETE /api/organizations/credentials/:id — RBAC + IDOR", () = // The denial is audited (assertOrgMembership emits a denied event). const { dbWrite } = await import("@/db/client"); const audited = await dbWrite.execute( - `SELECT actor_id, result, metadata FROM auth_events + `SELECT actor_id, action, result, metadata FROM auth_events WHERE result = 'denied' AND resource_type = 'pooled_credential' AND resource_id = '${credentialByMemberA}';`, ); expect(audited.rows.length).toBeGreaterThanOrEqual(1); expect((audited.rows[0] as { actor_id: string }).actor_id).toBe(MEMBER_B); + expect((audited.rows[0] as { action: string }).action).toBe( + "secret.access", + ); }); test("a non-contributor member cannot DELETE someone else's key", async () => { diff --git a/packages/cloud/api/src/middleware/org-membership.ts b/packages/cloud/api/src/middleware/org-membership.ts index b65c62873f2ab..c2571bef5a592 100644 --- a/packages/cloud/api/src/middleware/org-membership.ts +++ b/packages/cloud/api/src/middleware/org-membership.ts @@ -29,6 +29,7 @@ const RESOURCE_TYPE_TO_ACTION: Record = { api_key: "api_key.use", agent: "agent.config.update", container: "agent.config.update", + pooled_credential: "secret.access", secret: "secret.access", workflow: "agent.config.update", }; diff --git a/packages/cloud/api/v1/chat/completions/route.ts b/packages/cloud/api/v1/chat/completions/route.ts index 5f7ea5490e9dc..abbb869a9c479 100644 --- a/packages/cloud/api/v1/chat/completions/route.ts +++ b/packages/cloud/api/v1/chat/completions/route.ts @@ -53,7 +53,9 @@ import { getAiProviderConfigurationError, getLanguageModel, hasLanguageModelProviderConfigured, + type PooledLanguageModelCredential, resolveAiProviderSource, + resolvePooledDirectProviderForModel, } from "@/lib/providers/language-model"; import { type AIUsage, @@ -91,6 +93,10 @@ import { resolveInferenceBillingLedger, } from "@/lib/services/inference-billing-ledger"; import { getCachedGatewayModelById } from "@/lib/services/model-catalog"; +import { + getTeamPoolRegistry, + type SelectedPooledCredential, +} from "@/lib/services/team-credential-pool"; import { createCreditReservationSettler } from "@/lib/utils/credit-reservation"; import { logger } from "@/lib/utils/logger"; import { getRouteTimeoutMs } from "@/lib/utils/request-timeout"; @@ -101,6 +107,12 @@ const ROUTE_MAX_DURATION = 800; // Minimum tokens to reserve for actual response generation when CoT is active const MIN_RESPONSE_TOKENS = 4096; +interface PooledInferenceCredential extends PooledLanguageModelCredential { + organizationId: string; + credentialId: string; + label: string; +} + function buildProviderReconciliationMetadata( provider: string, model: string, @@ -770,6 +782,72 @@ function getRecoverableProviderErrorStatus(error: unknown): number | null { return null; } +function toPooledInferenceCredential( + organizationId: string, + selected: SelectedPooledCredential, +): PooledInferenceCredential { + return { + organizationId, + credentialId: selected.credentialId, + providerId: selected.providerId, + apiKey: selected.apiKey, + label: selected.label, + }; +} + +async function selectPooledInferenceCredential(params: { + model: string; + organizationId: string; + sessionKey: string; +}): Promise { + const providerId = resolvePooledDirectProviderForModel(params.model); + if (!providerId) return null; + const selected = await getTeamPoolRegistry().selectCredential({ + organizationId: params.organizationId, + providerId, + sessionKey: params.sessionKey, + }); + return selected + ? toPooledInferenceCredential(params.organizationId, selected) + : null; +} + +async function recordPooledInferenceSuccess( + pooledCredential: PooledInferenceCredential | null, + userId: string, +): Promise { + if (!pooledCredential) return; + await getTeamPoolRegistry().recordUse({ + organizationId: pooledCredential.organizationId, + credentialId: pooledCredential.credentialId, + userId, + }); +} + +async function recordPooledInferenceFailure( + pooledCredential: PooledInferenceCredential | null, + error: unknown, +): Promise { + if (!pooledCredential) return; + const status = + getRecoverableProviderErrorStatus(error) ?? getErrorStatusCode(error); + if (![401, 403, 429].includes(status)) return; + await getTeamPoolRegistry().recordProviderFailure({ + organizationId: pooledCredential.organizationId, + credentialId: pooledCredential.credentialId, + providerId: pooledCredential.providerId, + status, + detail: error instanceof Error ? error.message : String(error), + }); +} + +function shouldUsePooledNoopReservation(params: { + pooledCredential: PooledInferenceCredential | null; + useMonetizedAppBilling: boolean; +}): boolean { + return Boolean(params.pooledCredential && !params.useMonetizedAppBilling); +} + // ============================================================================ // Main Handler // ============================================================================ @@ -915,8 +993,13 @@ export async function handleChatCompletionsPOST( // by dedicated agents) to the bare Cerebras id so pricing, routing, and // billing all agree and route to cerebras-direct instead of OpenRouter. const model = canonicalizeCerebrasModelId(request.model); + const pooledCredential = await selectPooledInferenceCredential({ + model, + organizationId: user.organization_id, + sessionKey: apiKey?.id ?? user.id, + }); - if (!hasLanguageModelProviderConfigured(model)) { + if (!pooledCredential && !hasLanguageModelProviderConfigured(model)) { return addCorsHeaders( Response.json( { @@ -933,7 +1016,9 @@ export async function handleChatCompletionsPOST( const provider = getProviderFromModel(model); const normalizedModel = normalizeModelName(model); - const billingSource = resolveAiProviderSource(model) ?? "gateway"; + const billingSource = pooledCredential + ? "gateway" + : (resolveAiProviderSource(model) ?? "gateway"); const cotBudget = resolveAnthropicThinkingBudgetTokens(model, process.env); const cotOptions = cotBudget != null @@ -1052,6 +1137,9 @@ export async function handleChatCompletionsPOST( | ((actualCost: number) => Promise) | null = null; + const useMonetizedAppBilling = Boolean( + useAppCredits && appId && monetizedApp, + ); if (useAppCredits && appId && monetizedApp) { const { totalCost } = await calculateCost( normalizedModel, @@ -1097,6 +1185,13 @@ export async function handleChatCompletionsPOST( } throw error; } + } else if ( + shouldUsePooledNoopReservation({ + pooledCredential, + useMonetizedAppBilling, + }) + ) { + reservation = creditsService.createAnonymousReservation(); } else { // Organization credits path. #9899 Tier-2: when optimistic billing is // enabled AND this org's balance comfortably clears SAFE_BALANCE_THRESHOLD, @@ -1252,7 +1347,14 @@ export async function handleChatCompletionsPOST( // Optimistic path debits the actual cost off the response path; otherwise the // reservation settler reconciles the upfront hold. Same (actualCost) shape. - if (optimisticSettler) { + if ( + shouldUsePooledNoopReservation({ + pooledCredential, + useMonetizedAppBilling, + }) + ) { + settleReservation = async () => null; + } else if (optimisticSettler) { settleReservation = optimisticSettler; } else { if (!reservation) { @@ -1316,6 +1418,7 @@ export async function handleChatCompletionsPOST( effectiveMaxTokens, webSearchOptions, billingSource, + pooledCredential, ) : await handleNonStreamingRequest( model, @@ -1336,6 +1439,7 @@ export async function handleChatCompletionsPOST( effectiveMaxTokens, webSearchOptions, billingSource, + pooledCredential, options.executionCtx, ); // Emit per-step pre-forward timing as a readable header (#9899). Debug-only @@ -1593,12 +1697,14 @@ async function handleStreamingRequest( effectiveMaxTokens: number | undefined, webSearchOptions: ReturnType, billingSource: PricingBillingSource, + pooledCredential: PooledInferenceCredential | null, ) { const provider = getProviderFromModel(model); const tools = convertTools(request.tools); const toolChoice = mapToolChoice(request.tool_choice); const experimentalOutput = mapResponseFormat(request.response_format); const billingPrompt = buildChatPromptForBilling(request); + const billingAffiliateCode = pooledCredential ? null : affiliateCode; let deliveredText = ""; let streamingSettlementPromise: Promise | null = null; @@ -1629,7 +1735,7 @@ async function handleStreamingRequest( provider, user, apiKey, - affiliateCode, + affiliateCode: billingAffiliateCode, appId, requestId, idempotencyKey, @@ -1657,7 +1763,7 @@ async function handleStreamingRequest( }); const result = streamText({ - model: getLanguageModel(model), + model: getLanguageModel(model, pooledCredential ?? undefined), system: systemPrompt, messages, ...webSearchOptions, @@ -1680,11 +1786,12 @@ async function handleStreamingRequest( billingSource, requestId, appId, - affiliateCode, + affiliateCode: billingAffiliateCode, streaming: true, }); const billing = await billUsage(billingContext, usage); const reconciliation = await settleReservation(billing.totalCost); + await recordPooledInferenceSuccess(pooledCredential, user.id); const usageRecord = await recordUsageAnalytics( billingContext, @@ -1763,6 +1870,7 @@ async function handleStreamingRequest( // later onFinish/onAbort cannot double-refund. onError: async ({ error }: { error: unknown }) => { await refundStreamingReservationOnce(); + await recordPooledInferenceFailure(pooledCredential, error); logger.error( "[Chat Completions] Stream provider error — reservation refunded", { @@ -1952,6 +2060,7 @@ async function handleStreamingRequest( await settleStreamingAbortOnce([]); } else { await refundStreamingReservationOnce(); + await recordPooledInferenceFailure(pooledCredential, error); } const status = getRecoverableProviderErrorStatus(error) ?? getErrorStatusCode(error); @@ -2027,12 +2136,14 @@ async function handleNonStreamingRequest( effectiveMaxTokens: number | undefined, webSearchOptions: ReturnType, billingSource: PricingBillingSource, + pooledCredential: PooledInferenceCredential | null, executionCtx: { waitUntil(promise: Promise): void } | undefined, ) { const provider = getProviderFromModel(model); const tools = convertTools(request.tools); const toolChoice = mapToolChoice(request.tool_choice); const experimentalOutput = mapResponseFormat(request.response_format); + const billingAffiliateCode = pooledCredential ? null : affiliateCode; const safeParamsNonStream = getSafeModelParams(model, { temperature: request.temperature, @@ -2048,7 +2159,7 @@ async function handleNonStreamingRequest( try { const result = await generateText({ - model: getLanguageModel(model), + model: getLanguageModel(model, pooledCredential ?? undefined), system: systemPrompt, messages, ...webSearchOptions, @@ -2102,11 +2213,12 @@ async function handleNonStreamingRequest( billingSource, requestId, appId, - affiliateCode, + affiliateCode: billingAffiliateCode, streaming: false, }); const billing = await billUsage(billingContext, result.usage); const reconciliation = await settleReservation(billing.totalCost); + await recordPooledInferenceSuccess(pooledCredential, user.id); const usageRecord = await recordUsageAnalytics( billingContext, @@ -2232,6 +2344,7 @@ async function handleNonStreamingRequest( ); } catch (error) { await settleReservation?.(0); + await recordPooledInferenceFailure(pooledCredential, error); throw error; } } @@ -2280,3 +2393,7 @@ export const __nativeToolingTestHooks = { export const __streamingCreditTestHooks = { handleStreamingRequest, } as const; + +export const __billingBranchTestHooks = { + shouldUsePooledNoopReservation, +} as const; diff --git a/packages/cloud/shared/src/db/repositories/pooled-credentials.ts b/packages/cloud/shared/src/db/repositories/pooled-credentials.ts index c449d6502df3e..aa552ed10d763 100644 --- a/packages/cloud/shared/src/db/repositories/pooled-credentials.ts +++ b/packages/cloud/shared/src/db/repositories/pooled-credentials.ts @@ -52,6 +52,20 @@ export class PooledCredentialsRepository { return rows[0]; } + async findByIdForOrganization( + id: string, + organizationId: string, + ): Promise { + const rows = await dbRead + .select() + .from(pooledCredentials) + .where( + and(eq(pooledCredentials.id, id), eq(pooledCredentials.organization_id, organizationId)), + ) + .limit(1); + return rows[0]; + } + async listByOrganization(organizationId: string): Promise { return await dbRead .select() @@ -126,6 +140,22 @@ export class PooledCredentialsRepository { async updatePoolState( id: string, state: PooledCredentialPoolState, + ): Promise { + return this.updatePoolStateWhere(id, undefined, state); + } + + async updatePoolStateForOrganization( + id: string, + organizationId: string, + state: PooledCredentialPoolState, + ): Promise { + return this.updatePoolStateWhere(id, organizationId, state); + } + + private async updatePoolStateWhere( + id: string, + organizationId: string | undefined, + state: PooledCredentialPoolState, ): Promise { const set: Record = { updated_at: new Date() }; if (state.label !== undefined) set.label = state.label; @@ -138,15 +168,37 @@ export class PooledCredentialsRepository { const rows = await dbWrite .update(pooledCredentials) .set(set) - .where(eq(pooledCredentials.id, id)) + .where( + organizationId + ? and(eq(pooledCredentials.id, id), eq(pooledCredentials.organization_id, organizationId)) + : eq(pooledCredentials.id, id), + ) .returning(); return rows[0]; } async delete(id: string): Promise { + return this.deleteWhere(id); + } + + async deleteForOrganization( + id: string, + organizationId: string, + ): Promise { + return this.deleteWhere(id, organizationId); + } + + private async deleteWhere( + id: string, + organizationId?: string, + ): Promise { const rows = await dbWrite .delete(pooledCredentials) - .where(eq(pooledCredentials.id, id)) + .where( + organizationId + ? and(eq(pooledCredentials.id, id), eq(pooledCredentials.organization_id, organizationId)) + : eq(pooledCredentials.id, id), + ) .returning(); return rows[0]; } diff --git a/packages/cloud/shared/src/lib/middleware/rate-limit-config-verdict.test.ts b/packages/cloud/shared/src/lib/middleware/rate-limit-config-verdict.test.ts index 3d8a3fb30a2f0..1a9e90c9fc5dd 100644 --- a/packages/cloud/shared/src/lib/middleware/rate-limit-config-verdict.test.ts +++ b/packages/cloud/shared/src/lib/middleware/rate-limit-config-verdict.test.ts @@ -1,5 +1,5 @@ import { describe, expect, test } from "bun:test"; -import { rateLimitConfigVerdict } from "./rate-limit-hono-cloudflare"; +import { applyRateLimitMultiplier, rateLimitConfigVerdict } from "./rate-limit-hono-cloudflare"; // #9853 P1.1 — production must never silently serve with rate limiting OFF. describe("rateLimitConfigVerdict", () => { @@ -62,3 +62,36 @@ describe("rateLimitConfigVerdict", () => { } }); }); + +describe("applyRateLimitMultiplier", () => { + const config = { windowMs: 60_000, maxRequests: 10 }; + + test("non-production RATE_LIMIT_MULTIPLIER scales maxRequests", () => { + expect( + applyRateLimitMultiplier(config, { + NODE_ENV: "development", + RATE_LIMIT_MULTIPLIER: "25", + } as never), + ).toEqual({ windowMs: 60_000, maxRequests: 250 }); + }); + + test("invalid or sub-1 multiplier is ignored", () => { + for (const RATE_LIMIT_MULTIPLIER of ["0", "-2", "nope"]) { + expect( + applyRateLimitMultiplier(config, { + NODE_ENV: "development", + RATE_LIMIT_MULTIPLIER, + } as never), + ).toEqual(config); + } + }); + + test("production never scales limits", () => { + expect( + applyRateLimitMultiplier(config, { + NODE_ENV: "production", + RATE_LIMIT_MULTIPLIER: "100", + } as never), + ).toEqual(config); + }); +}); diff --git a/packages/cloud/shared/src/lib/middleware/rate-limit-hono-cloudflare.ts b/packages/cloud/shared/src/lib/middleware/rate-limit-hono-cloudflare.ts index e024ad624574f..abda12055f7d8 100644 --- a/packages/cloud/shared/src/lib/middleware/rate-limit-hono-cloudflare.ts +++ b/packages/cloud/shared/src/lib/middleware/rate-limit-hono-cloudflare.ts @@ -130,6 +130,15 @@ function applyRateLimitHeaders(c: Context, headers: Record): voi } } +export function applyRateLimitMultiplier(config: RateLimitConfig, env: Bindings): RateLimitConfig { + const m = multiplier(env); + if (m === 1) return config; + return { + ...config, + maxRequests: config.maxRequests * m, + }; +} + export async function checkUpstash( redis: CompatibleRedis, key: string, @@ -171,19 +180,27 @@ export function rateLimit(config: RateLimitConfig): MiddlewareHandler { return; } + const effectiveConfig = applyRateLimitMultiplier(config, env); + if ( (env.RATE_LIMIT_DISABLED === "true" || env.PLAYWRIGHT_TEST_AUTH === "true") && env.NODE_ENV !== "production" ) { await next(); - applyRateLimitHeaders(c, rateLimitHeaders(config, fallOpenResult(config), "disabled")); + applyRateLimitHeaders( + c, + rateLimitHeaders(effectiveConfig, fallOpenResult(effectiveConfig), "disabled"), + ); return; } const redis = getRedis(env); if (!redis) { await next(); - applyRateLimitHeaders(c, rateLimitHeaders(config, fallOpenResult(config), "fall-open")); + applyRateLimitHeaders( + c, + rateLimitHeaders(effectiveConfig, fallOpenResult(effectiveConfig), "fall-open"), + ); return; } @@ -192,7 +209,12 @@ export function rateLimit(config: RateLimitConfig): MiddlewareHandler { let policy = "redis"; try { - result = await checkUpstash(redis, key, config.windowMs, config.maxRequests); + result = await checkUpstash( + redis, + key, + effectiveConfig.windowMs, + effectiveConfig.maxRequests, + ); } catch (error) { // Rate limiting is protective middleware. If its backing store is down // or unreachable in local Worker dev, requests should fall open instead @@ -200,11 +222,11 @@ export function rateLimit(config: RateLimitConfig): MiddlewareHandler { logger.warn("[RateLimit] Redis unavailable; falling open", { error: error instanceof Error ? error.message : String(error), }); - result = fallOpenResult(config); + result = fallOpenResult(effectiveConfig); policy = "redis-unavailable"; } - const headers = rateLimitHeaders(config, result, policy); + const headers = rateLimitHeaders(effectiveConfig, result, policy); if (!result.allowed) { return c.json( @@ -212,8 +234,8 @@ export function rateLimit(config: RateLimitConfig): MiddlewareHandler { success: false, error: "Too many requests", code: "rate_limit_exceeded" as const, - message: `Rate limit exceeded. Maximum ${config.maxRequests} requests per ${Math.ceil( - config.windowMs / 1000, + message: `Rate limit exceeded. Maximum ${effectiveConfig.maxRequests} requests per ${Math.ceil( + effectiveConfig.windowMs / 1000, )} seconds.`, retryAfter: result.retryAfter, }, diff --git a/packages/cloud/shared/src/lib/providers/language-model-cerebras-fallback.test.ts b/packages/cloud/shared/src/lib/providers/language-model-cerebras-fallback.test.ts index 5f499d48e1959..b439672f85378 100644 --- a/packages/cloud/shared/src/lib/providers/language-model-cerebras-fallback.test.ts +++ b/packages/cloud/shared/src/lib/providers/language-model-cerebras-fallback.test.ts @@ -57,6 +57,16 @@ function tooManyRequests(): Response { }); } +function authorizationHeader(init?: RequestInit): string | null { + const headers = init?.headers; + if (!headers) return null; + if (headers instanceof Headers) return headers.get("authorization"); + if (Array.isArray(headers)) { + return headers.find(([name]) => name.toLowerCase() === "authorization")?.[1] ?? null; + } + return headers.authorization ?? headers.Authorization ?? null; +} + afterEach(() => { globalThis.fetch = ORIGINAL_FETCH; }); @@ -84,6 +94,28 @@ describe("getLanguageModel cerebras-direct (cerebras-only, no OpenRouter fallbac expect(hosts).toEqual(["cerebras"]); }); + test("a pooled Cerebras credential is used instead of the platform env key", async () => { + const authHeaders: Array = []; + globalThis.fetch = (async (url: RequestInfo | URL, init?: RequestInit) => { + hosts.push(hostOf(url)); + authHeaders.push(authorizationHeader(init)); + return completion("gemma-4-31b", "from-pooled-cerebras"); + }) as typeof fetch; + + const result = await generateText({ + model: getLanguageModel("gemma-4-31b", { + providerId: "cerebras-api", + apiKey: "pooled-cerebras-key", + }), + prompt: "hi", + maxRetries: 0, + }); + + expect(result.text).toBe("from-pooled-cerebras"); + expect(hosts).toEqual(["cerebras"]); + expect(authHeaders).toEqual(["Bearer pooled-cerebras-key"]); + }); + test("a 429 surfaces (cerebras-only) and is never routed to OpenRouter", async () => { globalThis.fetch = (async (url: RequestInfo | URL) => { hosts.push(hostOf(url)); diff --git a/packages/cloud/shared/src/lib/providers/language-model.ts b/packages/cloud/shared/src/lib/providers/language-model.ts index 1018b5867fafb..b8d241110a673 100644 --- a/packages/cloud/shared/src/lib/providers/language-model.ts +++ b/packages/cloud/shared/src/lib/providers/language-model.ts @@ -10,6 +10,7 @@ import { isGroqNativeModel, isVastNativeModel, } from "../models"; +import type { PooledDirectProvider } from "../services/team-credential-pool/provider-map"; import { logger } from "../utils/logger"; import { RETRYABLE_UPSTREAM_STATUSES } from "./failover"; import { toBitRouterModelId } from "./model-id-translation"; @@ -163,6 +164,50 @@ function getAnthropicClient() { return anthropicClient; } +export interface PooledLanguageModelCredential { + providerId: PooledDirectProvider; + apiKey: string; +} + +export function resolvePooledDirectProviderForModel(model: string): PooledDirectProvider | null { + if (isCerebrasNativeModel(model)) return "cerebras-api"; + if (isOpenAINativeModel(model) && !requiresGatewayRouting(model)) return "openai-api"; + if (isAnthropicNativeModel(model)) return "anthropic-api"; + return null; +} + +function getPooledLanguageModel(model: string, credential: PooledLanguageModelCredential) { + const providerId = resolvePooledDirectProviderForModel(model); + if (!providerId || providerId !== credential.providerId) return null; + + if (providerId === "cerebras-api") { + return withRateLimitFailFast( + createOpenAI({ + apiKey: credential.apiKey, + baseURL: "https://api.cerebras.ai/v1", + }).chat(normalizeCerebrasModelId(model)), + ); + } + + if (providerId === "openai-api") { + const baseURL = getProviderKey("OPENAI_BASE_URL") ?? undefined; + const client = createOpenAI({ + apiKey: credential.apiKey, + ...(baseURL ? { baseURL } : {}), + }); + const modelId = normalizeOpenAIModelId(model); + return baseURL ? client.chat(modelId) : client.languageModel(modelId); + } + + if (providerId === "anthropic-api") { + return createAnthropic({ apiKey: credential.apiKey }).languageModel( + normalizeAnthropicModelId(model), + ); + } + + return null; +} + function getVercelAIGatewayClient() { if (!vercelAIGatewayClient) { const apiKey = getVercelAIGatewayApiKey(); @@ -418,7 +463,12 @@ export function hasTextEmbeddingProviderConfigured(): boolean { return Boolean(getProviderKey("OPENAI_API_KEY") || getVercelAIGatewayApiKey()); } -export function getLanguageModel(model: string) { +export function getLanguageModel(model: string, credential?: PooledLanguageModelCredential) { + if (credential) { + const pooledModel = getPooledLanguageModel(model, credential); + if (pooledModel) return pooledModel; + } + if (isGroqNativeModel(model)) { return getGroqClient().languageModel(getGroqApiModelId(model)); } diff --git a/packages/cloud/shared/src/lib/services/__tests__/team-credential-pool.test.ts b/packages/cloud/shared/src/lib/services/__tests__/team-credential-pool.test.ts index 9d7e0519bcd13..574577632a6b3 100644 --- a/packages/cloud/shared/src/lib/services/__tests__/team-credential-pool.test.ts +++ b/packages/cloud/shared/src/lib/services/__tests__/team-credential-pool.test.ts @@ -51,8 +51,10 @@ let svc: typeof import("../team-credential-pool/service"); let registryMod: typeof import("../team-credential-pool/registry"); const ORG_A = "11111111-1111-4111-8111-111111111111"; +const ORG_B = "22222222-2222-4222-8222-222222222222"; const OWNER_A = "aaaaaaaa-1111-4111-8111-111111111111"; const MEMBER_A = "aaaaaaaa-2222-4222-8222-222222222222"; +const OWNER_B = "bbbbbbbb-1111-4111-8111-111111111111"; const AUDIT = { actorType: "user" as const, @@ -120,7 +122,10 @@ beforeAll(async () => { ); await apply(); - await dbWrite.insert(organizations).values([{ id: ORG_A, name: "Org A", slug: "org-a" }]); + await dbWrite.insert(organizations).values([ + { id: ORG_A, name: "Org A", slug: "org-a" }, + { id: ORG_B, name: "Org B", slug: "org-b" }, + ]); await dbWrite.insert(users).values([ { id: OWNER_A, @@ -136,6 +141,13 @@ beforeAll(async () => { role: "member", steward_user_id: `steward-${MEMBER_A}`, }, + { + id: OWNER_B, + email: "owner@b.test", + organization_id: ORG_B, + role: "owner", + steward_user_id: `steward-${OWNER_B}`, + }, ]); } catch (error) { pgliteReady = false; @@ -318,6 +330,44 @@ describe("selection — real AccountPool rotation + health", () => { expect(seen.has(credBeta)).toBe(true); }); + test("Worker provider outcome writeback marks 429 and 401 credentials unhealthy", async () => { + const registry = new registryMod.TeamPoolRegistry(); + + await registry.recordProviderFailure({ + organizationId: ORG_A, + credentialId: credBeta, + providerId: "anthropic-api", + status: 429, + detail: "429 from Worker inference", + }); + const betaAfter429 = await repo.findById(credBeta); + expect(betaAfter429?.health).toBe("rate-limited"); + expect(betaAfter429?.health_detail?.until).toBeGreaterThan(Date.now()); + expect(betaAfter429?.health_detail?.lastError).toBe("429 from Worker inference"); + + await registry.recordProviderFailure({ + organizationId: ORG_A, + credentialId: credGamma, + providerId: "anthropic-api", + status: 401, + detail: "401 from Worker inference", + }); + const gammaAfter401 = await repo.findById(credGamma); + expect(gammaAfter401?.health).toBe("needs-reauth"); + expect(gammaAfter401?.health_detail?.lastError).toBe("401 from Worker inference"); + + // Preserve the fixture state expected by the keep-alive test below: beta is + // rate-limited, but its cool-off has already passed. + await repo.updatePoolState(credBeta, { + health: "rate-limited", + health_detail: { + until: Date.now() - 1_000, + lastChecked: Date.now(), + lastError: "expired test cool-off", + }, + }); + }); + test("writeAccount (401 → needs-reauth) updates metadata only, ciphertext untouched", async () => { const before = await repo.findById(credGamma); if (!before) throw new Error("gamma missing"); @@ -428,6 +478,43 @@ describe("selection — real AccountPool rotation + health", () => { expect((await repo.findById(credAlpha))?.last_used_at).not.toBeNull(); }); + test("wrong-org service calls cannot update or delete a known credential id", async () => { + const before = await repo.findById(credAlpha); + if (!before) throw new Error("alpha missing"); + const secretId = before.secret_id; + + expect( + await repo.updatePoolStateForOrganization(credAlpha, ORG_B, { + enabled: false, + }), + ).toBeUndefined(); + expect(await repo.deleteForOrganization(credAlpha, ORG_B)).toBeUndefined(); + + await expect( + svc.updatePooledCredential({ + credentialId: credAlpha, + organizationId: ORG_B, + enabled: false, + }), + ).rejects.toMatchObject({ status: 404 }); + await expect( + svc.removePooledCredential({ + credentialId: credAlpha, + organizationId: ORG_B, + audit: { + actorType: "user", + actorId: OWNER_B, + source: "team-credential-pool.test", + }, + }), + ).rejects.toMatchObject({ status: 404 }); + + const after = await repo.findById(credAlpha); + expect(after?.organization_id).toBe(ORG_A); + expect(after?.enabled).toBe(true); + expect(await secretRow(secretId)).toBeDefined(); + }); + test("remove deletes the pool row AND its vault secret", async () => { const delta = await svc.contributePooledCredential({ organizationId: ORG_A, diff --git a/packages/cloud/shared/src/lib/services/team-credential-pool/pool-deps.ts b/packages/cloud/shared/src/lib/services/team-credential-pool/pool-deps.ts index 83428ab12d163..3449591f76c81 100644 --- a/packages/cloud/shared/src/lib/services/team-credential-pool/pool-deps.ts +++ b/packages/cloud/shared/src/lib/services/team-credential-pool/pool-deps.ts @@ -92,12 +92,16 @@ export class DrizzleAccountPoolDeps implements AccountPoolDeps { // Pool-owned columns ONLY. The pool spreads `...account` from a snapshot // that may be stale; persisting label/enabled/priority here would clobber // a concurrent admin PATCH (e.g. re-enable a just-disabled credential). - const updated = await pooledCredentialsRepository.updatePoolState(account.id, { - health: account.health, - health_detail: account.healthDetail ?? null, - usage: account.usage ?? null, - last_used_at: account.lastUsedAt ? new Date(account.lastUsedAt) : null, - }); + const updated = await pooledCredentialsRepository.updatePoolStateForOrganization( + account.id, + this.organizationId, + { + health: account.health, + health_detail: account.healthDetail ?? null, + usage: account.usage ?? null, + last_used_at: account.lastUsedAt ? new Date(account.lastUsedAt) : null, + }, + ); if (!updated) { // Row deleted underneath us (e.g. contributor removed it) — drop it // from the snapshot instead of resurrecting stale state. @@ -111,8 +115,12 @@ export class DrizzleAccountPoolDeps implements AccountPoolDeps { async deleteAccount(providerId: PoolProviderId, accountId: string): Promise { const row = - this.rowsById.get(accountId) ?? (await pooledCredentialsRepository.findById(accountId)); - const deleted = await pooledCredentialsRepository.delete(accountId); + this.rowsById.get(accountId) ?? + (await pooledCredentialsRepository.findByIdForOrganization(accountId, this.organizationId)); + const deleted = await pooledCredentialsRepository.deleteForOrganization( + accountId, + this.organizationId, + ); delete this.snapshot[poolRecordKey(providerId, accountId)]; this.rowsById.delete(accountId); const secretId = row?.secret_id; diff --git a/packages/cloud/shared/src/lib/services/team-credential-pool/registry.ts b/packages/cloud/shared/src/lib/services/team-credential-pool/registry.ts index af2d4a2c3d257..c848f99313914 100644 --- a/packages/cloud/shared/src/lib/services/team-credential-pool/registry.ts +++ b/packages/cloud/shared/src/lib/services/team-credential-pool/registry.ts @@ -177,9 +177,13 @@ export class TeamPoolRegistry { userId: params.userId, day, }); - await pooledCredentialsRepository.updatePoolState(params.credentialId, { - last_used_at: new Date(), - }); + await pooledCredentialsRepository.updatePoolStateForOrganization( + params.credentialId, + params.organizationId, + { + last_used_at: new Date(), + }, + ); } catch (err) { logger.warn("[TeamPoolRegistry] usage attribution failed", { organizationId: params.organizationId, @@ -189,6 +193,43 @@ export class TeamPoolRegistry { } } + /** + * Feed direct Worker/provider failures back into the org pool. Only statuses + * that tell us something about the selected credential mutate pool health: + * auth failures need reauth, and 429s cool off the credential briefly. + */ + async recordProviderFailure(params: { + organizationId: string; + credentialId: string; + providerId: PooledDirectProvider; + status: number; + detail?: string; + }): Promise { + if (![401, 403, 429].includes(params.status)) return; + try { + const entry = await this.getOrgPool(params.organizationId); + if (!entry) return; + const detail = params.detail ?? `provider returned ${params.status}`; + if (params.status === 429) { + await entry.pool.markRateLimited(params.credentialId, Date.now() + 60_000, detail, { + providerId: params.providerId, + }); + } else { + await entry.pool.markNeedsReauth(params.credentialId, detail, { + providerId: params.providerId, + }); + } + } catch (err) { + logger.warn("[TeamPoolRegistry] provider failure writeback failed", { + organizationId: params.organizationId, + credentialId: params.credentialId, + providerId: params.providerId, + status: params.status, + error: err instanceof Error ? err.message : String(err), + }); + } + } + private evictLru(): void { while (this.pools.size > this.maxOrgPools) { const oldest = this.pools.keys().next().value; diff --git a/packages/cloud/shared/src/lib/services/team-credential-pool/service.ts b/packages/cloud/shared/src/lib/services/team-credential-pool/service.ts index ad1cb681912c3..a646c4301ac8b 100644 --- a/packages/cloud/shared/src/lib/services/team-credential-pool/service.ts +++ b/packages/cloud/shared/src/lib/services/team-credential-pool/service.ts @@ -193,8 +193,13 @@ export async function listPooledCredentials( ); } -export async function getPooledCredential(id: string): Promise { - return pooledCredentialsRepository.findById(id); +export async function getPooledCredential( + id: string, + organizationId?: string, +): Promise { + return organizationId + ? pooledCredentialsRepository.findByIdForOrganization(id, organizationId) + : pooledCredentialsRepository.findById(id); } export interface UpdatePooledCredentialParams { @@ -208,11 +213,15 @@ export interface UpdatePooledCredentialParams { export async function updatePooledCredential( params: UpdatePooledCredentialParams, ): Promise { - const updated = await pooledCredentialsRepository.updatePoolState(params.credentialId, { - ...(params.enabled !== undefined ? { enabled: params.enabled } : {}), - ...(params.priority !== undefined ? { priority: params.priority } : {}), - ...(params.label !== undefined ? { label: params.label } : {}), - }); + const updated = await pooledCredentialsRepository.updatePoolStateForOrganization( + params.credentialId, + params.organizationId, + { + ...(params.enabled !== undefined ? { enabled: params.enabled } : {}), + ...(params.priority !== undefined ? { priority: params.priority } : {}), + ...(params.label !== undefined ? { label: params.label } : {}), + }, + ); if (!updated) { throw new TeamCredentialPoolError("Credential not found", 404); } @@ -225,7 +234,10 @@ export async function removePooledCredential(params: { organizationId: string; audit: AuditContext; }): Promise { - const row = await pooledCredentialsRepository.delete(params.credentialId); + const row = await pooledCredentialsRepository.deleteForOrganization( + params.credentialId, + params.organizationId, + ); if (!row) { throw new TeamCredentialPoolError("Credential not found", 404); }