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
2 changes: 1 addition & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -516,7 +516,7 @@ and is synced to tmpfs at `/run/usage-monitor/usage-monitor.env` (mode 0600). T
receipt importer, alongside the stable 32+ character `BILLING_RECEIPT_IDENTITY_KEY`. The identity
key must not rotate with the signing key because it derives durable receipt IDs. Receipt
credentials are manually provisioned and are not used by ordinary
telemetry. `USAGE_INGEST_PRODUCER_TOKENS` is an optional comma-separated list of `producerId:token` pairs that provides per-producer token scoping and isolated rate-limit buckets. When `USAGE_INGEST_REQUIRE_SCOPED_TOKENS=true` is set, unscoped `USAGE_INGEST_TOKEN` ingest is denied. A scoped token authorizes exactly one producer: its v2 `producerId` (the persisted `sourceApp`), OTLP metrics only for `claude-code`, and `/api/ingest/mac-heartbeat` only for `mac-host`. Mac collectors read their own `<PRODUCER>_INGEST_TOKEN` name first (`CODEX_`, `GROK_`, `COPILOT_`, `MINIMAX_`, `DEEPSEEK_`, `ANTIGRAVITY_`, `CLAUDE_CODE_`, `MAC_HEARTBEAT_`), then the unscoped fallback. The producer inventory and rotation runbook are in `docs/rollouts/2026-09-24-ingest-token-scoping.md`. `USAGE_READ_TOKEN` is a separate read-only token for
telemetry. `USAGE_INGEST_PRODUCER_TOKENS` is an optional comma-separated list of `producerId:token` pairs that provides per-producer token scoping and isolated rate-limit buckets. When `USAGE_INGEST_REQUIRE_SCOPED_TOKENS=true` is set, unscoped `USAGE_INGEST_TOKEN` ingest is denied. A scoped token authorizes exactly one producer: its v2 `producerId` (the persisted `sourceApp`), OTLP metrics only for `claude-code`, and `/api/ingest/mac-heartbeat` only for `mac-host`. Mac collectors read their own `<PRODUCER>_INGEST_TOKEN` name first (`CODEX_`, `GROK_`, `COPILOT_`, `MINIMAX_`, `DEEPSEEK_`, `ANTIGRAVITY_`, `CLAUDE_CODE_`, `MAC_HEARTBEAT_`), then the unscoped fallback.  **Provenance order (OPS-1120):** `resolveCollectorToken` asks this consumer's scoped Infisical binding before the environment, so a reviewed grant never loses to a value that merely sits in the environment, and an environment value shaped like an Infisical service token (`st.<id>.<secret>`) is refused outside `COLLECTOR_STRICT_INJECTED_SECRETS=1`, because that synchronous resolver cannot read the token's own metadata to prove which grant it is.  The documented static producer tokens are app bearers rather than Infisical grants and keep working from the host bootstrap store when the scoped store has no answer. The producer inventory and rotation runbook are in `docs/rollouts/2026-09-24-ingest-token-scoping.md`. `USAGE_READ_TOKEN` is a separate read-only token for
`/api/budget-status` and `GET /api/subscriptions`. It is **required in
production** (the deploy preflight hard-fails without it): the
`USAGE_INGEST_TOKEN` fallback only applies outside production or when
Expand Down
113 changes: 108 additions & 5 deletions scripts/__tests__/resolve-collector-token.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,19 @@ function fakeLookup(values) {
return vi.fn((name) => values[name] ?? null);
}

