Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
50 changes: 50 additions & 0 deletions .github/issue-evidence/11586-credential-pool-followups.md
Original file line number Diff line number Diff line change
@@ -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.
15 changes: 15 additions & 0 deletions packages/agent/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
4 changes: 2 additions & 2 deletions packages/agent/src/auth/credentials.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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.
Expand Down
12 changes: 11 additions & 1 deletion packages/app-core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
},
Expand Down
2 changes: 1 addition & 1 deletion packages/app-core/src/services/account-pool.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ import type {
LinkedAccountProviderId,
LinkedAccountsConfig,
LinkedAccountUsage,
} from "@elizaos/shared";
} from "@elizaos/shared/contracts/service-routing";
import {
pollAnthropicUsage,
pollCodexUsage,
Expand Down
2 changes: 1 addition & 1 deletion packages/app-core/src/services/account-usage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
14 changes: 11 additions & 3 deletions packages/app-core/src/services/coding-account-bridge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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);
Expand All @@ -119,6 +131,10 @@ afterAll(() => {
"@/lib/services/ai-billing-records",
() => aiBillingRecordsActual,
);
mock.module(
"@/lib/services/team-credential-pool",
() => teamCredentialPoolActual,
);
});

/**
Expand Down Expand Up @@ -174,7 +190,18 @@ const REQUEST = {
/** Invoke handleStreamingRequest with the test's settler and a fixed shape. */
function callStreaming(
settleReservation: (actualCost: number) => Promise<unknown> | 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,
Expand All @@ -183,7 +210,7 @@ function callStreaming(
REQUEST,
{ id: USER, organization_id: ORG },
null,
null,
options.affiliateCode ?? null,
"idem-1",
"req-1",
null,
Expand All @@ -196,6 +223,7 @@ function callStreaming(
undefined,
{} as never,
"gateway" as never,
options.pooledCredential ?? null,
);
}

Expand All @@ -204,6 +232,8 @@ beforeEach(() => {
billUsage.mockClear();
recordUsageAnalytics.mockClear();
aiBillingRecord.mockClear();
poolRecordUse.mockClear();
poolRecordProviderFailure.mockClear();
streamTextImpl = null;
});

Expand Down Expand Up @@ -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<unknown> | undefined;

streamTextImpl = (config) => {
const onFinish = config.onFinish as
| ((event: {
text: string;
usage: {
inputTokens: number;
outputTokens: number;
totalTokens: number;
};
}) => Promise<unknown> | 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);
Expand Down
5 changes: 4 additions & 1 deletion packages/cloud/api/__tests__/org-credentials-routes.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -208,7 +208,7 @@

describe("POST /api/organizations/credentials — contribute", () => {
test("rejects a key the provider 401s: 400, nothing stored", async () => {
expect(pgliteReady).toBe(true);

Check failure on line 211 in packages/cloud/api/__tests__/org-credentials-routes.test.ts

View workflow job for this annotation

GitHub Actions / coverage on changed files

error: expect(received).toBe(expected)

Expected: true Received: false at <anonymous> (/home/runner/work/eliza/eliza/packages/cloud/api/__tests__/org-credentials-routes.test.ts:211:25)
const res = await app.request(
"/api/organizations/credentials",
authed("eliza_member_a", {
Expand All @@ -227,7 +227,7 @@
});

test("rejects subscription providers with the Phase-2 gate message", async () => {
const res = await app.request(

Check failure on line 230 in packages/cloud/api/__tests__/org-credentials-routes.test.ts

View workflow job for this annotation

GitHub Actions / coverage on changed files

TypeError: undefined is not an object (evaluating 'app.request')

at <anonymous> (/home/runner/work/eliza/eliza/packages/cloud/api/__tests__/org-credentials-routes.test.ts:230:23)
"/api/organizations/credentials",
authed("eliza_member_a", {
method: "POST",
Expand All @@ -246,7 +246,7 @@

test("member contributes a live-validated key: 201 masked summary, plaintext never returned, ciphertext at rest", async () => {
const plaintext = "sk-ant-team-key-one-1111";
const res = await app.request(

Check failure on line 249 in packages/cloud/api/__tests__/org-credentials-routes.test.ts

View workflow job for this annotation

GitHub Actions / coverage on changed files

TypeError: undefined is not an object (evaluating 'app.request')

at <anonymous> (/home/runner/work/eliza/eliza/packages/cloud/api/__tests__/org-credentials-routes.test.ts:249:23)
"/api/organizations/credentials",
authed("eliza_member_a", {
method: "POST",
Expand Down Expand Up @@ -283,7 +283,7 @@

describe("GET /api/organizations/credentials — member-readable, masked", () => {
test("member sees the masked list (no key material anywhere)", async () => {
const res = await app.request(

Check failure on line 286 in packages/cloud/api/__tests__/org-credentials-routes.test.ts

View workflow job for this annotation

GitHub Actions / coverage on changed files

TypeError: undefined is not an object (evaluating 'app.request')

at <anonymous> (/home/runner/work/eliza/eliza/packages/cloud/api/__tests__/org-credentials-routes.test.ts:286:23)
"/api/organizations/credentials",
authed("eliza_member_a2"),
ENV,
Expand All @@ -303,7 +303,7 @@
});

test("another org's member sees an empty pool (org-scoped)", async () => {
const res = await app.request(

Check failure on line 306 in packages/cloud/api/__tests__/org-credentials-routes.test.ts

View workflow job for this annotation

GitHub Actions / coverage on changed files

TypeError: undefined is not an object (evaluating 'app.request')

at <anonymous> (/home/runner/work/eliza/eliza/packages/cloud/api/__tests__/org-credentials-routes.test.ts:306:23)
"/api/organizations/credentials",
authed("eliza_member_b"),
ENV,
Expand All @@ -313,14 +313,14 @@
});

test("unauthenticated request is rejected", async () => {
const res = await app.request("/api/organizations/credentials", {}, ENV);

Check failure on line 316 in packages/cloud/api/__tests__/org-credentials-routes.test.ts

View workflow job for this annotation

GitHub Actions / coverage on changed files

TypeError: undefined is not an object (evaluating 'app.request')

at <anonymous> (/home/runner/work/eliza/eliza/packages/cloud/api/__tests__/org-credentials-routes.test.ts:316:23)
expect(res.status).toBeGreaterThanOrEqual(400);
});
});

describe("PATCH/DELETE /api/organizations/credentials/:id — RBAC + IDOR", () => {
test("member cannot PATCH (owner/admin only)", async () => {
const res = await app.request(

Check failure on line 323 in packages/cloud/api/__tests__/org-credentials-routes.test.ts

View workflow job for this annotation

GitHub Actions / coverage on changed files

TypeError: undefined is not an object (evaluating 'app.request')

at <anonymous> (/home/runner/work/eliza/eliza/packages/cloud/api/__tests__/org-credentials-routes.test.ts:323:23)
`/api/organizations/credentials/${credentialByMemberA}`,
authed("eliza_member_a2", {
method: "PATCH",
Expand All @@ -332,7 +332,7 @@
});

test("admin PATCHes enabled/priority", async () => {
const res = await app.request(

Check failure on line 335 in packages/cloud/api/__tests__/org-credentials-routes.test.ts

View workflow job for this annotation

GitHub Actions / coverage on changed files

TypeError: undefined is not an object (evaluating 'app.request')

at <anonymous> (/home/runner/work/eliza/eliza/packages/cloud/api/__tests__/org-credentials-routes.test.ts:335:23)
`/api/organizations/credentials/${credentialByMemberA}`,
authed("eliza_admin_a", {
method: "PATCH",
Expand All @@ -349,7 +349,7 @@
});

test("cross-org member gets an audited 403 on a real credential id (IDOR)", async () => {
const res = await app.request(

Check failure on line 352 in packages/cloud/api/__tests__/org-credentials-routes.test.ts

View workflow job for this annotation

GitHub Actions / coverage on changed files

TypeError: undefined is not an object (evaluating 'app.request')

at <anonymous> (/home/runner/work/eliza/eliza/packages/cloud/api/__tests__/org-credentials-routes.test.ts:352:23)
`/api/organizations/credentials/${credentialByMemberA}`,
authed("eliza_member_b", { method: "DELETE" }),
ENV,
Expand All @@ -358,15 +358,18 @@
// 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 () => {
const res = await app.request(

Check failure on line 372 in packages/cloud/api/__tests__/org-credentials-routes.test.ts

View workflow job for this annotation

GitHub Actions / coverage on changed files

TypeError: undefined is not an object (evaluating 'app.request')

at <anonymous> (/home/runner/work/eliza/eliza/packages/cloud/api/__tests__/org-credentials-routes.test.ts:372:23)
`/api/organizations/credentials/${credentialByMemberA}`,
authed("eliza_member_a2", { method: "DELETE" }),
ENV,
Expand Down
1 change: 1 addition & 0 deletions packages/cloud/api/src/middleware/org-membership.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ const RESOURCE_TYPE_TO_ACTION: Record<string, AuditAction> = {
api_key: "api_key.use",
agent: "agent.config.update",
container: "agent.config.update",
pooled_credential: "secret.access",
secret: "secret.access",
workflow: "agent.config.update",
};
Expand Down
Loading
Loading