Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

Harden the spend export token and row order (#2211)

Eric Bakan1e9752552aea
diff --git a/cli/src/util.ts b/cli/src/util.ts
index 1ab08c8cf..5056d06b0 100644
--- a/cli/src/util.ts
+++ b/cli/src/util.ts
@@ -262,6 +262,7 @@ export function isMissingOrPlaceholder(value: string | undefined): boolean {
export function isInvalidSecret(name: string, value: string | undefined): boolean {
if (isMissingOrPlaceholder(value)) return true;
const candidate = value!.trim();
+ if (name === "DEPLOYMENT_CONTROL_SECRET" && candidate !== value) return true;
if (name === "ADMIN_GRANTS") {
const entries = candidate
.split(",")
diff --git a/docs/background-ownership.md b/docs/background-ownership.md
index 33b125eb4..9a5a27613 100644
--- a/docs/background-ownership.md
+++ b/docs/background-ownership.md
@@ -6,12 +6,12 @@ Production runs two core deployments (blue and green) against one PostgreSQL dat
Configure every core replica with:
-| Variable | Requirement |
-| --------------------------- | ------------------------------------------------------------------------------------------------------------------------- |
-| `BACKGROUND_DEPLOYMENT_ID` | An immutable identity shared by replicas of one deployment revision, distinct from every other deployment revision. |
-| `DEPLOYMENT_CONTROL_SECRET` | At least 32 characters, distinct from `CORE_SIGNING_SECRET`; distribute only to core and the trusted deployment operator. |
-| `CORE_SIGNING_SECRET` | The normal source request signing secret. |
-| `DATABASE_URL` | The shared PostgreSQL database. |
+| Variable | Requirement |
+| --------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `BACKGROUND_DEPLOYMENT_ID` | An immutable identity shared by replicas of one deployment revision, distinct from every other deployment revision. |
+| `DEPLOYMENT_CONTROL_SECRET` | At least 32 characters without surrounding whitespace, distinct from `CORE_SIGNING_SECRET`; distribute only to core and the trusted deployment operator. |
+| `CORE_SIGNING_SECRET` | The normal source request signing secret. |
+| `DATABASE_URL` | The shared PostgreSQL database. |
With `BACKGROUND_DEPLOYMENT_ID` set, `BACKGROUND_WORK_ENABLED` is ignored: the owner record alone decides. A fresh database has no owner, so no deployment runs background work until an operator sets one. Without `BACKGROUND_DEPLOYMENT_ID`, the process follows `BACKGROUND_WORK_ENABLED` as before and the legacy build-heartbeat supersession applies.
diff --git a/docs/deploy-directory.md b/docs/deploy-directory.md
index d6091d790..6dcf8b368 100644
--- a/docs/deploy-directory.md
+++ b/docs/deploy-directory.md
@@ -70,7 +70,7 @@ A chunk whose score is at or above its threshold resolves to Strict, and any Str
## Spend export
-`secretEnv.core.SPEND_EXPORT_TOKEN` (at least 32 characters, distinct from every catalogued core secret) turns on `GET /v1/spend/export?from=YYYY-MM-DD&to=YYYY-MM-DD` for an external spend or chargeback system. Requests send `Authorization: Bearer <token>`; the window is whole UTC days, half-open, and at most 93 days long. The response carries `scopeId`, the `window`, `asOf` when the report is served from saved daily totals, and `rows` at the Spend page's ledger grain — one per UTC day, scope, origin (`live`, `cron`, `background`) and model — each with `scopeId`, `kind`, `principalId` (people only, after identity links), `displayName`, `calls`, `costUsd` and the four token counts. `costUsd` is the same estimate the admin Spend page shows, not a provider bill. Without the secret the route answers 404, and every export is audited as `spend.export`. Portal does not forward the route, so callers use the origin that reaches core directly.
+`secretEnv.core.SPEND_EXPORT_TOKEN` (at least 32 characters, without surrounding whitespace, and distinct from every other environment value) turns on `GET /v1/spend/export?from=YYYY-MM-DD&to=YYYY-MM-DD` for an external spend or chargeback system. Requests send `Authorization: Bearer <token>`; the window is whole UTC days, half-open, and at most 93 days long. The response carries `scopeId`, the `window`, `asOf` when the report is served from saved daily totals, and `rows` at the Spend page's ledger grain — one per UTC day, scope, origin (`live`, `cron`, `background`) and model — each with `scopeId`, `kind`, `principalId` (people only, after identity links), `displayName`, `calls`, `costUsd` and the four token counts. `costUsd` is the same estimate the admin Spend page shows, not a provider bill. Without the secret the route answers 404, and every export is audited as `spend.export`. Portal does not forward the route, so callers use the origin that reaches core directly.
## Secrets
diff --git a/src/api/routes/admin/spend.ts b/src/api/routes/admin/spend.ts
index 57d95e5cb..6ccc23a6e 100644
--- a/src/api/routes/admin/spend.ts
+++ b/src/api/routes/admin/spend.ts
@@ -209,10 +209,16 @@ function entityOf(acc: EntityAccumulator, label: (scopeId: ScopeId) => string):
};
}
+function byCodePoint(a: string | null, b: string | null): number {
+ if (a === b) return 0;
+ if (a === null) return 1;
+ if (b === null) return -1;
+ return a < b ? -1 : 1;
+}
+
function byCostThenId(a: SpendEntity, b: SpendEntity): number {
if (a.costUsd !== b.costUsd) return b.costUsd - a.costUsd;
- if (a.scopeId === b.scopeId) return 0;
- return a.scopeId < b.scopeId ? -1 : 1;
+ return byCodePoint(a.scopeId, b.scopeId);
}
function byCostThenModel(
@@ -220,10 +226,7 @@ function byCostThenModel(
b: { model: string | null; costUsd: number },
): number {
if (a.costUsd !== b.costUsd) return b.costUsd - a.costUsd;
- if (a.model === b.model) return 0;
- if (a.model === null) return 1;
- if (b.model === null) return -1;
- return a.model < b.model ? -1 : 1;
+ return byCodePoint(a.model, b.model);
}
export function summarizeSpend(rows: readonly SpendRow[], opts: SpendSummaryOptions): SpendReport {
@@ -282,12 +285,7 @@ export function summarizeSpend(rows: readonly SpendRow[], opts: SpendSummaryOpti
calls: total.calls,
models: [...models].map(([model, costUsd]) => ({ model, costUsd })).sort(byCostThenModel),
people: [...people]
- .sort(([a], [b]) => {
- if (a === b) return 0;
- if (a === null) return 1;
- if (b === null) return -1;
- return a < b ? -1 : 1;
- })
+ .sort(([a], [b]) => byCodePoint(a, b))
.map(([principalId, costUsd]) => ({ principalId, costUsd })),
live: { costUsd: byOrigin.live.costUsd },
cron: { costUsd: byOrigin.cron.costUsd },
@@ -339,10 +337,10 @@ export function spendExportRows(rows: readonly SpendRow[], label: (scopeId: Scop
.map((out) => ({ ...out, displayName: displayNameOf(sources.get(out.scopeId) ?? [], label) }))
.sort(
(a, b) =>
- a.day.localeCompare(b.day) ||
- a.scopeId.localeCompare(b.scopeId) ||
+ byCodePoint(a.day, b.day) ||
+ byCodePoint(a.scopeId, b.scopeId) ||
ORIGIN_BUCKETS.indexOf(a.origin) - ORIGIN_BUCKETS.indexOf(b.origin) ||
- (a.model ?? "").localeCompare(b.model ?? ""),
+ byCodePoint(a.model ?? "", b.model ?? ""),
);
}
diff --git a/src/api/routes/background-work.ts b/src/api/routes/background-work.ts
index 3f1bb97f3..0ac6968f6 100644
--- a/src/api/routes/background-work.ts
+++ b/src/api/routes/background-work.ts
@@ -1,4 +1,4 @@
-import { isStrongSigningSecret } from "../../auth/source-auth.ts";
+import { isBearerSecret, isStrongSigningSecret } from "../../auth/source-auth.ts";
import { timingSafeEqual } from "node:crypto";
import { BackgroundOwnershipConflict, type BackgroundOwnership } from "../../runs/background-ownership.ts";
import { sendJson } from "../http.ts";
@@ -25,7 +25,14 @@ function status(ctx: ApiCtx, state: BackgroundOwnership): void {
export function requireDeploymentControl(ctx: ApiCtx): boolean {
const control = ctx.deps.backgroundOwnership;
const secret = ctx.deps.deploymentControlSecret;
- if (!control || !ctx.secret || !ctx.auth || !isStrongSigningSecret(secret) || secret === ctx.secret) {
+ if (
+ !control ||
+ !ctx.secret ||
+ !ctx.auth ||
+ !isStrongSigningSecret(secret) ||
+ !isBearerSecret(secret) ||
+ secret === ctx.secret
+ ) {
sendJson(ctx.res, 503, { error: "background_control_unavailable" });
return false;
}
diff --git a/src/auth/source-auth.ts b/src/auth/source-auth.ts
index 0774b848d..576d98c3c 100644
--- a/src/auth/source-auth.ts
+++ b/src/auth/source-auth.ts
@@ -9,6 +9,10 @@ export function isStrongSigningSecret(secret: string | undefined): secret is str
return (secret?.trim().length ?? 0) >= MIN_SIGNING_SECRET_LENGTH;
}
+export function isBearerSecret(secret: string | undefined): secret is string {
+ return Boolean(secret) && secret === secret?.trim();
+}
+
interface SourceAuthRequest {
signature: string;
timestamp: number;
diff --git a/src/config.ts b/src/config.ts
index a4ade2da8..cf6c0ece6 100644
--- a/src/config.ts
+++ b/src/config.ts
@@ -1,5 +1,5 @@
import type { ExternalSlackPolicies } from "./resolution/external-slack.ts";
-import { isStrongSigningSecret } from "./auth/source-auth.ts";
+import { isBearerSecret, isStrongSigningSecret } from "./auth/source-auth.ts";
import { parseSandboxCapabilityTtlMs } from "./auth/capability-token.ts";
import { parseScopeId } from "./types.ts";
import type { LegacySandboxScopeDefaults } from "./sandbox/sandbox-resource-upgrade.ts";
@@ -22,7 +22,7 @@ import { parseMemoryStrategyKind, type MemoryStrategyKind } from "./memory/strat
import { parseMemoryProviderConfig, type MemoryProviderConfig } from "./memory/provider-config.ts";
import { sanitizeBranding } from "./resolution/branding.ts";
import type { OrgBranding } from "./resolution/config-store.ts";
-import { CORE_SECRET_SPECS, validateCoreSecretEnv } from "./deployment/secret-schema.ts";
+import { validateCoreSecretEnv } from "./deployment/secret-schema.ts";
import { DEFAULT_CAPTURE_QUIET_MS } from "./memory/strategies/per-turn.ts";
import {
parseSecurityPosture,
@@ -1181,10 +1181,13 @@ function modelProviderEnvStrict(env: NodeJS.ProcessEnv): ModelProvider | undefin
}
export function loadConfig(env: NodeJS.ProcessEnv = process.env): Config {
- if (env.SPEND_EXPORT_TOKEN) {
- const reused = CORE_SECRET_SPECS.some((spec) => env[spec.name] === env.SPEND_EXPORT_TOKEN);
- if (!isStrongSigningSecret(env.SPEND_EXPORT_TOKEN) || reused)
- throw new Error("SPEND_EXPORT_TOKEN must be at least 32 characters and differ from every catalogued core secret");
+ const token = env.SPEND_EXPORT_TOKEN;
+ if (token) {
+ const reused = Object.entries(env).some(([name, value]) => name !== "SPEND_EXPORT_TOKEN" && value === token);
+ if (!isStrongSigningSecret(token) || !isBearerSecret(token) || reused)
+ throw new Error(
+ "SPEND_EXPORT_TOKEN must be at least 32 characters, have no surrounding whitespace and differ from every other environment value",
+ );
}
if (env.BACKGROUND_DEPLOYMENT_ID !== undefined) {
if (!env.BACKGROUND_DEPLOYMENT_ID.trim() || env.BACKGROUND_DEPLOYMENT_ID.length > 256)
diff --git a/src/deployment/secret-schema.ts b/src/deployment/secret-schema.ts
index 3c9880f8f..b2fdebd54 100644
--- a/src/deployment/secret-schema.ts
+++ b/src/deployment/secret-schema.ts
@@ -1,4 +1,4 @@
-import { isStrongSigningSecret } from "../auth/source-auth.ts";
+import { isBearerSecret, isStrongSigningSecret } from "../auth/source-auth.ts";
type SecretGate =
| "production"
@@ -104,6 +104,7 @@ export function validateCoreSecretEnv(env: NodeJS.ProcessEnv): string[] {
function isInvalidSecret(name: string, value: string | undefined): boolean {
const candidate = value?.trim();
if (!candidate || /^(replace-me|placeholder|changeme|todo)$/i.test(candidate)) return true;
+ if (name === "DEPLOYMENT_CONTROL_SECRET" && !isBearerSecret(value)) return true;
return (
(name === "CONNECTOR_SECRET_KEY" ||
name === "CORE_SIGNING_SECRET" ||
diff --git a/src/surfaces/slack-managed.ts b/src/surfaces/slack-managed.ts
index 8b69a1ff5..f2d1a3f1d 100644
--- a/src/surfaces/slack-managed.ts
+++ b/src/surfaces/slack-managed.ts
@@ -10,6 +10,7 @@ import {
isGatedEnvelope,
} from "../slack/deferred-ack.ts";
import { sendJson } from "../api/http.ts";
+import { isBearerSecret } from "../auth/source-auth.ts";
export function createManagedSlack(opts: {
serviceUrl: string;
@@ -20,7 +21,7 @@ export function createManagedSlack(opts: {
reconcile?: () => Promise<void>;
}) {
const serviceUrl = new URL(opts.serviceUrl);
- if (serviceUrl.protocol !== "https:" || serviceUrl.username || serviceUrl.password || !opts.token) {
+ if (serviceUrl.protocol !== "https:" || serviceUrl.username || serviceUrl.password || !isBearerSecret(opts.token)) {
throw new Error("Managed Slack requires an HTTPS service URL and credential");
}
let active: { app: BoltApp; installId: string; staging?: EnvelopeStaging } | undefined;
diff --git a/test/background-work-routes.test.ts b/test/background-work-routes.test.ts
index 8bf77897a..151e68df7 100644
--- a/test/background-work-routes.test.ts
+++ b/test/background-work-routes.test.ts
@@ -84,7 +84,7 @@ test("ownership controls require both source and distinct deployment credentials
} finally {
await srv.close();
}
- for (const secret of ["short", sourceSecret, "", " ".repeat(32)]) {
+ for (const secret of ["short", sourceSecret, "", " ".repeat(32), `${controlSecret}\n`]) {
const disabled = await fixture(secret);
try {
assert.equal((await disabled.request("GET")).status, 503);
diff --git a/test/config.test.ts b/test/config.test.ts
index 686e3caad..cda9d7724 100644
--- a/test/config.test.ts
+++ b/test/config.test.ts
@@ -10,7 +10,6 @@ import {
numEnv,
CONFIG_DEFAULTS,
} from "../src/config.ts";
-import { CORE_SECRET_SPECS } from "../src/deployment/secret-schema.ts";
const productionEnv = {
NODE_ENV: "production",
@@ -950,7 +949,7 @@ test("background ownership requires durable storage and an independent deploymen
assert.throws(() => loadConfig({ ...env, DEPLOYMENT_CONTROL_SECRET: " ".repeat(32) }), /DEPLOYMENT_CONTROL_SECRET/);
});
-test("the spend export token is optional, strong and never shared with another core secret", () => {
+test("the spend export token is optional, strong, trimmed and never shared with another environment value", () => {
const env = {
CORE_SIGNING_SECRET: "source-signing-secret-0123456789abcdef",
CAPABILITY_SECRET: "capability-secret-0123456789abcdef0123",
@@ -962,7 +961,13 @@ test("the spend export token is optional, strong and never shared with another c
assert.equal(loadConfig({ ...env, SPEND_EXPORT_TOKEN: "" }).spendExportToken, undefined);
assert.throws(() => loadConfig({ ...env, SPEND_EXPORT_TOKEN: "short" }), /SPEND_EXPORT_TOKEN/);
assert.throws(() => loadConfig({ ...env, SPEND_EXPORT_TOKEN: " ".repeat(40) }), /SPEND_EXPORT_TOKEN/);
- for (const { name } of CORE_SECRET_SPECS) {
+ assert.throws(() => loadConfig({ ...env, SPEND_EXPORT_TOKEN: `${env.SPEND_EXPORT_TOKEN}\n` }), /SPEND_EXPORT_TOKEN/);
+ for (const name of [
+ "CORE_SIGNING_SECRET",
+ "QM_SLACK_SERVICE_TOKEN",
+ "DEPLOY_APPS_SESSION_SECRET",
+ "SLACK_SIGNING_SECRET",
+ ]) {
assert.throws(
() => loadConfig({ ...env, [name]: env.SPEND_EXPORT_TOKEN }),
/SPEND_EXPORT_TOKEN/,
diff --git a/test/secret-schema-drift.test.ts b/test/secret-schema-drift.test.ts
index 2def94644..79bbb6f57 100644
--- a/test/secret-schema-drift.test.ts
+++ b/test/secret-schema-drift.test.ts
@@ -3,6 +3,7 @@ import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { FIRST_PARTY_SECRET_SPECS } from "../cli/src/secrets.ts";
import { MODEL_PROVIDERS, MODEL_PROVIDER_HARNESSES } from "../cli/src/config.ts";
+import { isInvalidSecret as cliRejectsSecret } from "../cli/src/util.ts";
import { CORE_SECRET_SPECS, validateCoreSecretEnv } from "../src/deployment/secret-schema.ts";
import { HARNESS_IDS, defaultModelForProvider } from "../src/model/pi-models.ts";
@@ -18,7 +19,7 @@ test("the standalone CLI and core agree on runtime-enforced core secret names",
test("background ownership requires strong control credentials only for configured deployments", () => {
assert.deepEqual(validateCoreSecretEnv({}), []);
- for (const secret of [undefined, "", " ".repeat(32), "short"]) {
+ for (const secret of [undefined, "", " ".repeat(32), "short", "separate-control-secret-value-0000000000\n"]) {
assert.deepEqual(
validateCoreSecretEnv({
BACKGROUND_DEPLOYMENT_ID: "core:release",
@@ -26,6 +27,7 @@ test("background ownership requires strong control credentials only for configur
}),
["DEPLOYMENT_CONTROL_SECRET"],
);
+ assert.equal(cliRejectsSecret("DEPLOYMENT_CONTROL_SECRET", secret), true, `the CLI preflight agrees on ${secret}`);
}
assert.deepEqual(
validateCoreSecretEnv({
@@ -34,6 +36,7 @@ test("background ownership requires strong control credentials only for configur
}),
[],
);
+ assert.equal(cliRejectsSecret("DEPLOYMENT_CONTROL_SECRET", "separate-control-secret-value-0000000000"), false);
});
test('deploy/core/Dockerfile pins NODE_ENV=production — the "production" secret gate is load-bearing on that line', () => {
diff --git a/test/slack-managed.test.ts b/test/slack-managed.test.ts
index e686ea9e1..6ac1fc9d6 100644
--- a/test/slack-managed.test.ts
+++ b/test/slack-managed.test.ts
@@ -228,3 +228,14 @@ test("explicit app pin still rejects another app at installation", async (t) =>
assert.equal((await request("installation", { ...installation, appId: "AOTHER" })).status, 400);
assert.equal(await store.get(), null);
});
+
+test("managed Slack refuses a service credential that a bearer header cannot carry", () => {
+ const store = createSlackInstallationStore(
+ "company",
+ createMemoryMap() as Parameters<typeof createSlackInstallationStore>[1],
+ "test-encryption-key",
+ );
+ for (const token of ["", "company-token\n", " company-token"]) {
+ assert.throws(() => createManagedSlack({ serviceUrl: "https://slack.example.com", token, store }), /credential/);
+ }
+});
diff --git a/test/spend-export.test.ts b/test/spend-export.test.ts
index 9fc6dcc16..d7760a29d 100644
--- a/test/spend-export.test.ts
+++ b/test/spend-export.test.ts
@@ -8,7 +8,7 @@ import { signRequest } from "../src/auth/source-auth.ts";
import { createMemorySessionStore } from "../src/sessions/memory-session-store.ts";
import type { SessionStore } from "../src/sessions/session-store.ts";
import { scopeId } from "../src/types.ts";
-import { buildApp } from "../src/wiring.ts";
+import { buildApp, serverDeps } from "../src/wiring.ts";
import { bill } from "./support/spend-usage.ts";
import { testConfig } from "./support/test-config.ts";
@@ -95,7 +95,7 @@ test("spend export: the token authorizes the export and nothing else", async ()
}
});
-test("spend export: rows keep the ledger grain with canonical people, origin buckets and the org scope", async () => {
+test("spend export: rows keep the ledger grain with canonical people, origin buckets and the org scope, in code-point order", async () => {
const s = fixture();
try {
const sessions = s.sessions!;
@@ -104,6 +104,7 @@ test("spend export: rows keep the ledger grain with canonical people, origin buc
await bill(sessions, "cron:nightly:fire:1", "dm", scopeId("personal", "alice"), { costUsd: 0.5 }, "gpt-6-astra");
await bill(sessions, "webhook:w1", "channel", scopeId("channel", "C1"), { costUsd: 4 }, "claude-opus-5");
await bill(sessions, "ch:C1:t1", "channel", scopeId("channel", "C1"), { costUsd: 3 }, "claude-opus-5");
+ await bill(sessions, "dm:U1:t1", "dm", scopeId("personal", "U1"), { costUsd: 1 }, "claude-opus-5");
const res = await s.get(`/v1/spend/export?${window}`);
assert.equal(res.status, 200);
const body: any = await res.json();
@@ -114,18 +115,19 @@ test("spend export: rows keep the ledger grain with canonical people, origin buc
[
[iso(today), "channel:C1", "channel", null, "live", "claude-opus-5", 1, 3],
[iso(today), "channel:C1", "channel", null, "background", "claude-opus-5", 1, 4],
+ [iso(today), "personal:U1", "person", "U1", "live", "claude-opus-5", 1, 1],
[iso(today), "personal:alice", "person", "alice", "live", "claude-opus-5", 2, 3],
[iso(today), "personal:alice", "person", "alice", "cron", "gpt-6-astra", 1, 0.5],
],
);
assert.deepEqual(
- [body.rows[2].input, body.rows[2].output, body.rows[2].cacheRead, body.rows[2].cacheWrite],
+ [body.rows[3].input, body.rows[3].output, body.rows[3].cacheRead, body.rows[3].cacheWrite],
[200, 40, 800, 80],
);
const audited = (await s.built.auditLog.events()).filter((e) => e.action === "spend.export");
assert.equal(audited.length, 1);
assert.equal(audited[0]!.principalId, "spend-export");
- assert.equal(audited[0]!.detail, `${iso(today - DAY)}..${iso(today + DAY)} rows=4`);
+ assert.equal(audited[0]!.detail, `${iso(today - DAY)}..${iso(today + DAY)} rows=5`);
} finally {
await s.close();
}
@@ -174,3 +176,9 @@ test("spend export: an unavailable spend store is an error, not an empty export"
await s.close();
}
});
+
+test("spend export: core receives the configured token", () => {
+ const config = testConfig({ spendExportToken: exportToken });
+ assert.equal(serverDeps(config, buildApp(config)).spendExportToken, exportToken);
+ assert.equal(serverDeps(testConfig(), buildApp(testConfig())).spendExportToken, undefined);
+});