Compare commits

...

2 Commits

Author SHA1 Message Date
diegosouzapw
0cddfb918b Merge remote-tracking branch 'origin/release/v3.8.55' into fix/usage-command-json-account-scope 2026-11-17 23:50:40 -03:00
diegosouzapw
90481eb9b3 fix(security): keep shared provider accounts out of the usage command JSON for client keys
GET /api/usage/om-usage?format=json returned every active provider connection
(ids, plans, raw quota windows, resets) to any key with allowUsageCommand.
provider/providers are now returned only to keys with self:account-quota or a
management scope, the rule /v1/me/status already applies; other keys get their
personal quota only. Missing scopes fail closed.

Co-authored-by: Witroch4 <175152067+Witroch4@users.noreply.github.com>
2026-11-17 12:35:55 -03:00
3 changed files with 99 additions and 1 deletions

View File

@@ -0,0 +1 @@
- Return the shared provider accounts in the usage command JSON (`?format=json`) only to keys with `self:account-quota` or a management scope, the same rule `/v1/me/status` uses; other keys get their personal quota only (thanks @Witroch4).

View File

@@ -4,6 +4,8 @@ import {
type ApiKeyUsageLimitStatus,
} from "@/lib/usage/apiKeyUsageLimits";
import { buildErrorBody } from "@omniroute/open-sse/utils/error";
import { hasManageScope } from "@/shared/constants/managementScopes";
import { hasSelfAccountQuotaScope } from "@/shared/constants/selfServiceScopes";
export const INTERNAL_USAGE_COMMAND = "@@om-usage";
export const USAGE_COMMAND_DISABLED_MESSAGE = "Usage command is disabled for this API key.";
@@ -23,6 +25,21 @@ export interface UsageCommandApiKeyMetadata {
dailyUsageLimitUsd?: number | null;
weeklyUsageLimitUsd?: number | null;
fiveHourUsageLimitUsd?: number | null;
scopes?: string[] | null;
}
/**
* The shared provider accounts behind a key (plan, raw quota windows, reset
* times, connection ids) are operator data, not the key holder's. Only a key
* explicitly granted `self:account-quota` (the same scope that gates
* `accountQuotas` on /v1/me/status) or a management key may read them; any other
* key gets its own personal quota and nothing else. Missing scopes fail closed.
*/
export function canReadSharedAccountQuota(scopes: readonly string[] | null | undefined): boolean {
const list = Array.isArray(scopes)
? scopes.filter((s): s is string => typeof s === "string")
: [];
return hasSelfAccountQuotaScope(list) || hasManageScope(list);
}
interface ProviderConnectionLike {
@@ -547,7 +564,9 @@ function appendQuotaBlock(
* NOTE on percentage semantics (#15530):
* - JSON `provider.quotas` and `providers[].quotas` expose raw upstream
* snapshots (unadjusted usage and remaining numbers/percentages), alongside
* connection-level `quotaWindowThresholds`.
* connection-level `quotaWindowThresholds` — ONLY to keys allowed to read the
* shared accounts ({@link canReadSharedAccountQuota}). Every other key gets
* `provider: null` and `providers: []`.
* - In contrast, text output (`buildUsageCommandText` / terminal `@@om-usage`)
* renders cutoff-adjusted remaining percentages (`NN% left`) via
* {@link effectiveRemainingPercent}, where the configured cutoff reserve
@@ -591,6 +610,9 @@ export async function buildUsageCommandJson(
{ now: resolvedDeps.now }
)
: null;
if (!canReadSharedAccountQuota(metadata.scopes)) {
return { allowed: true, personal, provider: null, providers: [] };
}
const snapshots = await collectUsageSnapshots(metadata, resolvedDeps);
const provider = selectUsageSnapshot(snapshots, selection);
return { allowed: true, personal, provider, providers: snapshots };

View File

@@ -32,11 +32,14 @@ function allowedDeps(overrides: Record<string, unknown> = {}) {
return {
now: () => NOW,
isValidApiKey: async (apiKey: string) => apiKey === "sk-allowed",
// The panel key is explicitly granted the shared-account view; a plain
// client key (self:usage only) is covered by the tests at the bottom.
getApiKeyMetadata: async () => ({
id: "key-allowed",
name: "panel key",
allowUsageCommand: true,
usageLimitEnabled: true,
scopes: ["self:usage", "self:account-quota"],
}),
getProviderConnections: async () => [
{ id: "conn-claude", provider: "claude", isActive: true },
@@ -223,3 +226,75 @@ test("om-usage preserves raw quota in json while text scales remaining quota by
assert.match(text, /Weekly/);
assert.match(text, /20% left/);
});
// A client key with the usage command could read, through ?format=json, every
// shared provider account: connection ids, plan, raw quota and resets. Those
// belong to the operator, not to the key holder.
function failingProviderCollectors() {
const fail = () => {
throw new Error("provider accounts must not be read for this key");
};
return {
getProviderConnections: async () => fail(),
getAllProviderLimitsCache: () => fail(),
getProviderConnectionById: async () => fail(),
getProviderLimitsCache: () => fail(),
};
}
for (const [label, scopes] of [
["a plain client key (self:usage only)", ["self:usage"]],
["a key whose metadata carries no scopes", undefined],
] as const) {
test(`om-usage ?format=json hides the shared provider accounts from ${label}`, async () => {
const response = await handleInternalUsageCommandHttpRequest(
new Request("http://localhost/api/usage/om-usage?format=json", {
headers: { Authorization: "Bearer sk-allowed" },
}),
allowedDeps({
getApiKeyMetadata: async () => ({
id: "key-client",
name: "client key",
allowUsageCommand: true,
usageLimitEnabled: true,
...(scopes ? { scopes: [...scopes] } : {}),
}),
...failingProviderCollectors(),
})
);
assert.equal(response.status, 200);
const body = (await response.json()) as {
allowed: boolean;
personal: { weeklySpentUsd: number } | null;
provider: unknown;
providers: unknown[];
};
assert.equal(body.allowed, true);
assert.equal(body.personal?.weeklySpentUsd, 8);
assert.equal(body.provider, null);
assert.deepEqual(body.providers, []);
assert.doesNotMatch(JSON.stringify(body), /conn-claude|conn-codex|Claude Max|Codex Pro/);
});
}
test("om-usage ?format=json still shows the shared accounts to a management key", async () => {
const response = await handleInternalUsageCommandHttpRequest(
new Request("http://localhost/api/usage/om-usage?format=json", {
headers: { Authorization: "Bearer sk-allowed" },
}),
allowedDeps({
getApiKeyMetadata: async () => ({
id: "key-admin",
name: "operator key",
allowUsageCommand: true,
usageLimitEnabled: false,
scopes: ["manage", "self:usage"],
}),
})
);
assert.equal(response.status, 200);
const body = (await response.json()) as { providers: Array<{ provider: string }> };
assert.deepEqual(body.providers.map((s) => s.provider).sort(), ["claude", "codex"]);
});