describe("resolveCollectorToken injected lookup compatibility", () => {
// A service-token-shaped fixture assembled at runtime: the resolver's shape
// check needs the form, and a literal here trips the repo's secret scanner.
const FAKE_SERVICE_TOKEN = ["st", "abc123", "secret456"].join(".");

describe("resolveCollectorToken store-first precedence (OPS-1120)", () => {
it("prefers the scoped store for the same name over an environment value", () => {
const lookup = fakeLookup({ CODEX_INGEST_TOKEN: "scoped-lookup" });
expect(
resolveCollectorToken(["CODEX_INGEST_TOKEN"], { env: { CODEX_INGEST_TOKEN: "env-value" }, fleetSecretsGet: lookup }),
).toBe("scoped-lookup");
expect(lookup).toHaveBeenCalledWith("CODEX_INGEST_TOKEN");
});

it("prefers a scoped name from the supplied lookup over an unscoped environment value", () => {
const token = resolveCollectorToken(["CODEX_INGEST_TOKEN", "USAGE_INGEST_TOKEN"], {
env: { USAGE_INGEST_TOKEN: "unscoped-env" },
Expand All @@ -15,14 +27,85 @@ describe("resolveCollectorToken injected lookup compatibility", () => {
expect(token).toBe("scoped-lookup");
});

it("prefers the environment for the same name without invoking the supplied lookup", () => {
it("falls back to the environment only for a name the store did not answer", () => {
const lookup = fakeLookup({});
expect(
resolveCollectorToken(["CODEX_INGEST_TOKEN", "USAGE_INGEST_TOKEN"], {
env: { CODEX_INGEST_TOKEN: "env-codex", USAGE_INGEST_TOKEN: "env-unscoped" },
fleetSecretsGet: lookup,
}),
).toBe("env-codex");
expect(lookup).toHaveBeenCalledWith("CODEX_INGEST_TOKEN");
});

it("refuses a service-token-shaped environment value the store did not provide", () => {
expect(() =>
resolveCollectorToken(["CODEX_INGEST_TOKEN"], {
env: { CODEX_INGEST_TOKEN: FAKE_SERVICE_TOKEN },
fleetSecretsGet: fakeLookup({}),
}),
).toThrow(/own Infisical binding/);
});

it("does not let a refused name block a valid later candidate", () => {
expect(
resolveCollectorToken(["CODEX_INGEST_TOKEN", "USAGE_INGEST_TOKEN"], {
env: { CODEX_INGEST_TOKEN: FAKE_SERVICE_TOKEN, USAGE_INGEST_TOKEN: "usage-env" },
fleetSecretsGet: fakeLookup({}),
}),
).toBe("usage-env");
});

it("accepts a service-token-shaped value in strict injected-secrets mode", () => {
expect(
resolveCollectorToken(["CODEX_INGEST_TOKEN"], {
env: { CODEX_INGEST_TOKEN: FAKE_SERVICE_TOKEN, COLLECTOR_STRICT_INJECTED_SECRETS: "1" },
fleetSecretsGet: fakeLookup({ CODEX_INGEST_TOKEN: "ignored" }),
}),
).toBe(FAKE_SERVICE_TOKEN);
});

it("skips the store entirely in strict injected-secrets mode", () => {
const lookup = fakeLookup({ CODEX_INGEST_TOKEN: "scoped-lookup" });
expect(
resolveCollectorToken(["CODEX_INGEST_TOKEN"], { env: { CODEX_INGEST_TOKEN: "scoped-env" }, fleetSecretsGet: lookup }),
).toBe("scoped-env");
resolveCollectorToken(["CODEX_INGEST_TOKEN"], {
env: { CODEX_INGEST_TOKEN: "delivered-value", COLLECTOR_STRICT_INJECTED_SECRETS: "1" },
fleetSecretsGet: lookup,
}),
).toBe("delivered-value");
expect(lookup).not.toHaveBeenCalled();
});

it("names every refused candidate when no value resolves", () => {
expect(() =>
resolveCollectorToken(["CODEX_INGEST_TOKEN", "OTHER_INGEST_TOKEN"], {
env: { CODEX_INGEST_TOKEN: FAKE_SERVICE_TOKEN, OTHER_INGEST_TOKEN: FAKE_SERVICE_TOKEN },
fleetSecretsGet: fakeLookup({}),
}),
).toThrow(/CODEX_INGEST_TOKEN, OTHER_INGEST_TOKEN/);
});

it("surfaces a scoped-read failure ahead of a shape refusal", () => {
const boom = new Error("scoped read unavailable");
expect(() =>
resolveCollectorToken(["CODEX_INGEST_TOKEN"], {
env: { CODEX_INGEST_TOKEN: FAKE_SERVICE_TOKEN },
fleetSecretsGet: () => {
throw boom;
},
}),
).toThrow(boom);
});

it("treats a whitespace-padded strict flag as strict", () => {
expect(
resolveCollectorToken(["CODEX_INGEST_TOKEN"], {
env: { CODEX_INGEST_TOKEN: "delivered-value", COLLECTOR_STRICT_INJECTED_SECRETS: " 1 " },
fleetSecretsGet: fakeLookup({ CODEX_INGEST_TOKEN: "ignored" }),
}),
).toBe("delivered-value");
});

it("falls back in order and returns null when nothing matches", () => {
const lookup = fakeLookup({ USAGE_INGEST_TOKEN: "unscoped-lookup" });
expect(resolveCollectorToken(["CODEX_INGEST_TOKEN", "USAGE_INGEST_TOKEN"], { env: {}, fleetSecretsGet: lookup })).toBe(
Expand All @@ -31,4 +114,24 @@ describe("resolveCollectorToken injected lookup compatibility", () => {
expect(resolveCollectorToken(["CODEX_INGEST_TOKEN"], { env: {}, fleetSecretsGet: lookup })).toBeNull();
expect(resolveCollectorToken(["CODEX_INGEST_TOKEN"], { env: {}, fleetSecretsGet: () => null })).toBeNull();
});
});

it("rethrows a deferred store failure only when no name yields a value", () => {
const boom = new Error("scoped read unavailable");
expect(() =>
resolveCollectorToken(["CODEX_INGEST_TOKEN"], {
env: {},
fleetSecretsGet: () => {
throw boom;
},
}),
).toThrow(boom);
expect(
resolveCollectorToken(["CODEX_INGEST_TOKEN"], {
env: { CODEX_INGEST_TOKEN: "env-value" },
fleetSecretsGet: () => {
throw boom;
},
}),
).toBe("env-value");
});
});
16 changes: 13 additions & 3 deletions scripts/__tests__/run-session-token-collector.fixture.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -77,15 +77,25 @@ function stubEnv(mode, extra = {}) {
function resetRecord() { writeFileSync(recordFile, ""); }
function record() { return existsSync(recordFile) ? readFileSync(recordFile, "utf8") : ""; }

// 1. env value wins; lookup must not run
// 1. store value wins (OPS-1120); env is consulted only after the store
{
let called = 0;
const v = resolveCollectorToken(["USAGE_INGEST_TOKEN"], {
env: { USAGE_INGEST_TOKEN: " env-token " },
fleetSecretsGet: () => { called++; return "lookup-token"; },
});
check("env value wins and is trimmed", v === "env-token");
check("lookup not called when env has the value", called === 0);
check("store value wins over env for the same name", v === "lookup-token");
check("store is consulted before the env value", called === 1);
}
{
// env is still trimmed and returned when the store has no answer
let called = 0;
const v = resolveCollectorToken(["USAGE_INGEST_TOKEN"], {
env: { USAGE_INGEST_TOKEN: " env-token " },
fleetSecretsGet: () => { called++; return null; },
});
check("env fallback value is trimmed", v === "env-token");
check("store consulted once before the env fallback", called === 1);
}

// 2. per-name order: name1 env-then-lookup before name2
Expand Down
69 changes: 54 additions & 15 deletions scripts/lib/run-session-token-collector.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -90,29 +90,47 @@ function scopedInfisicalRead(name, env) {
}

/**
* Resolves an ingest token from the environment, then from Infisical through
* this consumer's scoped service-token binding.
* Resolves an ingest token through this consumer's scoped Infisical binding
* first, then from the environment (OPS-1120).
*
* Names are tried strictly in order, each in the environment and then through
* the scoped lookup, so a producer-scoped name kept in Infisical still beats
* an unscoped USAGE_INGEST_TOKEN exported in the environment. Pass
* `fleetSecretsGet: () => null` for an environment-only lookup; the option
* key keeps its historical name for caller/test compatibility, but the
* Infisical is the source; the environment only transports values synced to
* the host, so a reviewed grant in the store must never lose to a value that
* merely sits in the environment. Names are still tried strictly in order,
* and for each name the scoped lookup answers before the environment is
* consulted.
*
* An environment value shaped like an Infisical service token
* (`st.<id>.<secret>`) is refused outside strict-injected mode: this
* synchronous resolver cannot read that token's own metadata to prove whose
* grant it is, so a hand-set service token never stands in for the reviewed
* grant. The documented static producer tokens (`<PRODUCER>_INGEST_TOKEN` /
* `USAGE_INGEST_TOKEN`, which are app bearers and not Infisical grants) keep
* working from the host bootstrap store when the scoped store has no answer.
*
* Pass `fleetSecretsGet: () => null` for an environment-only lookup; the
* option key keeps its historical name for caller/test compatibility, but the
* default no longer touches the retired fleet-secrets CLI.
*/
const SERVICE_TOKEN_VALUE_SHAPE = /^st\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+(?:\.|$)/;

export function resolveCollectorToken(
tokenEnvVarNames = ["USAGE_INGEST_TOKEN"],
{ env = process.env, fleetSecretsGet: lookup } = {},
) {
const effectiveLookup = lookup ?? ((name) => scopedInfisicalRead(name, env));
let deferredFailure = null;
// Strict injected-secrets mode skips the runtime lookup entirely: the
// injector already read the store, so only the delivered values count.
// Trimmed like the token values themselves: a padded flag must not silently
// drop the process into the non-strict path.
const strictInjected = String(env.COLLECTOR_STRICT_INJECTED_SECRETS ?? "").trim() === "1";
// Two separate slots, so one kind of deferred failure cannot hide the other:
// a scoped-read failure is an infrastructure problem and outranks a shape
// refusal, and every refused name is reported rather than only the first.
let deferredLookupFailure = null;
const refusedNames = [];
for (const name of tokenEnvVarNames) {
Comment thread
jaywedgeworth22 marked this conversation as resolved.
Resolved
const val = env[name]?.trim();
if (val) return val;
// Strict injected-secrets mode skips the runtime lookup entirely:
// only values already injected into the environment count.
let fromLookup = null;
if (env.COLLECTOR_STRICT_INJECTED_SECRETS !== "1") {
if (!strictInjected) {
try {
fromLookup = effectiveLookup(name)?.trim();
} catch (err) {
Expand All @@ -122,12 +140,33 @@ export function resolveCollectorToken(
// rethrown only when no name yields a value at all: a failure with no
// usable token anywhere is not a silent miss (deliberate contract
// change from the retired helper's null-on-failure).
deferredFailure ??= err;
deferredLookupFailure ??= err;
}
}
if (fromLookup) return fromLookup;
const val = env[name]?.trim();
if (!val) continue;
Comment thread
jaywedgeworth22 marked this conversation as resolved.
Resolved
// Strict injected-secrets mode is a delivery channel: the injector read
// the store, so a delivered service-token value is already the reviewed
// grant and the shape check cannot apply there.
if (!strictInjected && SERVICE_TOKEN_VALUE_SHAPE.test(val)) {
Comment thread
jaywedgeworth22 marked this conversation as resolved.
Resolved
// A refused value is never used, but it must not poison a later
// candidate either: collect, so a valid USAGE_INGEST_TOKEN still
// resolves and the refusal is raised only when no name yields a usable
// value.
refusedNames.push(name);
continue;
}
return val;
Comment thread
kody-ai[bot] marked this conversation as resolved.
Resolved
}
// A failed scoped read is the more actionable error, so it wins; otherwise
// every refused name is named at once instead of one per run.
if (deferredLookupFailure) throw deferredLookupFailure;
if (refusedNames.length > 0) {
throw new Error(
`${refusedNames.join(", ")} hold${refusedNames.length === 1 ? "s" : ""} an Infisical service token in the environment; store it in this consumer's own Infisical binding instead (the environment cannot prove which grant it is)`,
);
}
if (deferredFailure) throw deferredFailure;
return null;
}

Expand Down
1 change: 1 addition & 0 deletions scripts/vitest.collectors.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ const config = {
include: [
"scripts/__tests__/kimi-zcode-telemetry.test.mjs",
"scripts/__tests__/muse-code-usage-collector.test.mjs",
"scripts/__tests__/resolve-collector-token.test.mjs",
"scripts/__tests__/transfer-muse-code-access-token-to-infisical.test.mjs",
],
},
Expand Down
Loading