Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

Cap a broker credential's calls per UTC day with one shared Postgres counter

Josh France6c19874377d8
diff --git a/src/admin/credential-usage-sink.ts b/src/admin/credential-usage-sink.ts
index 679f42cee..ff685db8f 100644
--- a/src/admin/credential-usage-sink.ts
+++ b/src/admin/credential-usage-sink.ts
@@ -33,16 +33,28 @@ export interface CredentialUsageSink {
record(s: Omit<CredentialUsageSample, "ts">): void;
list(opts?: CredentialUsageQuery): Promise<CredentialUsageSample[]>;
summary(slugs: readonly string[]): Promise<CredentialUsageSummary[]>;
+ admitDailyCall(slug: string, cap: number): Promise<boolean>;
}
-export function createCredentialUsageSink(): CredentialUsageSink {
+export const utcDayStart = (ms: number): number => ms - (ms % 86_400_000);
+
+export function createCredentialUsageSink(now: () => number = Date.now): CredentialUsageSink {
const sink = createTimestampedEventSink<CredentialUsageSample>({
max: 10000,
defaultLimit: CREDENTIAL_USAGE_WINDOW,
equalityFields: ["slug"],
});
+ const daily = new Map<string, { day: number; sent: number }>();
return {
...sink,
+ async admitDailyCall(slug, cap) {
+ const day = utcDayStart(now());
+ const tally = daily.get(slug)?.day === day ? daily.get(slug)! : { day, sent: 0 };
+ daily.set(slug, tally);
+ if (tally.sent >= cap) return false;
+ tally.sent += 1;
+ return true;
+ },
async summary(slugs) {
return Promise.all(
[...new Set(slugs)].map(async (slug) => {
diff --git a/src/admin/postgres-credential-usage-sink.ts b/src/admin/postgres-credential-usage-sink.ts
index 67b6e199f..29b537020 100644
--- a/src/admin/postgres-credential-usage-sink.ts
+++ b/src/admin/postgres-credential-usage-sink.ts
@@ -1,6 +1,7 @@
import { createPostgresEventSink, type EventColumn } from "./scoped-event-sink.ts";
import {
CREDENTIAL_USAGE_WINDOW,
+ utcDayStart,
type CredentialUsageSample,
type CredentialUsageSink,
} from "./credential-usage-sink.ts";
@@ -30,6 +31,12 @@ export function createPostgresCredentialUsageSink(connectionString: string): Cre
"CREATE INDEX CONCURRENTLY IF NOT EXISTS credential_usage_by_slug_ts_id ON credential_usage(slug, ts DESC, id DESC)",
],
},
+ {
+ id: "admin/scoped-events/credential_usage/0003",
+ statements: [
+ "CREATE TABLE IF NOT EXISTS credential_daily_calls(slug TEXT NOT NULL, day BIGINT NOT NULL, sent INT NOT NULL, PRIMARY KEY (slug, day))",
+ ],
+ },
],
},
defaultLimit: CREDENTIAL_USAGE_WINDOW,
@@ -38,6 +45,16 @@ export function createPostgresCredentialUsageSink(connectionString: string): Cre
});
return {
...sink,
+ async admitDailyCall(slug, cap) {
+ const rows = await sink.q(
+ `INSERT INTO credential_daily_calls(slug, day, sent) VALUES ($1, $2, 1)
+ ON CONFLICT (slug, day) DO UPDATE SET sent = credential_daily_calls.sent + 1
+ WHERE credential_daily_calls.sent < $3
+ RETURNING sent`,
+ [slug, utcDayStart(Date.now()), cap],
+ );
+ return rows.length > 0;
+ },
async summary(slugs) {
if (!slugs.length) return [];
const rows = await sink.q(
diff --git a/src/api/credential-broker.ts b/src/api/credential-broker.ts
index 32139beae..7663d047e 100644
--- a/src/api/credential-broker.ts
+++ b/src/api/credential-broker.ts
@@ -1,4 +1,5 @@
import { isComposioHost } from "../credentials/keychain.ts";
+import { errMessage } from "../util/errors.ts";
import type { CapabilityClaims } from "../auth/capability-token.ts";
import type { ScopeId } from "../types.ts";
import type { CredentialUsageSink } from "../admin/credential-usage-sink.ts";
@@ -198,6 +199,24 @@ export async function brokerCredentialCall(opts: {
return deny(403, "path_not_allowed", "url path is not in the credential's allowlist", rec.host);
}
+ if (rec.maxRequestsPerDay !== undefined) {
+ let admitted: boolean;
+ try {
+ if (!opts.usage) throw new Error("no usage ledger");
+ admitted = await opts.usage.admitDailyCall(slug, rec.maxRequestsPerDay);
+ } catch (err) {
+ console.error(`[credential-broker] daily cap check failed for ${slug}:`, errMessage(err));
+ return deny(503, "daily_cap_unavailable", "the credential's daily request cap could not be checked", rec.host);
+ }
+ if (!admitted)
+ return deny(
+ 429,
+ "daily_cap_reached",
+ `this credential has used its ${rec.maxRequestsPerDay} requests for today (UTC); it resets at 00:00 UTC`,
+ rec.host,
+ );
+ }
+
const headers: Record<string, string> = {};
if (body.headers && typeof body.headers === "object") {
for (const [k, v] of Object.entries(body.headers as Record<string, unknown>)) {
diff --git a/src/credentials/keychain.ts b/src/credentials/keychain.ts
index 429e9ec9f..61bdbe11a 100644
--- a/src/credentials/keychain.ts
+++ b/src/credentials/keychain.ts
@@ -190,6 +190,8 @@ export interface PublicServiceCredential {
deployments: boolean;
enabled: boolean;
hasSecret: boolean;
+ maxRequestsPerDay?: number;
+ source?: "deployment";
updatedBy?: string;
updatedAt: number;
}
@@ -206,6 +208,7 @@ export interface DecryptedServiceCredential {
allowedPathPrefixes?: string[];
deployments: boolean;
enabled: boolean;
+ maxRequestsPerDay?: number;
}
export function isValidCredentialSlug(slug: string): boolean {
diff --git a/test/credential-broker.test.ts b/test/credential-broker.test.ts
index 6b622a790..7fff6b7a7 100644
--- a/test/credential-broker.test.ts
+++ b/test/credential-broker.test.ts
@@ -474,3 +474,46 @@ test("generic credential broker cannot bypass Composio identity binding", async
assert.equal(result.status, 403);
assert.equal(cap.calls.length, 0);
});
+
+test("a daily cap admits that many outbound calls per UTC day, then refuses with 429 without calling out", async () => {
+ const cap = captureFetch();
+ let clock = Date.UTC(2026, 9, 16, 23, 0);
+ const usage = createCredentialUsageSink(() => clock);
+ const capped = base({
+ fetchImpl: cap.fetch,
+ usage,
+ reader: reader({ slug: "x-firehose", allowedPathPrefixes: ["/2/"], maxRequestsPerDay: 2 }),
+ });
+ assert.equal((await brokerCredentialCall(capped)).status, 200);
+ assert.equal(
+ (await brokerCredentialCall({ ...capped, body: { ...capped.body, url: "https://evil.example/" } })).status,
+ 403,
+ );
+ assert.equal((await brokerCredentialCall(capped)).status, 200);
+ const refused = await brokerCredentialCall(capped);
+ assert.equal(refused.status, 429);
+ assert.equal((refused.json as { error: string }).error, "daily_cap_reached");
+ assert.equal(cap.calls.length, 2);
+
+ clock = Date.UTC(2026, 9, 17, 0, 1);
+ assert.equal((await brokerCredentialCall(capped)).status, 200);
+ assert.equal(cap.calls.length, 3);
+});
+
+test("a capped credential refuses closed when no usage ledger can count its calls", async () => {
+ const capped = { reader: reader({ slug: "x-firehose", allowedPathPrefixes: ["/2/"], maxRequestsPerDay: 3 }) };
+ assert.equal((await brokerCredentialCall(base(capped))).status, 503);
+});
+
+test("concurrent calls cannot overshoot a daily cap", async () => {
+ const cap = captureFetch();
+ const usage = createCredentialUsageSink();
+ const capped = base({
+ fetchImpl: cap.fetch,
+ usage,
+ reader: reader({ slug: "x-firehose", allowedPathPrefixes: ["/2/"], maxRequestsPerDay: 3 }),
+ });
+ const results = await Promise.all(Array.from({ length: 8 }, () => brokerCredentialCall(capped)));
+ assert.equal(results.filter((r) => r.status === 200).length, 3);
+ assert.equal(cap.calls.length, 3);
+});
diff --git a/test/postgres-credential-usage-sink.test.ts b/test/postgres-credential-usage-sink.test.ts
index 2cc15534a..be25829ae 100644
--- a/test/postgres-credential-usage-sink.test.ts
+++ b/test/postgres-credential-usage-sink.test.ts
@@ -13,6 +13,7 @@ before(async () => {
const p = new pg.Pool({ connectionString: URL });
await p.query("DROP TABLE IF EXISTS qm_schema_migrations CASCADE");
await p.query("DROP TABLE IF EXISTS credential_usage CASCADE");
+ await p.query("DROP TABLE IF EXISTS credential_daily_calls CASCADE");
await p.end();
});
@@ -169,3 +170,13 @@ test("pg credential summaries do not wait for pending telemetry writes", { skip
]);
assert.equal(result[0]!.usageCount, 0);
});
+
+test("pg credential-usage sink: every process shares one daily cap per credential", { skip }, async () => {
+ const processes = [createPostgresCredentialUsageSink(URL!), createPostgresCredentialUsageSink(URL!)];
+ const admitted = await Promise.all(
+ Array.from({ length: 10 }, (_, i) => processes[i % 2]!.admitDailyCall("capped", 3)),
+ );
+ assert.equal(admitted.filter(Boolean).length, 3);
+ assert.equal(await createPostgresCredentialUsageSink(URL!).admitDailyCall("capped", 3), false);
+ assert.equal(await processes[0]!.admitDailyCall("capped", 4), true);
+});
diff --git a/test/scoped-event-sink-schema.test.ts b/test/scoped-event-sink-schema.test.ts
index b0fb3eb2e..4900bc2c5 100644
--- a/test/scoped-event-sink-schema.test.ts
+++ b/test/scoped-event-sink-schema.test.ts
@@ -94,6 +94,7 @@ test("every released scoped-event sink pins its 0001 checksum", () => {
[
"admin/scoped-events/credential_usage/0001",
"admin/scoped-events/credential_usage/0002",
+ "admin/scoped-events/credential_usage/0003",
"admin/scoped-events/egress_events/0001",
"admin/scoped-events/error_events/0001",
],