diff --git a/INFISICAL.md b/INFISICAL.md
index c1adfbaa2..f32e1959d 100644
--- a/INFISICAL.md
+++ b/INFISICAL.md
@@ -29,7 +29,7 @@ Machine-identity connections verify read access before saving. Declared machin
An unreadable connection is reported separately so healthy project uses remain manageable. Replace it by entering all credentials, or disable it to suppress its environment fallback; blank fields cannot reuse credentials from unreadable saved data. Replacements retain the original saved-row revision so a concurrent edit or disable wins. Project token counting tolerates malformed routes when the project and token inventory remain readable, but an unknown project or encrypted inventory still blocks service-token saves until that source is replaced or disabled; machine-identity saves add no service tokens.
-The value-blind secrets helper accepts only `INFISICAL_UM_WRITE_TOKEN` with verified service-token write metadata for token-based writes; generic `INFISICAL_TOKEN` remains a read alias. Opaque bearer tokens cannot attest write permissions. The helper also retains its explicit UM machine-identity login path, whose real operations are authorized by Infisical without claiming a service-token permission check.
+The value-blind secrets helper requires `INFISICAL_UM_READ_TOKEN` for reads or `INFISICAL_UM_WRITE_TOKEN` for writes, verified against the exact project/prod/folder permission; `INFISICAL_TOKEN` remains a service-token read alias. Opaque bearers and machine-identity login are refused. Copy operations read only explicitly named Infisical-synced environment values; platform sync uses its fixed map and never copies retired machine credentials. The manual Local keys bundle reads only its provider catalog's synced environment names, with an explicit fixture-file option retained for tests. Actual token custody, finite expiry and producer delivery remain separately qualified.
Legacy raw responses can omit project/environment/folder fields. Only a token whose own verified metadata contains one exact folder makes those omissions unambiguous; any returned contradictory identity is rejected. A multi-folder token must receive the exact identity fields in each response, or the operation fails closed.
diff --git a/docs/rollouts/2026-11-08-collector-keychain-tokens.md b/docs/rollouts/2026-11-08-collector-keychain-tokens.md
index 8998f3b97..411eb62ac 100644
--- a/docs/rollouts/2026-11-08-collector-keychain-tokens.md
+++ b/docs/rollouts/2026-11-08-collector-keychain-tokens.md
@@ -1,6 +1,6 @@
# Per-Consumer Collector Tokens In The Mac Login Keychain
-Each collector that reads a provider secret reads it with its own scoped Infisical service token, and that token now lives in the owner's login keychain instead of a plaintext file on disk. The nine per-consumer binding files that say so are in this repository now, tracked, with the read implemented once and the per-consumer differences held as data.
+Eight collector bindings read through their own scoped Infisical service tokens in the owner's login keychain instead of plaintext files. The ninth, Codex, accepts only Infisical-synced values injected for its own consumer. The nine binding files are tracked, with shared resolution and the per-consumer differences held in thin bindings.
## Why The Files Were Missing
@@ -26,15 +26,15 @@ The two Infisical responses are external, so neither is read field by field befo
The resolver honours COLLECTOR_STRICT_INJECTED_SECRETS=1 as environment-only, the same way the shared resolver does, so a host that asked for environment-only resolution never reaches the login keychain and never makes an Infisical request. The lookup is built once per resolver and shared, so the keychain read, the metadata request and the per-folder fetches happen once per run rather than once per name the collector asks for.
-`scripts/lib/automation-collector-token.mjs` holds the Codex collector's existing mechanism, unchanged. The Codex collector reads through the System keychain automation identity, which the owner permitted, and that identity is shared rather than a per-consumer grant, so it is neither one of the scoped tokens nor something the owner's login keychain should hold.
+`scripts/lib/codex-run-session-token-collector.mjs` forces the shared resolver's injected-secrets mode on every call. It accepts `CODEX_INGEST_TOKEN` before `USAGE_INGEST_TOKEN` from its supplied environment and returns no token when both are absent. A caller cannot enable runtime lookups by supplying a lookup function or disabling strict mode. The former System keychain automation reader is removed; Codex performs no keychain read, universal-auth login, CLI lookup or default-folder discovery.
-The nine per-consumer files under `scripts/lib/` are now thin. Each one re-exports the shared library, states its own binding, and overrides the resolver with the scoped one. The binding is data: the token's account name, the human label, the pinned grant id, the project and the folders. All eight scoped consumers share one project, the root folder and the global API keys folder, and read permission only. Because the binding is data and the read is one implementation, a change to the read can no longer drift between consumers, which is exactly what the nine forks had been doing.
+The nine per-consumer files under `scripts/lib/` are thin and re-export the shared library. Eight override the resolver with the scoped reader; their binding data is the token's account name, the human label, the pinned grant id, the project and the folders. All eight scoped consumers share one project, the root folder and the global API keys folder, and read permission only. Codex overrides the shared resolver only to require injected values. The shared implementations keep reads from drifting between consumers.
## The Entry Points
Each of the nine collectors now imports its own binding instead of the shared library, and awaits the resolver. The eight other collectors, which have no per-consumer grant, keep the shared library and are unchanged.
-The Codex collector's resolver stays synchronous, because the automation identity read is synchronous and has always been. Awaiting it changes nothing.
+The Codex collector's resolver stays synchronous and preserves the shared library's public exports and option shape. It copies the supplied environment before forcing injected mode, leaving caller options and environment unchanged. Awaiting its result remains supported.
## The Install Order
@@ -42,10 +42,12 @@ The plaintext files are deleted only after the merged collectors are deployed an
## The Test
-`scripts/collector-keychain.node-test.mjs` runs under Node's own test runner as part of the collector runtime gate. Every keychain read goes through an injected stand-in for `security`, so the test never touches the real keychain. It covers the item lookup and its arguments, the three refusals and how they are told apart, the refusal to read an invalid account name, the grant id check, the malformed-token refusal, the environment taking precedence over the keychain, the metadata binding refusal, the refusal of a malformed Infisical body, the strict mode that reaches neither the keychain nor Infisical, the shared lookup that reads the keychain once, and the rule that a failed read never carries the value. It also pins each of the nine bindings to its own account, label, grant id, project and folders, checks that each entry point imports its own binding and awaits the resolver, checks that the other collectors still import the shared library, and checks that no collector reads a plaintext token file any more.
+`scripts/collector-keychain.node-test.mjs` runs under Node's own test runner as part of the collector runtime gate. Every keychain read goes through an injected stand-in for `security`, so the test never touches the real keychain. It covers the item lookup and its arguments, the three refusals and how they are told apart, the refusal to read an invalid account name, the grant id check, the malformed-token refusal, the environment taking precedence over the keychain, the metadata binding refusal, the refusal of a malformed Infisical body, the strict mode that reaches neither the keychain nor Infisical, the shared lookup that reads the keychain once, and the rule that a failed read never carries the value. It pins the eight scoped bindings to their own accounts, labels, grant ids, project and folders. Codex fixtures exercise the actual wrapper and shared resolver in bounded isolated child processes, guard commands with inert authentication traps, and reject provider calls. They verify injected name priority, changed values between calls, absent and partial bootstrap, immutable caller options and the inability to bypass injected mode. The suite also checks each entry point's binding import and awaited resolver, the other collectors' shared imports, and the absence of plaintext token readers.
## What Is Not Covered Here
+The Codex source change does not qualify an actual grant or installed injector. Its own service-token custody, exact project/prod/folder/read metadata, finite expiry, producer injection and installed collector acceptance remain separate gates. No account, grant id or folder is inferred, and the generic CLI resolver's compatibility lookups do not establish that qualification.
+
The ninth plaintext file on the Mac, `fleet-zulip-client-read`, is not a collector token and has no consumer that a search of the Mac's applications, launch agents, secrets directory and configuration found. It is moved to the keychain on its own footing, not by this change.
The nine collector grants have no row in the Fleet-OPS registry. The registry names each service token and where its value lives, and a reader holding the registry row is how a keychain item is found, so the rows belong with this change and are filed separately.
diff --git a/package.json b/package.json
index cbdeea9a1..50b631a76 100644
--- a/package.json
+++ b/package.json
@@ -65,7 +65,7 @@
"test:apple-projects": "bash scripts/verify-apple-projects.sh",
"test:antigravity-collector": "node scripts/test-antigravity-collector.mjs",
"test:session-token-collectors": "node scripts/test-session-token-collectors.mjs",
- "test:collector-runtime": "node scripts/test-local-collector-runtime.mjs && node --test scripts/__tests__/opencode-profiles.node-test.mjs scripts/sentry-partial-ack.node-test.mjs scripts/idle-collector-sentry.node-test.mjs scripts/collector-keychain.node-test.mjs && node scripts/__tests__/run-session-token-collector.fixture.mjs && node scripts/__tests__/retirement-sentry.fixture.mjs && vitest run --config scripts/vitest.collectors.config.mjs",
+ "test:collector-runtime": "python3 -m unittest scripts.test_ops_synced_credentials && node scripts/test-local-collector-runtime.mjs && node --test scripts/__tests__/opencode-profiles.node-test.mjs scripts/sentry-partial-ack.node-test.mjs scripts/idle-collector-sentry.node-test.mjs scripts/collector-keychain.node-test.mjs && node scripts/__tests__/run-session-token-collector.fixture.mjs && node scripts/__tests__/retirement-sentry.fixture.mjs && vitest run --config scripts/vitest.collectors.config.mjs",
"test:cf-token-map": "bash scripts/test-cf-token-map.sh",
"test:replica-status-probe": "bash scripts/test-replica-status-probe.sh",
"test:quota-wrapper": "bash scripts/test-subscription-quota-wrapper.sh",
diff --git a/scripts/__tests__/resolve-collector-token.test.mjs b/scripts/__tests__/resolve-collector-token.test.mjs
index 28985977f..8b6b1ea02 100644
--- a/scripts/__tests__/resolve-collector-token.test.mjs
+++ b/scripts/__tests__/resolve-collector-token.test.mjs
@@ -1,23 +1,22 @@
import { describe, expect, it, vi } from "vitest";
-import { fleetSecretsGet, fleetSecretsGetAsync, fleetSecretsNames, resetFleetSecretsCache } from "../lib/fleet-secrets.mjs";
import { resolveCollectorToken } from "../lib/run-session-token-collector.mjs";
-function fakeFleet(values) {
+function fakeLookup(values) {
return vi.fn((name) => values[name] ?? null);
}
-describe("resolveCollectorToken", () => {
- it("prefers a scoped name from fleet-secrets over an unscoped name in the environment", () => {
+describe("resolveCollectorToken injected lookup compatibility", () => {
+ 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" },
- fleetSecretsGet: fakeFleet({ CODEX_INGEST_TOKEN: "scoped-fleet", USAGE_INGEST_TOKEN: "unscoped-fleet" }),
+ fleetSecretsGet: fakeLookup({ CODEX_INGEST_TOKEN: "scoped-lookup", USAGE_INGEST_TOKEN: "unscoped-lookup" }),
});
- expect(token).toBe("scoped-fleet");
+ expect(token).toBe("scoped-lookup");
});
- it("prefers the environment for the same name and never calls fleet-secrets", () => {
- const lookup = fakeFleet({ CODEX_INGEST_TOKEN: "scoped-fleet" });
+ it("prefers the environment for the same name without invoking the supplied lookup", () => {
+ const lookup = fakeLookup({ CODEX_INGEST_TOKEN: "scoped-lookup" });
expect(
resolveCollectorToken(["CODEX_INGEST_TOKEN"], { env: { CODEX_INGEST_TOKEN: "scoped-env" }, fleetSecretsGet: lookup }),
).toBe("scoped-env");
@@ -25,120 +24,11 @@ describe("resolveCollectorToken", () => {
});
it("falls back in order and returns null when nothing matches", () => {
- const lookup = fakeFleet({ USAGE_INGEST_TOKEN: "unscoped-fleet" });
+ const lookup = fakeLookup({ USAGE_INGEST_TOKEN: "unscoped-lookup" });
expect(resolveCollectorToken(["CODEX_INGEST_TOKEN", "USAGE_INGEST_TOKEN"], { env: {}, fleetSecretsGet: lookup })).toBe(
- "unscoped-fleet",
+ "unscoped-lookup",
);
expect(resolveCollectorToken(["CODEX_INGEST_TOKEN"], { env: {}, fleetSecretsGet: lookup })).toBeNull();
expect(resolveCollectorToken(["CODEX_INGEST_TOKEN"], { env: {}, fleetSecretsGet: () => null })).toBeNull();
});
});
-
-describe("fleetSecretsGet", () => {
- const options = (exec) => ({ exec, binary: "/fake/fleet-secrets", useCache: false });
-
- it("returns the trimmed stdout of the root lookup", () => {
- const exec = vi.fn(() => "value-from-root\n");
- expect(fleetSecretsGet("USAGE_INGEST_TOKEN", options(exec))).toBe("value-from-root");
- expect(exec).toHaveBeenCalledTimes(1);
- expect(exec.mock.calls[0][0]).toBe("/fake/fleet-secrets");
- expect(exec.mock.calls[0][1]).toEqual(["get", "USAGE_INGEST_TOKEN", "--path", "/"]);
- });
-
- it("retries /global-api-keys when the key is absent at the root", () => {
- const exec = vi.fn((_bin, args) => {
- if (args.at(-1) === "/") throw Object.assign(new Error("absent"), { status: 3 });
- return "value-from-folder";
- });
- expect(fleetSecretsGet("USAGE_INGEST_TOKEN", options(exec))).toBe("value-from-folder");
- expect(exec.mock.calls.map((call) => call[1].at(-1))).toEqual(["/", "/global-api-keys"]);
- });
-
- it("returns null when the binary is missing or every lookup fails", () => {
- const exec = vi.fn(() => {
- throw Object.assign(new Error("spawn ENOENT"), { code: "ENOENT" });
- });
- expect(fleetSecretsGet("USAGE_INGEST_TOKEN", options(exec))).toBeNull();
- });
-
- it("refuses a name that is not a plain env var name", () => {
- const exec = vi.fn(() => "x");
- expect(fleetSecretsGet("--path", options(exec))).toBeNull();
- expect(exec).not.toHaveBeenCalled();
- });
-
- it("caches per process", () => {
- resetFleetSecretsCache();
- const exec = vi.fn(() => "cached-value");
- const opts = { exec, binary: "/fake/fleet-secrets" };
- expect(fleetSecretsGet("CACHE_TEST_NAME", opts)).toBe("cached-value");
- expect(fleetSecretsGet("CACHE_TEST_NAME", opts)).toBe("cached-value");
- expect(exec).toHaveBeenCalledTimes(1);
- resetFleetSecretsCache();
- });
-
- it("still returns null by default when every lookup fails transiently", () => {
- const exec = vi.fn(() => {
- throw Object.assign(new Error("fetch failed"), { status: 4 });
- });
- expect(fleetSecretsGet("USAGE_INGEST_TOKEN", options(exec))).toBeNull();
- });
-
- it("throws with a cause in strict mode instead of reporting a failure as absent", () => {
- const failure = Object.assign(new Error("fetch failed"), { status: 4 });
- const exec = vi.fn(() => {
- throw failure;
- });
- let error = null;
- try {
- fleetSecretsGet("USAGE_INGEST_TOKEN", { ...options(exec), strict: true });
- } catch (caught) {
- error = caught;
- }
- expect(error).not.toBeNull();
- expect(error.message).toContain("USAGE_INGEST_TOKEN");
- expect(error.message).not.toContain("secret-value");
- expect(error.secretName).toBe("USAGE_INGEST_TOKEN");
- expect(error.cause).toBe(failure);
- });
-
- it("strict mode still returns null for an absent key", () => {
- const exec = vi.fn(() => {
- throw Object.assign(new Error("absent"), { status: 3 });
- });
- expect(fleetSecretsGet("USAGE_INGEST_TOKEN", { ...options(exec), strict: true })).toBeNull();
- });
-
- it("the async twin throws with a cause in strict mode on a transient failure", async () => {
- const failure = Object.assign(new Error("timed out"), { code: "ETIMEDOUT" });
- const exec = vi.fn(async () => {
- throw failure;
- });
- let error = null;
- try {
- await fleetSecretsGetAsync("USAGE_INGEST_TOKEN", { exec, binary: "/fake/fleet-secrets", strict: true });
- } catch (caught) {
- error = caught;
- }
- expect(error).not.toBeNull();
- expect(error.message).toContain("USAGE_INGEST_TOKEN");
- expect(error.cause).toBe(failure);
- });
-});
-
-describe("fleetSecretsNames", () => {
- it("merges names from root and the folder and ignores junk lines", () => {
- const exec = vi.fn((_bin, args) =>
- args.at(-1) === "/" ? "ALPHA\nBETA\n\n" : "BETA\nGAMMA\nnot a name\n",
- );
- const names = fleetSecretsNames({ exec, binary: "/fake/fleet-secrets" });
- expect([...names].sort()).toEqual(["ALPHA", "BETA", "GAMMA"]);
- });
-
- it("returns an empty set when the binary fails", () => {
- const exec = vi.fn(() => {
- throw new Error("boom");
- });
- expect(fleetSecretsNames({ exec, binary: "/fake/fleet-secrets" }).size).toBe(0);
- });
-});
diff --git a/scripts/antigravity-usage-collector.mjs b/scripts/antigravity-usage-collector.mjs
index 439425644..ca1ec242c 100644
--- a/scripts/antigravity-usage-collector.mjs
+++ b/scripts/antigravity-usage-collector.mjs
@@ -616,7 +616,7 @@ async function main() {
]);
if (!ingestToken && !DRY_RUN) {
fail(
- "Missing ANTIGRAVITY_INGEST_TOKEN or USAGE_INGEST_TOKEN. Ensure the token is set in the environment or available through `fleet-secrets get`."
+ "Missing ANTIGRAVITY_INGEST_TOKEN or USAGE_INGEST_TOKEN.\u00A0 Check this consumer's Infisical-synced value or qualified scoped binding."
);
}
diff --git a/scripts/collector-injector.mjs b/scripts/collector-injector.mjs
index 93906eb1a..8d480d622 100644
--- a/scripts/collector-injector.mjs
+++ b/scripts/collector-injector.mjs
@@ -14,7 +14,7 @@ const PROFILES = Object.freeze({
const SETTINGS = ["HOME", "PATH", "TMPDIR", "LANG", "TZ", "USAGE_MACHINE_ID", "USAGE_MONITOR_INGEST_URL", "COLLECTOR_SENTRY_ENABLED", "COLLECTOR_TELEMETRY_HUB_ENDPOINT", "COLLECTOR_SENTRY_STATE_DIR"];
const PROFILE_SETTINGS = { kimi: ["KIMI_CODE_HOME"], zcode: ["ZCODE_DB", "ZCODE_DATA_BASE_DIR"], "muse-code": [] };
-function custody(path, mode) {
+function custody(path) {
if (!isAbsolute(path)) throw new Error("invalid_custody");
const fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
try {
@@ -29,7 +29,7 @@ function custody(path, mode) {
}
if (bytes > 16384) throw new Error("invalid_custody");
const raw = buffer.subarray(0, bytes).toString("utf8");
- if (mode === "service-token" && raw.startsWith("st.")) {
+ if (raw.startsWith("st.")) {
// Existing service-token custody stores raw ASCII, optionally ending in
// one newline. Accept it without rewriting the shared custody file.
const token = raw.endsWith("\r\n") ? raw.slice(0, -2) : raw.endsWith("\n") ? raw.slice(0, -1) : raw;
@@ -37,7 +37,7 @@ function custody(path, mode) {
return { token };
}
const data = JSON.parse(raw);
- const keys = mode === "service-token" ? ["token"] : ["clientId", "clientSecret"];
+ const keys = ["token"];
if (!data || Array.isArray(data) || typeof data !== "object" || Object.keys(data).sort().join() !== keys.sort().join() || keys.some((key) => typeof data[key] !== "string" || !data[key].trim() || data[key] !== data[key].trim())) throw new Error("invalid_custody");
// Restrict custody to a flat object with literal field names, rejecting
// duplicate keys that JSON.parse would otherwise silently overwrite.
@@ -67,22 +67,14 @@ async function requestJson(url, init, fetchImpl) {
}
export async function prepareCollector({ profile, mode, path, env = process.env, fetchImpl = fetch, origin = "https://app.infisical.com" }) {
- if (!Object.hasOwn(PROFILES, profile) || !["service-token", "machine-identity"].includes(mode) || typeof path !== "string") throw new Error("invalid_arguments");
+ if (!Object.hasOwn(PROFILES, profile) || mode !== "service-token" || typeof path !== "string") throw new Error("invalid_arguments");
if (env.USAGE_MONITOR_INGEST_URL !== undefined && env.USAGE_MONITOR_INGEST_URL !== "https://usage.jays.services/api/ingest/usage") throw new Error("invalid_ingest_url");
if (Object.keys(env).some((key) => key.startsWith("INFISICAL_") && env[key])) throw new Error("ambiguous_auth");
const url = new URL(origin);
if (url.protocol !== "https:" || !["app.infisical.com", "us.infisical.com", "eu.infisical.com"].includes(url.hostname) || url.username || url.password || url.port || url.search || url.hash || !["", "/"].includes(url.pathname)) throw new Error("invalid_origin");
- const auth = custody(path, mode);
- let token;
- if (mode === "service-token") {
- token = auth.token;
- if (!token.startsWith("st.")) throw new Error("invalid_service_token");
- await verifyServiceToken({ token, projectId: PROJECT, paths: ["/telemetry"], permissions: ["read"], baseUrl: url.origin, fetchImpl });
- } else {
- const login = await requestJson(`${url.origin}/api/v1/auth/universal-auth/login`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(auth) }, fetchImpl);
- if (!login || typeof login.accessToken !== "string" || !login.accessToken.trim() || login.accessToken !== login.accessToken.trim() || login.accessToken.startsWith("st.")) throw new Error("invalid_login");
- token = login.accessToken;
- }
+ const { token } = custody(path);
+ if (!token.startsWith("st.")) throw new Error("invalid_service_token");
+ await verifyServiceToken({ token, projectId: PROJECT, paths: ["/telemetry"], permissions: ["read"], baseUrl: url.origin, fetchImpl });
const query = new URLSearchParams({ workspaceId: PROJECT, environment: "prod", secretPath: "/telemetry", viewSecretValue: "true", expandSecretReferences: "false", include_imports: "false", recursive: "false" });
const body = await requestJson(`${url.origin}/api/v3/secrets/raw?${query}`, { headers: { authorization: `Bearer ${token}` } }, fetchImpl);
if (!body || !Array.isArray(body.secrets)) throw new Error("invalid_secrets");
diff --git a/scripts/collector-injector.node-test.mjs b/scripts/collector-injector.node-test.mjs
index 4186a7b18..e78a81b99 100644
--- a/scripts/collector-injector.node-test.mjs
+++ b/scripts/collector-injector.node-test.mjs
@@ -1,6 +1,6 @@
import { test } from "node:test";
import assert from "node:assert/strict";
-import { mkdtempSync, writeFileSync, chmodSync, symlinkSync, rmSync, readFileSync } from "node:fs";
+import { mkdtempSync, writeFileSync, chmodSync, symlinkSync, rmSync, readFileSync, existsSync } from "node:fs";
import { EventEmitter } from "node:events";
import { spawnSync } from "node:child_process";
import { tmpdir } from "node:os";
@@ -26,6 +26,7 @@ function fakeFetch(profile, meta = metadata, rows = pairs[profile].map((secretKe
}
test("all profiles use exact scope and isolated child environments", async (t) => {
const { path } = fixture(t);
+ const original = readFileSync(path);
for (const profile of Object.keys(pairs)) {
const fake = fakeFetch(profile);
const result = await prepareCollector({ profile, mode: "service-token", path, env: { HOME: "/home/test", NODE_OPTIONS: "sentinel", USAGE_INGEST_TOKEN: "sentinel", COLLECTOR_TELEMETRY_HUB_TOKEN: "sentinel" }, fetchImpl: fake.fetchImpl });
@@ -35,6 +36,8 @@ test("all profiles use exact scope and isolated child environments", async (t) =
for (const [key, value] of Object.entries({ workspaceId: project, environment: "prod", secretPath: "/telemetry", include_imports: "false", recursive: "false", expandSecretReferences: "false" })) assert.equal(query.get(key), value);
assert.equal(fake.calls[0].options.redirect, "error");
assert.equal(fake.calls[1].options.redirect, "error");
+ for (const call of fake.calls) assert.equal(call.options.headers.authorization, "Bearer st.sentinel");
+ assert.ok(readFileSync(path).equals(original));
}
});
test("scope violations fail before fetching secrets", async (t) => {
@@ -68,7 +71,7 @@ test("raw custody preserves metadata verification before secret lookup", async (
await assert.rejects(prepareCollector({ profile: "kimi", mode: "service-token", path, env: {}, fetchImpl: fake.fetchImpl }), /service_token_verification_failed/);
assert.equal(fake.calls.length, 1);
});
-test("malformed raw custody and raw machine-identity custody fail before network", async (t) => {
+test("malformed raw custody fails before network", async (t) => {
const { path, dir } = fixture(t);
let calls = 0;
const fetchImpl = async () => { calls++; throw new Error("network must not run"); };
@@ -78,7 +81,6 @@ test("malformed raw custody and raw machine-identity custody fail before network
await assert.rejects(run());
}
writeFileSync(path, "st.raw-sentinel");
- await assert.rejects(run("machine-identity"));
chmodSync(path, 0o644); await assert.rejects(run()); chmodSync(path, 0o600);
const link = join(dir, "raw-link"); symlinkSync(path, link); await assert.rejects(run("service-token", link));
writeFileSync(path, '{"token":"st.raw-sentinel","extra":"value"}'); await assert.rejects(run());
@@ -87,7 +89,8 @@ test("malformed raw custody and raw machine-identity custody fail before network
test("raw custody failures disclose neither custody bytes nor path", (t) => {
const { path } = fixture(t);
writeFileSync(path, "st.raw-sentinel\ninvalid");
- const result = spawnSync(process.execPath, [new URL("./collector-injector.mjs", import.meta.url).pathname, "kimi", "service-token", path], { encoding: "utf8", env: { PATH: process.env.PATH } });
+ const result = spawnSync(process.execPath, [new URL("./collector-injector.mjs", import.meta.url).pathname, "kimi", "service-token", path], { encoding: "utf8", env: { PATH: process.env.PATH }, timeout: 15000, killSignal: "SIGKILL" });
+ assert.ifError(result.error);
assert.notEqual(result.status, 0);
assert.equal(result.stdout, "");
assert.equal(result.stderr.trim(), "Collector credential injection failed.");
@@ -143,7 +146,8 @@ test("templates select the injector and failures never print custody values", (t
for (const profile of ["kimi", "zcode"]) {
const template = readFileSync(new URL(`./com.jays.${profile}-usage-collector.plist.example`, import.meta.url), "utf8");
assert.match(template, /collector-injector\.mjs/); assert.ok(template.includes(`${profile}`));
- assert.match(template, /AUTH_MODE<\/string>/);
+ assert.match(template, /service-token<\/string>/);
+ assert.equal(template.includes("AUTH_MODE"), false);
assert.equal(template.includes("sentinel"), false);
}
const museCodeTemplate = readFileSync(new URL("./com.jays.muse-code-usage-collector.plist.example", import.meta.url), "utf8");
@@ -151,7 +155,8 @@ test("templates select the injector and failures never print custody values", (t
assert.equal(museCodeTemplate.includes("collector-injector"), false);
assert.equal(museCodeTemplate.includes("AUTH_MODE"), false);
assert.equal(museCodeTemplate.includes("sentinel"), false);
- const result = spawnSync(process.execPath, [new URL("./collector-injector.mjs", import.meta.url).pathname, "kimi", "invalid", path], { encoding: "utf8" });
+ const result = spawnSync(process.execPath, [new URL("./collector-injector.mjs", import.meta.url).pathname, "kimi", "invalid", path], { encoding: "utf8", env: { PATH: process.env.PATH }, timeout: 15000, killSignal: "SIGKILL" });
+ assert.ifError(result.error);
assert.notEqual(result.status, 0); assert.equal((result.stdout + result.stderr).includes("sentinel"), false);
});
test("malformed, duplicate, missing and unexpanded values fail closed", async (t) => {
@@ -166,11 +171,34 @@ test("network, redirect and oversized responses fail closed", async (t) => {
const { path } = fixture(t);
for (const fetchImpl of [async () => { throw new Error("network"); }, async () => new Response(null, { status: 302, headers: { location: "https://elsewhere.invalid" } }), async () => new Response("x".repeat(140000))]) await assert.rejects(prepareCollector({ profile: "kimi", mode: "service-token", path, env: {}, fetchImpl }));
});
-test("machine identity logs in with explicit custody and strict lookup never calls fleet secrets", async (t) => {
- const { path } = fixture(t, { clientId: "app-id", clientSecret: "sentinel" });
+test("machine identity refuses before custody, network or child launch", async (t) => {
+ const { dir } = fixture(t);
+ const path = join(dir, "nonexistent-custody.json");
let calls = 0;
- const fetchImpl = async (url, options) => { calls++; assert.equal(options.redirect, "error"); return response(calls === 1 ? { accessToken: "machine-bearer" } : { secrets: pairs.kimi.map((secretKey) => ({ secretKey, secretValue: "value" })) }); };
- const result = await prepareCollector({ profile: "kimi", mode: "machine-identity", path, env: {}, fetchImpl });
+ const fetchImpl = async () => { calls++; throw new Error("network must not run"); };
+ for (const profile of Object.keys(pairs)) {
+ await assert.rejects(prepareCollector({ profile, mode: "machine-identity", path, env: {}, fetchImpl }), /^Error: invalid_arguments$/);
+ }
+ assert.equal(calls, 0);
+ assert.equal(existsSync(path), false);
+ const marker = join(dir, "forbidden-operation");
+ const hook = join(dir, "refusal-traps.mjs");
+ writeFileSync(hook, `import fs from 'node:fs'; import cp from 'node:child_process'; import { syncBuiltinESMExports } from 'node:module';
+const fail = () => { fs.writeFileSync(process.env.TEST_MARKER, 'forbidden'); throw new Error('forbidden'); };
+const open = fs.openSync; fs.openSync = (path, ...args) => path === process.env.TEST_CUSTODY ? fail() : open(path, ...args);
+cp.spawn = fail; globalThis.fetch = fail; syncBuiltinESMExports();\n`);
+ const result = spawnSync(process.execPath, ["--import", hook, new URL("./collector-injector.mjs", import.meta.url).pathname, "kimi", "machine-identity", path], { encoding: "utf8", env: { PATH: process.env.PATH, TEST_MARKER: marker, TEST_CUSTODY: path }, timeout: 15000, killSignal: "SIGKILL" });
+ assert.ifError(result.error);
+ assert.equal(result.status, 1);
+ assert.equal(result.stdout, "");
+ assert.equal(result.stderr.trim(), "Collector credential injection failed.");
+ assert.equal(existsSync(marker), false);
+ assert.equal((result.stdout + result.stderr).includes(path), false);
+});
+test("service-token injection keeps strict lookup without calling fleet secrets", async (t) => {
+ const { path } = fixture(t);
+ const fake = fakeFetch("kimi");
+ const result = await prepareCollector({ profile: "kimi", mode: "service-token", path, env: {}, fetchImpl: fake.fetchImpl });
assert.equal(result.env.COLLECTOR_STRICT_INJECTED_SECRETS, "1");
const lookup = () => { throw new Error("fleet-secrets called"); };
assert.equal(resolveCollectorToken(["MISSING"], { env: result.env, fleetSecretsGet: lookup }), null);
diff --git a/scripts/collector-keychain.node-test.mjs b/scripts/collector-keychain.node-test.mjs
index b4591e9de..c8995f6d0 100644
--- a/scripts/collector-keychain.node-test.mjs
+++ b/scripts/collector-keychain.node-test.mjs
@@ -494,15 +494,100 @@ test("Muse Code uses its pinned ingest binding and reuses the real resolver cach
]);
});
-test("the codex binding keeps the automation identity and never reads the login keychain", async () => {
- const source = await readFile(join(scripts, "lib", "codex-run-session-token-collector.mjs"), "utf8");
- assert.ok(!source.includes("infisical-service-token"));
- assert.ok(!source.includes("keychain-service-token.mjs"));
- const binding = await import("./lib/codex-run-session-token-collector.mjs");
- const shared = await import("./lib/run-session-token-collector.mjs");
- assert.notEqual(binding.resolveCollectorToken, shared.resolveCollectorToken);
- assert.equal(binding.resolveCollectorToken(["CODEX_INGEST_TOKEN"], { env: { CODEX_INGEST_TOKEN: "tok" } }), "tok");
+// BEGIN CODEX INJECTED FIXTURES
+async function codexInjectedFixture(t, body) {
+ const { mkdtemp, writeFile, rm } = await import("node:fs/promises");
+ const { tmpdir } = await import("node:os");
+ const { spawnSync } = await import("node:child_process");
+ const { pathToFileURL } = await import("node:url");
+ const directory = await mkdtemp(join(tmpdir(), "codex-injected-"));
+ t.after(() => rm(directory, { recursive: true, force: true }));
+ const traps = ["security", "infisical", "fleet-secrets"].map(name => join(directory, name));
+ for (const path of traps) await writeFile(path, '#!/bin/sh\nprintf invoked >> "$FIXTURE_AUTH_MARKER"\nexit 97\n', { mode: 0o700 });
+ const marker = join(directory, "auth-invoked");
+ const program = `
+import assert from "node:assert/strict";
+import cp from "node:child_process";
+import { syncBuiltinESMExports } from "node:module";
+import { existsSync } from "node:fs";
+const traps = ${JSON.stringify(traps)};
+const marker = ${JSON.stringify(marker)};
+const childCalls = [], networkCalls = [];
+const realExec = cp.execFileSync;
+cp.execFileSync = (binary, args, options) => {
+ childCalls.push(binary);
+ // Refuse any destination outside the inert fixture before spawning.
+ assert.ok(traps.includes(binary), "unexpected credential executable");
+ return realExec(binary, args, { ...options, timeout: 15000, killSignal: "SIGKILL" });
+};
+syncBuiltinESMExports();
+globalThis.fetch = () => { networkCalls.push(true); throw new Error("unexpected provider request"); };
+const binding = await import(${JSON.stringify(pathToFileURL(join(scripts, "lib", "codex-run-session-token-collector.mjs")).href)});
+const shared = await import(${JSON.stringify(pathToFileURL(join(scripts, "lib", "run-session-token-collector.mjs")).href)});
+const bootstrap = {
+ INFISICAL_TOKEN: "st.synthetic-bootstrap", INFISICAL_FLEET_OPS_PROJECT_ID: "synthetic-project",
+ INFISICAL_BIN: traps[1], CODEX_SECURITY_BIN: traps[0], COLLECTOR_STRICT_INJECTED_SECRETS: "0",
+ INFISICAL_CLIENT_ID: "synthetic-client", INFISICAL_CLIENT_SECRET: "synthetic-secret",
+ INFISICAL_UNIVERSAL_AUTH_CLIENT_ID: "synthetic-client", INFISICAL_UNIVERSAL_AUTH_CLIENT_SECRET: "synthetic-secret",
+};
+${body}
+assert.deepEqual(childCalls, [], "Codex must not spawn credential readers");
+assert.deepEqual(networkCalls, [], "Codex must not request provider data");
+assert.equal(existsSync(marker), false, "inert auth traps must remain unused");
+`;
+ const result = spawnSync(process.execPath, ["--input-type=module"], {
+ input: program, encoding: "utf8", timeout: 15000, killSignal: "SIGKILL", maxBuffer: 64 * 1024,
+ env: { PATH: directory, HOME: directory, FIXTURE_AUTH_MARKER: marker },
+ });
+ assert.equal(result.error, undefined);
+ assert.equal(result.signal, null);
+ assert.equal(result.status, 0, result.stderr);
+ assert.equal(result.stdout, "");
+ assert.equal(result.stderr, "");
+}
+
+test("Codex preserves shared exports and reads injected names in priority order without caching", async (t) => {
+ await codexInjectedFixture(t, `
+for (const name of Object.keys(shared)) if (name !== "resolveCollectorToken") assert.equal(binding[name], shared[name]);
+const names = Object.freeze(["CODEX_INGEST_TOKEN", "USAGE_INGEST_TOKEN"]);
+const env = { ...bootstrap, CODEX_INGEST_TOKEN: "first-output", USAGE_INGEST_TOKEN: "shared-output" };
+assert.ok(binding.resolveCollectorToken(names, { env }) === "first-output");
+env.CODEX_INGEST_TOKEN = "changed-output";
+assert.ok(binding.resolveCollectorToken(names, { env }) === "changed-output");
+delete env.CODEX_INGEST_TOKEN;
+assert.ok(binding.resolveCollectorToken(names, { env }) === "shared-output");
+env.CODEX_INGEST_TOKEN = " ";
+assert.ok(binding.resolveCollectorToken(names, { env }) === "shared-output");
+delete env.USAGE_INGEST_TOKEN;
+assert.equal(binding.resolveCollectorToken(names, { env }), null);
+assert.equal(binding.resolveCollectorToken(undefined, { env: { USAGE_INGEST_TOKEN: "default-output" } }), "default-output");
+process.env.CODEX_INGEST_TOKEN = "process-output";
+assert.ok(binding.resolveCollectorToken(names) === "process-output");
+delete process.env.CODEX_INGEST_TOKEN;
+`);
+});
+
+test("Codex forces injected mode without mutating options or accepting a lookup bypass", async (t) => {
+ await codexInjectedFixture(t, `
+let lookups = 0;
+const env = Object.freeze({ ...bootstrap });
+const options = Object.freeze({ env, fleetSecretsGet: () => { lookups++; throw new Error("synthetic-secret"); } });
+assert.equal(binding.resolveCollectorToken(["CODEX_INGEST_TOKEN", "USAGE_INGEST_TOKEN"], options), null);
+assert.equal(lookups, 0);
+assert.equal(options.env, env);
+assert.equal(env.COLLECTOR_STRICT_INJECTED_SECRETS, "0");
+assert.equal(Object.keys(options).length, 2);
+`);
+});
+
+test("Codex missing or partial bootstrap stays environment-only with no auth diagnostics", async (t) => {
+ await codexInjectedFixture(t, `
+for (const env of [{}, bootstrap, { INFISICAL_TOKEN: "st.fixture" }, { INFISICAL_FLEET_OPS_PROJECT_ID: bootstrap.INFISICAL_FLEET_OPS_PROJECT_ID }, { ...bootstrap, COLLECTOR_STRICT_INJECTED_SECRETS: "1" }]) {
+ assert.equal(binding.resolveCollectorToken(["CODEX_INGEST_TOKEN", "USAGE_INGEST_TOKEN"], { env }), null);
+}
+`);
});
+// END CODEX INJECTED FIXTURES
for (const [entry, stem] of Object.entries(ENTRY_POINTS)) {
test(`the ${entry} entry point uses its own binding and awaits the resolver`, async () => {
diff --git a/scripts/collector-tests/cursor-usage-collector.test.mjs b/scripts/collector-tests/cursor-usage-collector.test.mjs
index ddc3b3d28..7f38ff779 100644
--- a/scripts/collector-tests/cursor-usage-collector.test.mjs
+++ b/scripts/collector-tests/cursor-usage-collector.test.mjs
@@ -18,9 +18,13 @@
// is one level below scripts/ either way.
import assert from "node:assert/strict";
+import { spawnSync } from "node:child_process";
+import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { fileURLToPath, pathToFileURL } from "node:url";
import { describe, it } from "vitest";
-
import {
CURSOR_ADMIN_ATTRIBUTIONS,
CURSOR_ADMIN_DATE_RANGE_ERROR,
@@ -37,6 +41,72 @@ import {
runCursorCollector,
} from "../lib/cursor-admin-telemetry.mjs";
+describe("Cursor Admin synced key", () => {
+ it("keeps synced-key resolution and missing-key CLI runs offline without any credential helper", () => {
+ const home = mkdtempSync(join(tmpdir(), "cursor-synced-key-"));
+ try {
+ const bin = join(home, ".local", "bin");
+ mkdirSync(bin, { recursive: true });
+ const marker = join(home, "unexpected-call");
+ for (const name of ["fleet-secrets", "infisical", "security"]) {
+ writeFileSync(join(bin, name), '#!/bin/sh\nprintf called >> "$CURSOR_TEST_MARKER"\nexit 91\n', { mode: 0o755 });
+ }
+ const preload = join(home, "offline.mjs");
+ writeFileSync(preload, `import { appendFileSync } from "node:fs";
+globalThis.fetch = async () => {
+ appendFileSync(process.env.CURSOR_TEST_MARKER, "fetch");
+ throw new Error("unexpected network request");
+};
+`);
+ const script = fileURLToPath(new URL("../cursor-usage-collector.mjs", import.meta.url));
+ const helperProgram = `import assert from "node:assert/strict";
+import { resolveCursorAdminApiKey } from ${JSON.stringify(pathToFileURL(script).href)};
+const unrelated = {
+ CURSOR_ADMIN_INGEST_TOKEN: "fixture",
+ USAGE_INGEST_TOKEN: "fixture",
+ INFISICAL_TOKEN: "fixture",
+ INFISICAL_FLEET_OPS_PROJECT_ID: "fixture",
+};
+assert.equal(resolveCursorAdminApiKey({ ...unrelated, CURSOR_ADMIN_API_KEY: " fixture " }), "fixture");
+for (const value of [undefined, "", " \t "]) {
+ assert.equal(resolveCursorAdminApiKey({ ...unrelated, CURSOR_ADMIN_API_KEY: value }), null);
+}
+`;
+ const helperResult = spawnSync(process.execPath, ["--import", preload, "--input-type=module", "--eval", helperProgram], {
+ env: { HOME: home, PATH: bin, TMPDIR: home, CURSOR_TEST_MARKER: marker, NODE_ENV: "test", VITEST: "true" },
+ cwd: home, encoding: "utf8", timeout: 5000, killSignal: "SIGKILL", maxBuffer: 64 * 1024,
+ });
+ assert.ifError(helperResult.error);
+ assert.equal(helperResult.signal, null);
+ assert.equal(helperResult.status, 0, helperResult.stderr);
+ assert.equal(existsSync(marker), false, "helper resolution must not read credentials or make requests");
+ assert.equal((helperResult.stdout + helperResult.stderr).includes("fixture"), false);
+ for (const value of [undefined, "", " \t "]) {
+ for (const dryRun of [true, false]) {
+ const env = {
+ HOME: home, PATH: bin, TMPDIR: home, CURSOR_TEST_MARKER: marker,
+ INFISICAL_TOKEN: "fixture", INFISICAL_FLEET_OPS_PROJECT_ID: "fixture",
+ CURSOR_ADMIN_INGEST_TOKEN: "fixture", USAGE_INGEST_TOKEN: "fixture",
+ ...(value === undefined ? {} : { CURSOR_ADMIN_API_KEY: value }),
+ NODE_ENV: "test", VITEST: "true",
+ };
+ const result = spawnSync(process.execPath, ["--import", preload, script, ...(dryRun ? ["--dry-run"] : [])], {
+ env, cwd: home, encoding: "utf8", timeout: 5000, killSignal: "SIGKILL", maxBuffer: 64 * 1024,
+ });
+ assert.ifError(result.error);
+ assert.equal(result.signal, null);
+ assert.equal(result.status, dryRun ? 0 : 1, result.stderr);
+ assert.match(dryRun ? result.stdout : result.stderr, dryRun ? /no CURSOR_ADMIN_API_KEY available; nothing to read/ : /CURSOR_ADMIN_API_KEY is required/);
+ assert.equal(existsSync(marker), false, "no credential helper, Cursor request or ingest request may run");
+ assert.equal((result.stdout + result.stderr).includes("fixture"), false);
+ }
+ }
+ } finally {
+ rmSync(home, { recursive: true, force: true });
+ }
+ });
+});
+
const USER_ID = "user_9f2c41de";
const USER_EMAIL = "jay.owner@example.com";
const USER_NAME = "Jay Owner";
diff --git a/scripts/com.jays.kimi-usage-collector.plist.example b/scripts/com.jays.kimi-usage-collector.plist.example
index 4442afd37..c782b0ed6 100644
--- a/scripts/com.jays.kimi-usage-collector.plist.example
+++ b/scripts/com.jays.kimi-usage-collector.plist.example
@@ -4,7 +4,7 @@
Scheduled exact Kimi Code turn telemetry. Install from the detached
collector runtime after replacing every absolute-path and hub-host placeholder.
- Provide a scoped custody file; never put secret values in this plist.
+ Provide a scoped service-token custody file; never put secret values in this plist.
-->
@@ -15,7 +15,7 @@
/ABSOLUTE/PATH/TO/node
/ABSOLUTE/PATH/TO/COLLECTORS/scripts/collector-injector.mjs
kimi
- AUTH_MODE
+ service-token
/ABSOLUTE/PATH/TO/CUSTODY.json
EnvironmentVariables
diff --git a/scripts/com.jays.zcode-usage-collector.plist.example b/scripts/com.jays.zcode-usage-collector.plist.example
index e9061a1e3..3c39196b7 100644
--- a/scripts/com.jays.zcode-usage-collector.plist.example
+++ b/scripts/com.jays.zcode-usage-collector.plist.example
@@ -4,7 +4,7 @@
Scheduled exact ZCode model-request telemetry. Install from the detached
collector runtime after replacing every absolute-path and hub-host placeholder.
- Provide a scoped custody file; never put secret values in this plist.
+ Provide a scoped service-token custody file; never put secret values in this plist.
-->
@@ -15,7 +15,7 @@
/ABSOLUTE/PATH/TO/node
/ABSOLUTE/PATH/TO/COLLECTORS/scripts/collector-injector.mjs
zcode
- AUTH_MODE
+ service-token
/ABSOLUTE/PATH/TO/CUSTODY.json
EnvironmentVariables
diff --git a/scripts/cursor-usage-collector.mjs b/scripts/cursor-usage-collector.mjs
index 04aeb6696..ca3c56a0d 100644
--- a/scripts/cursor-usage-collector.mjs
+++ b/scripts/cursor-usage-collector.mjs
@@ -32,13 +32,11 @@
// node scripts/cursor-usage-collector.mjs [--dry-run] [--debug] [--days N] [--end YYYY-MM-DD]
//
// Env:
-// CURSOR_ADMIN_API_KEY Cursor Admin API key. Read from the environment
-// first, then from Infisical through `fleet-secrets
-// get CURSOR_ADMIN_API_KEY`. Never logged, never
-// written to disk, never put on a command line.
-// USAGE_INGEST_TOKEN UM ingest token. Same env-then-fleet-secrets
-// resolution. Read from the environment first, then
-// from Infisical.
+// CURSOR_ADMIN_API_KEY Cursor Admin API key synced from Infisical into
+// the environment. No local credential fallback;
+// never logged, written to disk or put on argv.
+// USAGE_INGEST_TOKEN UM ingest token, resolved by the shared collector
+// resolver after CURSOR_ADMIN_INGEST_TOKEN.
// USAGE_MONITOR_INGEST_URL full ingest URL
// (default https://usage.jays.services/api/ingest/usage)
// USAGE_MONITOR_BASE_URL base URL (default https://usage.jays.services);
@@ -52,7 +50,6 @@ import { pathToFileURL } from "node:url";
import { postUsageBatches } from "./lib/session-token-collectors.mjs";
import { resolveCollectorToken } from "./lib/run-session-token-collector.mjs";
-import { fleetSecretsGet } from "./lib/fleet-secrets.mjs";
import {
CURSOR_ADMIN_MAX_WINDOW_DAYS,
CURSOR_ADMIN_PRODUCER_ID,
@@ -79,12 +76,9 @@ export function ingestUrl(env = process.env) {
return `${base.replace(/\/+$/, "")}/api/ingest/usage`;
}
-/** The Cursor Admin API key: environment first, then Infisical. */
+/** The Cursor Admin API key transported in the Infisical-synced environment. */
export function resolveCursorAdminApiKey(env = process.env) {
- const fromEnv = env.CURSOR_ADMIN_API_KEY?.trim();
- if (fromEnv) return fromEnv;
- const fromInfisical = fleetSecretsGet("CURSOR_ADMIN_API_KEY");
- return typeof fromInfisical === "string" ? fromInfisical.trim() : null;
+ return env.CURSOR_ADMIN_API_KEY?.trim() || null;
}
/** Parse the CLI flags. No secret ever arrives through argv. */
diff --git a/scripts/fleet-usage-collector.mjs b/scripts/fleet-usage-collector.mjs
index 18dd0b339..5bd6334ae 100755
--- a/scripts/fleet-usage-collector.mjs
+++ b/scripts/fleet-usage-collector.mjs
@@ -224,7 +224,7 @@ async function collectAllSessionEvents(since) {
/**
* Scoped ingest token names per producer. A scoped token authorizes exactly
* one producerId, so every batch resolves its own token (environment first,
- * then `fleet-secrets get`) before the unscoped USAGE_INGEST_TOKEN,
+ * then an explicit Infisical service-token lookup) before the unscoped USAGE_INGEST_TOKEN,
* which is refused once USAGE_INGEST_REQUIRE_SCOPED_TOKENS=true.
*/
export const FLEET_TOKEN_ENV_BY_PRODUCER = {
diff --git a/scripts/infisical-secrets-safe.sh b/scripts/infisical-secrets-safe.sh
index 655abb572..38ff9ebcf 100755
--- a/scripts/infisical-secrets-safe.sh
+++ b/scripts/infisical-secrets-safe.sh
@@ -14,11 +14,11 @@
# Every subcommand here is value-blind by construction:
# names list secret KEY NAMES only
# has KEY exit 0/1 — does KEY exist, with a non-empty value
-# set KEY copy KEY from `fleet-secrets get` into this project's Infisical
+# set KEY copy an Infisical-synced environment value into this project
# pull KEY retired (OPS-818); nothing writes or reads the flat secrets file
# sync-platforms batch-copy the platform-status tokens (see MAP below)
#
-# A value only ever travels: fleet-secrets -> shell variable -> CLI (stdin or
+# A value only ever travels: synced environment -> shell variable -> CLI (stdin or
# captured --plain). It is never interpolated into a command line (visible in
# `ps`), never echoed, and never written to a log.
#
@@ -36,7 +36,6 @@
# INFISICAL_PATH default /
# INFISICAL_UM_READ_TOKEN read-only service token for names/has
# INFISICAL_UM_WRITE_TOKEN write-only service token for set/delete
-# INFISICAL_UM_CLIENT_ID / _CLIENT_SECRET explicit project machine identity
# INFISICAL_TOKEN legacy read token only; never used for writes
#
set -euo pipefail
@@ -48,25 +47,42 @@ SECRET_PATH="${INFISICAL_UM_SECRET_PATH:-${INFISICAL_PATH:-/}}"
die() { printf '%s\n' "$*" >&2; exit 1; }
note() { printf '%s\n' "$*"; }
+validate_key() { [[ "$1" =~ ^[A-Za-z_][A-Za-z0-9_]*$ ]] || die "Invalid secret key name."; }
+case "${1:-}" in
+ has|set|delete) for key in "${@:2}"; do validate_key "$key"; done ;;
+esac
command -v infisical >/dev/null 2>/dev/null || die "infisical CLI not found on PATH."
node "$ROOT/scripts/check-infisical-token.mjs" config || die "Infisical target configuration rejected."
+INFISICAL_ORIGIN="$(node -e 'process.stdout.write(new URL(process.env.INFISICAL_BASE_URL || process.env.INFISICAL_API_URL || "https://app.infisical.com").origin)')" \
+ || die "Infisical target configuration rejected."
+
+# Use the same approved origin and selected token as the metadata verifier.
+# Subshell changes never alter the caller's environment or bootstrap inputs.
+infisical_cli() (
+ unset INFISICAL_BASE_URL INFISICAL_API_URL TOKEN \
+ INFISICAL_CLIENT_ID INFISICAL_CLIENT_SECRET \
+ INFISICAL_UNIVERSAL_AUTH_CLIENT_ID INFISICAL_UNIVERSAL_AUTH_CLIENT_SECRET \
+ INFISICAL_UNIVERSAL_AUTH_ACCESS_TOKEN \
+ INFISICAL_AUTOMATION_CLIENT_ID INFISICAL_AUTOMATION_CLIENT_SECRET \
+ INFISICAL_UM_CLIENT_ID INFISICAL_UM_CLIENT_SECRET \
+ INFISICAL_UM_READ_TOKEN INFISICAL_UM_WRITE_TOKEN
+ export INFISICAL_DOMAIN="$INFISICAL_ORIGIN"
+ command infisical "$@"
+)
-# One value from the Mac-side fleet-secrets CLI (root, then /global-api-keys).
-# Prints nothing and succeeds when the binary or the key is absent.
-fleet_value() {
+# One explicitly named Infisical-synced environment value; no store discovery.
+synced_value() {
local name="$1"
- command -v fleet-secrets >/dev/null 2>/dev/null || return 0
- fleet-secrets get "$name" --path / 2>/dev/null \
- || fleet-secrets get "$name" --path /global-api-keys 2>/dev/null \
- || true
+ validate_key "$name"
+ printf '%s' "${!name-}"
}
# ---------------------------------------------------------------------------
-# Auth — prefer permission-specific project tokens; machine identity is explicit.
+# Auth — permission-specific project service tokens only.
# ---------------------------------------------------------------------------
infisical_token() {
- local permission="$1" token id secret token_name
+ local permission="$1" token token_name
case "$permission" in
read)
token_name="INFISICAL_UM_READ_TOKEN"
@@ -78,24 +94,9 @@ infisical_token() {
;;
*) die "Unsupported Infisical permission" ;;
esac
- if [ -n "$token" ]; then
- INFISICAL_TOKEN="$token" INFISICAL_UM_PROJECT_ID="$PROJECT_ID" INFISICAL_UM_SECRET_PATH="$SECRET_PATH" \
- node "$ROOT/scripts/check-infisical-token.mjs" "$permission" || die "Infisical credential verification failed."
- printf '%s' "$token"; return 0
- fi
-
- id="${INFISICAL_UM_CLIENT_ID:-}"
- secret="${INFISICAL_UM_CLIENT_SECRET:-}"
- [ -n "$id" ] && [ -n "$secret" ] || die \
- "No Infisical $permission credential; export $token_name or an explicit project machine-identity pair."
-
- # --silent keeps the token off stdout except as the captured value.
- token="$(INFISICAL_UNIVERSAL_AUTH_CLIENT_ID="$id" \
- INFISICAL_UNIVERSAL_AUTH_CLIENT_SECRET="$secret" \
- infisical login --method=universal-auth --plain --silent 2>/dev/null)" \
- || die "Infisical login failed (explicit machine identity rejected)."
- # This explicit project identity has no service-token metadata to attest.
- # The target configuration was checked above; Infisical authorizes the operation.
+ [[ "$token" == st.* ]] || die "$token_name service token required for Infisical $permission access."
+ INFISICAL_TOKEN="$token" INFISICAL_UM_PROJECT_ID="$PROJECT_ID" INFISICAL_UM_SECRET_PATH="$SECRET_PATH" \
+ node "$ROOT/scripts/check-infisical-token.mjs" "$permission" || die "Infisical credential verification failed."
printf '%s' "$token"
}
@@ -110,8 +111,8 @@ ensure_write_token() { [ -n "$WRITE_TOKEN" ] || WRITE_TOKEN="$(infisical_token w
# Print only KEY NAMES from the project. Never values.
cmd_names() {
- ensure_read_token
- INFISICAL_TOKEN="$READ_TOKEN" infisical secrets --projectId="$PROJECT_ID" \
+ ensure_read_token || return 1
+ INFISICAL_TOKEN="$READ_TOKEN" infisical_cli secrets --projectId="$PROJECT_ID" \
--env="$ENV_SLUG" --path="$SECRET_PATH" --silent --plain 2>/dev/null \
| grep -oE '^[A-Za-z_][A-Za-z0-9_]*' | sort -u
}
@@ -119,24 +120,27 @@ cmd_names() {
# Exit 0 if KEY exists in Infisical with a non-empty value.
cmd_has() {
local key="${1:?usage: has KEY}"
- cmd_names | grep -qx "$key"
+ validate_key "$key"
+ cmd_names | grep -Fxq -- "$key"
}
-# Read KEY's value from fleet-secrets without printing it.
+# Read KEY's synced environment value without printing it.
read_local_value() {
local key="$1" value
- value="$(fleet_value "$key")"
+ value="$(synced_value "$key")"
[ -n "$value" ] || return 1
printf '%s' "$value"
}
-# Copy SRC_KEY from fleet-secrets into this project's Infisical as DEST_KEY.
+# Copy synced SRC_KEY into this project's Infisical as DEST_KEY.
# The CLI reads the value from stdin using its supported @file input.
set_secret() {
local src="$1" dest="${2:-$1}" value
- value="$(read_local_value "$src")" || { note " SKIP $dest (source $src not available from fleet-secrets)"; return 1; }
- ensure_write_token
- if printf '%s' "$value" | INFISICAL_TOKEN="$WRITE_TOKEN" infisical secrets set "$dest=@/dev/stdin" \
+ validate_key "$src"
+ validate_key "$dest"
+ value="$(read_local_value "$src")" || { note " SKIP $dest (source $src not available in synced environment)"; return 1; }
+ ensure_write_token || return 1
+ if printf '%s' "$value" | INFISICAL_TOKEN="$WRITE_TOKEN" infisical_cli secrets set "$dest=@/dev/stdin" \
--projectId="$PROJECT_ID" \
--env="$ENV_SLUG" --path="$SECRET_PATH" --silent >/dev/null 2>/dev/null; then
note " OK $dest <- $src"
@@ -152,10 +156,9 @@ cmd_set() {
}
# Retired (OPS-818): `pull` copied an Infisical value into the flat local
-# secrets file, which nothing may read or edit by hand any more. Read a value
-# with `fleet-secrets get KEY` instead.
+# secrets file, which nothing may read or edit by hand any more.
cmd_pull() {
- die "pull is retired. Use: fleet-secrets get KEY"
+ die "pull is retired. Use an Infisical-synced environment value."
}
# Delete KEY(s) from Infisical. `infisical secrets delete` prints nothing
@@ -168,14 +171,16 @@ cmd_pull() {
# a shared secret silently does nothing, which looks like success.
cmd_delete() {
[ "$#" -gt 0 ] || die "usage: delete KEY [KEY...]"
- ensure_write_token
+ for key in "$@"; do validate_key "$key"; done
+ ensure_read_token || return 1
+ ensure_write_token || return 1
local rc=0
for key in "$@"; do
if ! cmd_has "$key"; then
note " SKIP $key (not present)"
continue
fi
- if INFISICAL_TOKEN="$WRITE_TOKEN" infisical secrets delete "$key" --type=shared \
+ if INFISICAL_TOKEN="$WRITE_TOKEN" infisical_cli secrets delete "$key" --type=shared \
--projectId="$PROJECT_ID" \
--env="$ENV_SLUG" --path="$SECRET_PATH" >/dev/null 2>/dev/null; then
if cmd_has "$key"; then
@@ -206,20 +211,15 @@ MAP=(
"SLACK_MCP_XOXB_TOKEN:SLACK_BOT_TOKEN"
"PUSHOVER_USAGE_API_TOKEN:PUSHOVER_USAGE_API_TOKEN"
"PUSHOVER_USER_KEY:PUSHOVER_USER_KEY"
- # GITHUB_TOKEN in the fleet-secrets store is dead (GitHub 401s it directly), but
- # GITHUB_MCP_TOKEN is live — verified 2026-08-12 against /rate_limit.
+ # Use the explicit synced source; do not substitute a generic GITHUB_TOKEN.
"GITHUB_MCP_TOKEN:GITHUB_TOKEN"
- # The project's stored copy went stale while the local one still logs in —
- # verified 2026-08-12 via universal-auth against app.infisical.com. This
- # was the single dead identity behind the prod Infisical card incident.
- "INFISICAL_ST_CLIENT_SECRET:INFISICAL_ST_CLIENT_SECRET"
)
# Deliberately NOT synced automatically — see the notes printed below.
HELD_BACK=(
- "SENTRY_READ_TOKEN already present and WORKING in prod; never overwrite with SENTRY_AUTH_TOKEN (wrong token type)"
- "STRIPE_SECRET_KEY Stripe itself says api_key_expired for the stored key; issue a fresh restricted read key first"
- "GITHUB_TOKEN (fleet-secrets copy) GitHub 401s it; the sync uses GITHUB_MCP_TOKEN instead — fix the store at leisure"
+ "SENTRY_READ_TOKEN never overwrite with SENTRY_AUTH_TOKEN (wrong token type)"
+ "STRIPE_SECRET_KEY requires separately qualified restricted read credentials"
+ "GITHUB_TOKEN the sync uses only the explicit GITHUB_MCP_TOKEN source"
"TWILIO_MCP_CREDS -> TWILIO_ACCOUNT_SID + TWILIO_AUTH_TOKEN one blob, needs splitting by hand"
"ASC_KEY_PATH -> ASC_PRIVATE_KEY source is a FILE PATH; prod needs the .p8 PEM CONTENTS"
"VERCEL_API_TOKEN intentionally absent; Vercel is not used by this fleet directly"
@@ -230,7 +230,7 @@ cmd_sync_platforms() {
[ "${1:-}" = "--dry-run" ] && dry=1
note "Infisical target: project ${PROJECT_ID} env=${ENV_SLUG} path=${SECRET_PATH}"
- note "Source: fleet-secrets"
+ note "Source: Infisical-synced environment"
note ""
if [ "$dry" = 1 ]; then
note "DRY RUN — nothing will be written. Planned copies:"
@@ -243,6 +243,7 @@ cmd_sync_platforms() {
fi
done
else
+ ensure_write_token || return 1
note "Writing ${#MAP[@]} secrets:"
for entry in "${MAP[@]}"; do
set_secret "${entry%%:*}" "${entry##*:}" || true
@@ -250,7 +251,7 @@ cmd_sync_platforms() {
fi
note ""
- note "Held back on purpose (copying these would move a broken credential):"
+ note "Held back on purpose (not copied automatically):"
for h in "${HELD_BACK[@]}"; do note " - $h"; done
note ""
note "Then redeploy so scripts/infisical-run.mjs injects them:"
@@ -272,14 +273,13 @@ infisical-secrets-safe.sh — value-blind Infisical access.
names list secret KEY NAMES only
has KEY exit 0 if KEY exists with a non-empty value
- set KEY [DEST_KEY] copy KEY from fleet-secrets into Infisical
- pull KEY [DEST_KEY] retired; use fleet-secrets get KEY
+ set KEY [DEST_KEY] copy a synced environment value into Infisical
+ pull KEY [DEST_KEY] retired; use synced environment values
delete KEY [KEY...] delete shared secret(s), verifying they are gone
sync-platforms [--dry-run] batch-copy the platform-status tokens
Credentials: use INFISICAL_UM_READ_TOKEN for names/has and
-INFISICAL_UM_WRITE_TOKEN for set/delete, or configure an explicit
-INFISICAL_UM_CLIENT_ID / INFISICAL_UM_CLIENT_SECRET project identity.
+INFISICAL_UM_WRITE_TOKEN for set/delete; service tokens are required.
USAGE
exit 2
;;
diff --git a/scripts/lib/automation-collector-token.mjs b/scripts/lib/automation-collector-token.mjs
deleted file mode 100644
index 08723dfaf..000000000
--- a/scripts/lib/automation-collector-token.mjs
+++ /dev/null
@@ -1,196 +0,0 @@
-import { execFileSync } from "node:child_process";
-
-/**
- * The Codex usage collector reads its ingest token with the System Keychain
- * automation identity, as permitted by the owner. No fleet-secrets
- * executable and no personal CLI session is used.
- *
- * This is a DIFFERENT mechanism from the eight scoped service tokens, which
- * read the owner's login keychain under the consumer's own grant name. The
- * automation identity lives in the System keychain, is shared, and is not a
- * per-consumer grant, so it stays exactly as it was.
- */
-
-const COLLECTOR_TOKEN_FOLDERS = ["/", "/global-api-keys"];
-const AUTOMATION_PROJECT = "8dae6d03-8f12-48b2-adf3-e5c1b881c8c5";
-
-function cleanAuthEnvironment(env) {
- const child = { ...env, INFISICAL_DOMAIN: "https://app.infisical.com" };
- for (const key of [
- "INFISICAL_API_URL",
- "INFISICAL_UNIVERSAL_AUTH_CLIENT_ID",
- "INFISICAL_UNIVERSAL_AUTH_CLIENT_SECRET",
- "INFISICAL_CLIENT_ID",
- "INFISICAL_CLIENT_SECRET",
- "INFISICAL_UNIVERSAL_AUTH_ACCESS_TOKEN",
- "INFISICAL_TOKEN",
- "TOKEN",
- "INFISICAL_AUTOMATION_CLIENT_ID",
- "INFISICAL_AUTOMATION_CLIENT_SECRET",
- ]) {
- delete child[key];
- }
- return child;
-}
-
-function automationEnvironment(env, exec) {
- const child = cleanAuthEnvironment(env);
- let clientId = "";
- let clientSecret = "";
- let access = "";
- const options = {
- encoding: "utf8",
- stdio: ["ignore", "pipe", "ignore"],
- timeout: 10000,
- killSignal: "SIGKILL",
- cwd: "/",
- env: child,
- maxBuffer: 65536,
- };
- try {
- const read = (account) =>
- exec(env.CODEX_SECURITY_BIN || "/usr/bin/security", [
- "find-generic-password",
- "-s",
- "fleet-secrets",
- "-a",
- account,
- "-w",
- "/Library/Keychains/System.keychain",
- ], options).trim();
- clientId = read("infisical-client-id");
- clientSecret = read("infisical-client-secret");
- if (!clientId || !clientSecret) throw Error("missing");
- const loginEnv = {
- ...child,
- INFISICAL_UNIVERSAL_AUTH_CLIENT_ID: clientId,
- INFISICAL_UNIVERSAL_AUTH_CLIENT_SECRET: clientSecret,
- };
- try {
- access = exec(env.INFISICAL_BIN || "/opt/homebrew/bin/infisical", [
- "login",
- "--method=universal-auth",
- "--plain",
- "--silent",
- ], { ...options, timeout: 15000, env: loginEnv }).trim();
- } finally {
- delete loginEnv.INFISICAL_UNIVERSAL_AUTH_CLIENT_ID;
- delete loginEnv.INFISICAL_UNIVERSAL_AUTH_CLIENT_SECRET;
- }
- if (!access || /\s/.test(access)) throw Error("invalid");
- child.INFISICAL_UNIVERSAL_AUTH_ACCESS_TOKEN = access;
- return child;
- } catch {
- throw new Error("Codex usage Infisical automation authentication failed");
- } finally {
- clientId = clientSecret = access = "";
- }
-}
-
-function scopedInfisicalRead(name, env, childEnv, exec) {
- if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) return null;
- const project = AUTOMATION_PROJECT;
- for (const folder of COLLECTOR_TOKEN_FOLDERS) {
- let out;
- try {
- out = exec(env.INFISICAL_BIN || "/opt/homebrew/bin/infisical", [
- "secrets",
- "get",
- name,
- "--plain",
- "--silent",
- "--telemetry=false",
- "--expand=true",
- "--env=prod",
- `--path=${folder}`,
- `--projectId=${project}`,
- ], {
- encoding: "utf8",
- stdio: ["ignore", "pipe", "ignore"],
- timeout: 15000,
- killSignal: "SIGKILL",
- env: childEnv,
- });
- } catch (err) {
- // Whitelisted diagnostics only - spawn code, timeout-kill, signal or
- // exit status; never err.stderr/cause/message (a CLI error can echo
- // its input).
- const sig = ["SIGKILL", "SIGTERM", "SIGINT", "SIGHUP"].includes(err.signal) ? err.signal : "unknown";
- const diag =
- err.code === "ETIMEDOUT"
- ? `deadline-killed(${sig})`
- : err.signal
- ? `signal(${sig})`
- : ["ENOENT", "EACCES", "EPERM", "ENOTDIR"].includes(err.code)
- ? `spawn(${err.code})`
- : Number.isInteger(err.status) && err.status >= 0 && err.status <= 255
- ? `status(${err.status})`
- : "status(unknown)";
- const hint = /^status\([0-9]+\)$/.test(diag) ? "; check the automation read permission" : "";
- const readError = new Error(`Infisical read failed for ${name} at ${folder} (${diag})${hint}`);
- // Trusted machine-readable tag: the ONLY channel callers may classify
- // on. diag is built exclusively from finite enums above, never from
- // CLI output, so this property can never carry secret material.
- readError.infisicalDiag = diag;
- throw readError;
- }
- const value = out.trim();
- if (/\$\{[^}]+\}/.test(value)) throw new Error(`Infisical returned an unresolved reference for ${name}`);
- if (value) return value;
- }
- return null; // confirmed absent in every folder
-}
-
-/**
- * Build the Codex ingest-token resolver.
- *
- * 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 and test compatibility,
- * but the default no longer touches the retired fleet-secrets CLI.
- */
-export function createAutomationCollectorTokenResolver(deps = {}) {
- const { exec = execFileSync } = deps;
- return function resolveCollectorToken(
- tokenEnvVarNames = ["USAGE_INGEST_TOKEN"],
- { env = process.env, fleetSecretsGet: lookup } = {},
- ) {
- let auth;
- let authError;
- let authAttempted = false;
- const effectiveLookup = lookup ?? ((name) => {
- if (!authAttempted) {
- authAttempted = true;
- try {
- auth = automationEnvironment(env, exec);
- } catch (error) {
- authError = error;
- }
- }
- if (authError) throw authError;
- return scopedInfisicalRead(name, env, auth, exec);
- });
- let deferredFailure = null;
- for (const name of tokenEnvVarNames) {
- const val = env[name]?.trim();
- if (val) return val;
- let fromLookup = null;
- try {
- fromLookup = effectiveLookup(name)?.trim();
- } catch (err) {
- // A remote read/auth failure is not a value and must never mask a
- // usable input under a later name (the retired helper returned null
- // on failure, so a later env token still won). The first failure is
- // 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;
- }
- if (fromLookup) return fromLookup;
- }
- if (deferredFailure) throw deferredFailure;
- return null;
- };
-}
diff --git a/scripts/lib/codex-run-session-token-collector.mjs b/scripts/lib/codex-run-session-token-collector.mjs
index 800dca626..5d8a72070 100644
--- a/scripts/lib/codex-run-session-token-collector.mjs
+++ b/scripts/lib/codex-run-session-token-collector.mjs
@@ -1,18 +1,17 @@
/**
* Codex usage collector token binding.
*
- * The Codex collector reads its ingest token with the System Keychain
- * automation identity, as permitted by the owner: no fleet-secrets
- * executable and no personal CLI session is used. That identity is shared
- * and is not a per-consumer grant, so it is neither one of the scoped
- * service tokens the other collectors use nor something the owner's login
- * keychain should hold.
- *
- * The read itself lives in scripts/lib/automation-collector-token.mjs; this
- * file holds only the binding, so it cannot drift from the shared library.
+ * Only Infisical-synced values injected for this consumer are accepted.
+ * Its own grant, injector and installed delivery require qualification;
+ * this binding never discovers credentials or authenticates at runtime.
*/
-import { createAutomationCollectorTokenResolver } from "./automation-collector-token.mjs";
+import { resolveCollectorToken as resolveInjectedToken } from "./run-session-token-collector.mjs";
export * from "./run-session-token-collector.mjs";
-export const resolveCollectorToken = createAutomationCollectorTokenResolver();
+export function resolveCollectorToken(names, options = {}) {
+ return resolveInjectedToken(names, {
+ ...options,
+ env: { ...(options.env ?? process.env), COLLECTOR_STRICT_INJECTED_SECRETS: "1" },
+ });
+}
diff --git a/scripts/lib/fleet-secrets.mjs b/scripts/lib/fleet-secrets.mjs
deleted file mode 100644
index 64666d6e5..000000000
--- a/scripts/lib/fleet-secrets.mjs
+++ /dev/null
@@ -1,166 +0,0 @@
-import { execFile, execFileSync } from "node:child_process";
-import { existsSync } from "node:fs";
-import { homedir } from "node:os";
-import { join } from "node:path";
-import { promisify } from "node:util";
-
-const execFileAsync = promisify(execFile);
-
-/**
- * Read one fleet secret through the Mac-side `fleet-secrets` CLI (OPS-818).
- *
- * Mac collectors and helper scripts call this AFTER checking their own
- * environment. It replaces the old read of the retired flat key file, which
- * nothing may read any more. Never use it from cloud, CI or Vercel code:
- * those get their values from the environment only.
- *
- * Root `/` is tried first, then `/global-api-keys`, because some names (for
- * example USAGE_INGEST_TOKEN) live only in that folder. The value is captured
- * from stdout and returned; it is never logged, and the CLI's stderr is
- * discarded. A missing binary, an absent key, a fetch failure or a timeout
- * all mean "absent" and return null, unless `strict` is set: then a transient
- * failure (anything but an absent key on every path) throws an error naming
- * the secret with the lookup failure as its cause, so a required secret is
- * never silently read as missing. The secret VALUE is never in the error.
- */
-export const FLEET_SECRETS_PATHS = ["/", "/global-api-keys"];
-
-/**
- * True when a `fleet-secrets` helper failure means "the key is absent".
- *
- * The CLI exits 3 for an absent key (surfaced as `status` by the sync
- * caller and as `code` by the promise caller, so both are checked).
- * Every other failure — exit 4 (fetch/auth), exit 5 (unresolved
- * reference), a timeout, a missing binary — is transient, not absence.
- */
-export function isSecretAbsentError(error) {
- return error?.status === 3 || error?.code === 3;
-}
-
-const cache = new Map();
-
-export function fleetSecretsBinary({ home = homedir(), exists = existsSync } = {}) {
- // A LaunchAgent's PATH is minimal, so prefer the absolute install location.
- const installed = join(home, ".local", "bin", "fleet-secrets");
- return exists(installed) ? installed : "fleet-secrets";
-}
-
-export function fleetSecretsGet(
- name,
- { exec = execFileSync, binary = fleetSecretsBinary(), paths = FLEET_SECRETS_PATHS, useCache = true, strict = false } = {},
-) {
- if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) return null;
- if (useCache && cache.has(name)) return cache.get(name);
- let value = null;
- let transient = null;
- for (const secretPath of paths) {
- try {
- const out = exec(binary, ["get", name, "--path", secretPath], {
- encoding: "utf8",
- stdio: ["ignore", "pipe", "ignore"],
- timeout: 30_000,
- maxBuffer: 1024 * 1024,
- });
- const trimmed = typeof out === "string" ? out.trim() : "";
- if (trimmed) {
- value = trimmed;
- break;
- }
- } catch (error) {
- // Exit 3 (absent): try the next path. Any other failure (fetch/auth
- // failure, timeout, missing binary) is recorded: with `strict` it is
- // thrown on the final path instead of reported as absent.
- if (!isSecretAbsentError(error)) transient = error;
- }
- }
- if (value === null && strict && transient) {
- const lookupError = new Error(`fleet secret "${name}" lookup failed`, { cause: transient });
- lookupError.secretName = name;
- throw lookupError;
- }
- if (useCache) cache.set(name, value);
- return value;
-}
-
-export function resetFleetSecretsCache() {
- cache.clear();
-}
-
-/**
- * The promise-based twin of `fleetSecretsGet`.
- *
- * `fleetSecretsGet` spawns the helper with `execFileSync`, which blocks the
- * event loop of the calling process for as long as the helper runs. That is
- * fine for a short-lived collector, and wrong for a long-running process
- * that also serves requests, so a long-running caller uses this instead.
- *
- * The same paths are tried in the same order and the same value is returned:
- * a missing binary, an absent key, a fetch failure or a timeout all mean
- * "absent" and return null, unless `strict` is set (see `fleetSecretsGet`).
- * The value is never logged. There is no cache
- * here: a caller that needs one memoizes the result itself, which is what
- * keeps a rotated secret visible to a running process.
- */
-export async function fleetSecretsGetAsync(
- name,
- { exec = execFileAsync, binary = fleetSecretsBinary(), paths = FLEET_SECRETS_PATHS, strict = false } = {},
-) {
- if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) return null;
- let value = null;
- let transient = null;
- for (const secretPath of paths) {
- try {
- const { stdout } = await exec(binary, ["get", name, "--path", secretPath], {
- encoding: "utf8",
- stdio: ["ignore", "pipe", "ignore"],
- timeout: 30_000,
- maxBuffer: 1024 * 1024,
- });
- const trimmed = typeof stdout === "string" ? stdout.trim() : "";
- if (trimmed) {
- value = trimmed;
- break;
- }
- } catch (error) {
- // Exit 3 (absent): try the next path. Any other failure is recorded
- // and, with `strict`, thrown on the final path (see `fleetSecretsGet`).
- if (!isSecretAbsentError(error)) transient = error;
- }
- }
- if (value === null && strict && transient) {
- const lookupError = new Error(`fleet secret "${name}" lookup failed`, { cause: transient });
- lookupError.secretName = name;
- throw lookupError;
- }
- return value;
-}
-
-/**
- * Key NAMES visible through `fleet-secrets names`, root plus the
- * /global-api-keys folder. Names only; never a value. Returns an empty Set
- * when the binary is missing or the fetch fails.
- */
-export function fleetSecretsNames({
- exec = execFileSync,
- binary = fleetSecretsBinary(),
- paths = FLEET_SECRETS_PATHS,
-} = {}) {
- const names = new Set();
- for (const secretPath of paths) {
- try {
- const out = exec(binary, ["names", "--path", secretPath], {
- encoding: "utf8",
- stdio: ["ignore", "pipe", "ignore"],
- timeout: 60_000,
- maxBuffer: 4 * 1024 * 1024,
- });
- for (const line of String(out).split(/\r?\n/)) {
- const name = line.trim();
- if (/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) names.add(name);
- }
- } catch {
- // Treat a failing path as contributing no names.
- }
- }
- return names;
-}
diff --git a/scripts/local-keys-bundle.mjs b/scripts/local-keys-bundle.mjs
index 67bc783d1..94ccd6d18 100644
--- a/scripts/local-keys-bundle.mjs
+++ b/scripts/local-keys-bundle.mjs
@@ -19,11 +19,11 @@
* - The passphrase comes from --passphrase-file (chmod 600), never argv.
*
* Subcommands:
- * list Print the provider -> source-env table and presence.
+ * list Print provider source-name presence, without checking usable values.
* build --passphrase-file --out
* [--providers a,b,c] [--config ]
* [--secrets-file ] [--iterations ]
- * Keys come from `fleet-secrets` (OPS-818). --secrets-file names a KEY=VALUE
+ * Keys come from Infisical-synced environment values. --secrets-file names a KEY=VALUE
* fixture file for tests; never point it at the retired flat secrets file.
* verify --passphrase-file
*/
@@ -34,8 +34,6 @@ import path from "node:path";
import process from "node:process";
import { fileURLToPath } from "node:url";
-import { fleetSecretsGet, fleetSecretsNames } from "./lib/fleet-secrets.mjs";
-
// ---------------------------------------------------------------------------
// THE MAP — catalog provider slug -> source env name(s) in the secrets file.
//
@@ -141,13 +139,13 @@ function sourceEnvNames() {
return names;
}
-/** Name -> value map for `build`: from a fixture file, else fleet-secrets. */
+/** Name -> value map for `build`: fixture file or allowlisted synced environment. */
function readSecretsMap(secretsPath) {
if (secretsPath === undefined) {
const map = new Map();
for (const name of sourceEnvNames()) {
- const value = fleetSecretsGet(name);
- if (value) map.set(name, value);
+ const value = process.env[name];
+ if (typeof value === "string") map.set(name, value);
}
return map;
}
@@ -160,14 +158,10 @@ function readSecretsMap(secretsPath) {
return parseSecretsFile(text);
}
-/** Names only for `list`: values never leave the store. */
+/** Names only for `list`: default presence checks never read environment values. */
function readSecretNames(secretsPath) {
if (secretsPath === undefined) {
- const names = fleetSecretsNames();
- if (names.size === 0) {
- throw new CliError("fleet-secrets returned no key names. Run: fleet-secrets doctor");
- }
- return names;
+ return new Set([...sourceEnvNames()].filter((name) => Object.hasOwn(process.env, name)));
}
return new Set(readSecretsMap(secretsPath).keys());
}
@@ -366,9 +360,8 @@ export function resolveProvider(source, secretsMap) {
function cmdList(args) {
const secretsPath = args.get("--secrets-file");
- // Names only: `fleet-secrets names` never returns a value, and a fixture
- // file's values are discarded at the parse boundary, so nothing
- // value-bearing can reach the console below.
+ // Default presence checks use key membership only; fixture values are
+ // discarded at the parse boundary before the printed table is built.
const presentNames = readSecretNames(secretsPath);
const rows = PROVIDER_SOURCES.map((source) => {
const presence = providerPresence(source, presentNames);
@@ -383,9 +376,10 @@ function cmdList(args) {
const providerWidth = Math.max(8, ...rows.map((row) => row.provider.length));
const sourceWidth = Math.max(10, ...rows.map((row) => row.source.length));
console.log("Local Keys Bundle — Provider Sources");
- console.log(`Secrets source: ${secretsPath ?? "fleet-secrets"} (names checked, values never printed)`);
+ console.log(`Secrets source: ${secretsPath ?? "Infisical-synced environment"} (names checked, values never printed)`);
+ console.log("Present means the name exists; it does not verify a usable value.");
console.log("");
- console.log(` ${"Provider".padEnd(providerWidth)} ${"Source Env".padEnd(sourceWidth)} Status`);
+ console.log(` ${"Provider".padEnd(providerWidth)} ${"Source Env".padEnd(sourceWidth)} Name Presence`);
for (const row of rows) {
console.log(` ${row.provider.padEnd(providerWidth)} ${row.source.padEnd(sourceWidth)} ${row.status}`);
}
diff --git a/scripts/muse-usage-collector.mjs b/scripts/muse-usage-collector.mjs
index fa670bbf3..9dfd2d74e 100755
--- a/scripts/muse-usage-collector.mjs
+++ b/scripts/muse-usage-collector.mjs
@@ -32,7 +32,7 @@
// SECRETS: this script reads the CLI binary's stdout but never logs it raw --
// the resolved percentages, window labels, and ISO reset dates are the only
// numbers that leave the process. Tokens are loaded from the environment or
-// `fleet-secrets get` via resolveCollectorToken and only used as Bearer
+// an explicit Infisical service-token lookup via resolveCollectorToken and only used as Bearer
// headers in outbound HTTP requests; the value is never logged.
import { execFile } from "node:child_process";
diff --git a/scripts/namecheap.py b/scripts/namecheap.py
index 3717ab9cf..97aa07c93 100755
--- a/scripts/namecheap.py
+++ b/scripts/namecheap.py
@@ -3,8 +3,8 @@
Namecheap API client & CLI for AI Agents and fleet operations.
Allows querying account balances, listing domains, checking availability, and viewing DNS records.
-The account username (sent as both ApiUser and UserName) is resolved from
-$NAMECHEAP_API_USER or `fleet-secrets get NAMECHEAP_API_USER`, exactly like the API key — it is
+The account username (sent as both ApiUser and UserName) is resolved from the
+Infisical-synced $NAMECHEAP_API_USER environment value, exactly like the API key — it is
never hardcoded here (this repo is public; account details live in the private
fleet-ops ATTACK-MAP.md). A wrong username makes the API return error 1011102
"API Key is invalid", even when the key itself is fine.
@@ -19,8 +19,6 @@
import argparse
import json
import os
-import shutil
-import subprocess
import sys
import urllib.parse
import urllib.request
@@ -32,21 +30,6 @@ def _read_secret(name):
if val:
return val.strip().strip("\"'")
- # OPS-818: the retired flat key file is no longer read. Fall back to the
- # Mac-side fleet-secrets CLI; stdout is captured and never logged.
- binary = shutil.which("fleet-secrets") or os.path.expanduser("~/.local/bin/fleet-secrets")
- for secret_path in ("/", "/global-api-keys"):
- try:
- result = subprocess.run(
- [binary, "get", name, "--path", secret_path],
- capture_output=True,
- text=True,
- timeout=30,
- )
- except (OSError, subprocess.SubprocessError):
- return None
- if result.returncode == 0 and result.stdout.strip():
- return result.stdout.strip().strip("\"'")
return None
@@ -76,12 +59,12 @@ def call_namecheap(command, params=None, api_user=None, api_key=None, client_ip=
if not api_key:
api_key = get_api_key()
if not api_key:
- raise ValueError("NAMECHEAP_API_KEY not found in environment or `fleet-secrets get`")
+ raise ValueError("NAMECHEAP_API_KEY required in the Infisical-synced environment")
if not api_user:
api_user = get_api_user()
if not api_user:
- raise ValueError("NAMECHEAP_API_USER not found in environment or `fleet-secrets get`")
+ raise ValueError("NAMECHEAP_API_USER required in the Infisical-synced environment")
if not client_ip:
client_ip = get_public_ip()
@@ -235,7 +218,7 @@ def cmd_dns(args):
def main():
parser = argparse.ArgumentParser(description="Namecheap API CLI for Agents & Fleet Operations")
- parser.add_argument("--user", default=None, help="Namecheap username (default: $NAMECHEAP_API_USER or `fleet-secrets get NAMECHEAP_API_USER`)")
+ parser.add_argument("--user", default=None, help="Namecheap username (default: Infisical-synced $NAMECHEAP_API_USER)")
parser.add_argument("--ip", default=None, help="Whitelisted client IP (default: auto-detected public IP)")
parser.add_argument("--json", action="store_true", help="Output raw JSON")
diff --git a/scripts/ops/mac-server-watchdog.sh b/scripts/ops/mac-server-watchdog.sh
index efe192ef3..0dde933e9 100755
--- a/scripts/ops/mac-server-watchdog.sh
+++ b/scripts/ops/mac-server-watchdog.sh
@@ -6,29 +6,19 @@
set -euo pipefail
INGEST_URL="${INGEST_URL:-https://usage.jays.services/api/ingest/mac-heartbeat}"
-FLEET_SECRETS_BIN="${FLEET_SECRETS_BIN:-/Users/jay/.local/bin/fleet-secrets}"
# Prefer the scoped heartbeat token (a `mac-host:` entry in the
# monitor's USAGE_INGEST_PRODUCER_TOKENS); the unscoped USAGE_INGEST_TOKEN is
# refused once USAGE_INGEST_REQUIRE_SCOPED_TOKENS=true.
#
-# OPS-818: the retired flat key file is no longer read. A name missing from
-# the environment comes from `fleet-secrets get` (root, then the
-# /global-api-keys folder); the value is captured, never echoed.
-read_secret() {
- [[ -x "$FLEET_SECRETS_BIN" ]] || return 0
- "$FLEET_SECRETS_BIN" get "$1" --path / 2>/dev/null \
- || "$FLEET_SECRETS_BIN" get "$1" --path /global-api-keys 2>/dev/null \
- || true
-}
+# Accept only explicitly injected Infisical-synced values for this consumer.
+# The legacy environment alias does not establish a producer-scoped grant.
TOKEN="${MAC_HEARTBEAT_INGEST_TOKEN:-}"
-[[ -n "$TOKEN" ]] || TOKEN="$(read_secret MAC_HEARTBEAT_INGEST_TOKEN)"
-[[ -n "$TOKEN" ]] || TOKEN="${USAGE_INGEST_TOKEN:-}"
-[[ -n "$TOKEN" ]] || TOKEN="$(read_secret USAGE_INGEST_TOKEN)"
+[[ "$TOKEN" =~ [^[:space:]] ]] || TOKEN="${USAGE_INGEST_TOKEN:-}"
-if [[ -z "$TOKEN" ]]; then
- echo "Error: MAC_HEARTBEAT_INGEST_TOKEN / USAGE_INGEST_TOKEN not found in environment or fleet-secrets" >&2
+if ! [[ "$TOKEN" =~ [^[:space:]] ]]; then
+ echo "Error: MAC_HEARTBEAT_INGEST_TOKEN / USAGE_INGEST_TOKEN required in the Infisical-synced environment" >&2
exit 1
fi
diff --git a/scripts/subscription-quota-collector.mjs b/scripts/subscription-quota-collector.mjs
index df95d8fb0..fb7930f6b 100644
--- a/scripts/subscription-quota-collector.mjs
+++ b/scripts/subscription-quota-collector.mjs
@@ -36,8 +36,8 @@
// GBU_INGEST_TOKEN (gbu).
// Each falls back to SUBSCRIPTION_QUOTA_INGEST_TOKEN, then USAGE_INGEST_TOKEN
// (unscoped; refused once USAGE_INGEST_REQUIRE_SCOPED_TOKENS=true). Every
-// name is read from the environment first, then `fleet-secrets get`
-// via resolveCollectorToken.
+// name is read from the environment first, then through the collector's
+// scoped reader via resolveCollectorToken.
// USAGE_MONITOR_INGEST_URL (default https://usage.jays.services/api/ingest/usage)
// CLAUDE_CODE_OAUTH_CREDENTIALS_JSON — Claude Code OAuth credential JSON
// (same shape as ~/.claude/.credentials.json). The LaunchAgent injects it
diff --git a/scripts/test-infisical-secrets-safe.sh b/scripts/test-infisical-secrets-safe.sh
index 015994b1c..075fdc041 100644
--- a/scripts/test-infisical-secrets-safe.sh
+++ b/scripts/test-infisical-secrets-safe.sh
@@ -1,118 +1,193 @@
#!/usr/bin/env bash
-# Offline auth-routing checks for infisical-secrets-safe.sh.
+# Offline auth and synced-source checks; no inherited credentials or real stores.
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
SRC="$ROOT/scripts/infisical-secrets-safe.sh"
TMP="$(mktemp -d)"
trap 'rm -rf "$TMP"' EXIT
-mkdir -p "$TMP/bin"
-
+mkdir -p "$TMP/bin" "$TMP/home"
fail() { printf 'FAIL %s\n' "$*" >&2; exit 1; }
-
NODE_BIN="$(command -v node || true)"
[ -n "$NODE_BIN" ] || fail "node runtime must be available before PATH isolation"
ln -s "$NODE_BIN" "$TMP/bin/node"
-cat >"$TMP/bin/infisical" <<'MOCK'
-#!/usr/bin/env bash
+cat >"$TMP/run.mjs" <<'FIXTURE'
+import { spawnSync } from "node:child_process";
+import { appendFileSync } from "node:fs";
+const result = spawnSync("/bin/bash", process.argv.slice(2), {
+ env: process.env, encoding: "utf8", timeout: 15000, killSignal: "SIGKILL", maxBuffer: 128 * 1024,
+});
+if (result.error || result.signal || result.status === null) throw new Error("Fixture child failed to complete");
+appendFileSync(process.env.FIXTURE_OUTPUT, result.stdout + result.stderr);
+process.stdout.write(result.stdout);
+process.stderr.write(result.stderr);
+process.exitCode = result.status;
+FIXTURE
+cat >"$TMP/bin/infisical" <<'FIXTURE'
+#!/bin/bash
set -euo pipefail
-case "${1:-}" in
- login)
- printf 'login\n' >>"$INFISICAL_MOCK_LOG"
- printf 'mock-session'
- exit 0
+[ "${1:-}" = secrets ] || { printf 'unexpected-command\n' >>"$FIXTURE_CALLS"; exit 99; }
+[ "${INFISICAL_DOMAIN:-}" = "${FIXTURE_ORIGIN:-https://app.infisical.com}" ] || { printf 'unexpected-origin\n' >>"$FIXTURE_CALLS"; exit 88; }
+for selector in INFISICAL_API_URL INFISICAL_BASE_URL TOKEN INFISICAL_CLIENT_ID INFISICAL_CLIENT_SECRET INFISICAL_UNIVERSAL_AUTH_CLIENT_ID INFISICAL_UNIVERSAL_AUTH_CLIENT_SECRET INFISICAL_UNIVERSAL_AUTH_ACCESS_TOKEN INFISICAL_AUTOMATION_CLIENT_ID INFISICAL_AUTOMATION_CLIENT_SECRET INFISICAL_UM_CLIENT_ID INFISICAL_UM_CLIENT_SECRET INFISICAL_UM_READ_TOKEN INFISICAL_UM_WRITE_TOKEN; do
+ [ -z "${!selector+x}" ] || { printf 'unexpected-auth-selector\n' >>"$FIXTURE_CALLS"; exit 87; }
+done
+printf 'cli-origin %s\n' "$INFISICAL_DOMAIN" >>"$FIXTURE_CALLS"
+for argument in "$@"; do
+ case "$argument" in *fake-source*|*fake-platform*|*fake-github*|*fake-retired*|*st.read*|*st.write*) exit 90 ;; esac
+done
+for flag in --projectId=project-fixture --env=prod --path=/; do
+ [[ " $* " == *" $flag "* ]] || exit 89
+done
+case "${INFISICAL_TOKEN:-}" in
+ st.read) purpose=read ;;
+ st.write) purpose=write ;;
+ *) printf 'unexpected-auth\n' >>"$FIXTURE_CALLS"; exit 98 ;;
+esac
+operation="${2:-names}"
+[[ "$operation" != --projectId=* ]] || operation=names
+case "$operation" in
+ names)
+ [ "$purpose" = read ] || exit 97
+ if [ -e "$FIXTURE_DELETED" ]; then printf 'SECOND=fake-remote\n';
+ else printf 'FIRST=fake-remote\nSECOND=fake-remote\n'; fi
;;
- secrets)
- operation="${2:-names}"
- [[ "$operation" != --projectId=* ]] || operation="names"
- case "$operation" in
- names)
- if [ -e "$INFISICAL_MOCK_DELETED" ]; then
- printf 'SECOND=value\n'
- else
- printf 'FIRST=value\nSECOND=value\n'
- fi
- ;;
- set)
- [ "${3:-}" = 'SOURCE_KEY=@/dev/stdin' ] || exit 4
- [ "$(cat)" = 'local-value' ] || exit 5
- ;;
- delete) : >"$INFISICAL_MOCK_DELETED" ;;
- *) printf 'unexpected infisical command\n' >&2; exit 2 ;;
+ set)
+ [ "$purpose" = write ] || exit 96
+ case "${3:-}" in
+ SOURCE_KEY=@/dev/stdin) expected=fake-source ;;
+ UPTIMEROBOT_API_KEY=@/dev/stdin) expected=fake-platform ;;
+ GITHUB_TOKEN=@/dev/stdin) expected=fake-github ;;
+ *) printf 'unexpected-destination\n' >>"$FIXTURE_CALLS"; exit 95 ;;
esac
- printf '%s %s\n' "$operation" "${INFISICAL_TOKEN:-none}" >>"$INFISICAL_MOCK_LOG"
+ [ "$(cat)" = "$expected" ] || exit 94
;;
- *) printf 'unexpected infisical command\n' >&2; exit 2 ;;
-esac
-MOCK
-cat >"$TMP/bin/fleet-secrets" <<'MOCK'
-#!/usr/bin/env bash
-case "${2:-}" in
- SOURCE_KEY) printf 'local-value' ;;
+ delete)
+ [ "$purpose" = write ] && [ "${3:-}" = FIRST ] || exit 93
+ [[ " $* " == *' --type=shared '* ]] || exit 92
+ : >"$FIXTURE_DELETED"
+ ;;
+ *) printf 'unexpected-operation\n' >>"$FIXTURE_CALLS"; exit 91 ;;
esac
-MOCK
-chmod +x "$TMP/bin/infisical" "$TMP/bin/fleet-secrets"
-export PATH="$TMP/bin:/usr/bin:/bin"
-export INFISICAL_PROJECT_ID="project-test"
-export INFISICAL_MOCK_LOG="$TMP/calls.log"
-export INFISICAL_MOCK_DELETED="$TMP/deleted"
-cat >"$TMP/fetch.mjs" <<'MOCK'
-globalThis.fetch = async () => new Response(JSON.stringify({workspace:"project-test",permissions:[process.env.MOCK_PERMISSION || "read"],scopes:[{environment:"prod",secretPath:process.env.MOCK_PATH || "/"}],expiresAt:null}));
-MOCK
-
-bash -n "$SRC" || fail "bash -n"
-
-INFISICAL_UM_READ_TOKEN="read-fake" bash "$SRC" names >/dev/null
-grep -qx 'names read-fake' "$INFISICAL_MOCK_LOG" || fail "names did not use the read token"
-NODE_OPTIONS="--import=$TMP/fetch.mjs" INFISICAL_UM_READ_TOKEN="st.fake-read" bash "$SRC" names >/dev/null
-grep -qx 'names st.fake-read' "$INFISICAL_MOCK_LOG" || fail "metadata-verified read token was not used"
-if NODE_OPTIONS="--import=$TMP/fetch.mjs" MOCK_PATH="/wrong" INFISICAL_UM_READ_TOKEN="st.fake-read" bash "$SRC" names >/dev/null 2>&1; then
- fail "wrong-folder metadata was accepted"
-fi
-if NODE_OPTIONS="--import=$TMP/fetch.mjs" INFISICAL_UM_WRITE_TOKEN="st.fake-read-only" bash "$SRC" set SOURCE_KEY >/dev/null 2>&1; then
- fail "read-only metadata was accepted for a write"
-fi
-
-NODE_OPTIONS="--import=$TMP/fetch.mjs" MOCK_PERMISSION="write" INFISICAL_UM_WRITE_TOKEN="st.fake-write" bash "$SRC" set SOURCE_KEY >/dev/null
-grep -qx 'set st.fake-write' "$INFISICAL_MOCK_LOG" || fail "set did not use the write token"
+printf '%s %s\n' "$operation" "$purpose" >>"$FIXTURE_CALLS"
+[ "$operation" != set ] || printf 'destination %s\n' "${3%%=*}" >>"$FIXTURE_CALLS"
+FIXTURE
+for trap_name in fleet-secrets security; do
+ cat >"$TMP/bin/$trap_name" <<'FIXTURE'
+#!/bin/sh
+printf 'retired-reader\n' >>"$FIXTURE_CALLS"
+exit 99
+FIXTURE
+done
+chmod +x "$TMP/bin/infisical" "$TMP/bin/fleet-secrets" "$TMP/bin/security"
+cat >"$TMP/fetch.mjs" <<'FIXTURE'
+import { appendFileSync } from "node:fs";
+globalThis.fetch = async (url, options) => {
+ // This replaces fetch before the actual verifier loads; it never opens a socket.
+ const origin = process.env.FIXTURE_ORIGIN || "https://app.infisical.com";
+ if (String(url) !== origin + "/api/v2/service-token" || options.redirect !== "error") throw new Error("Unexpected fixture metadata destination");
+ appendFileSync(process.env.FIXTURE_CALLS, "metadata-origin " + origin + "\n");
+ const authHeader = options.headers.authorization;
+ const permission = authHeader === "Bearer st.read" ? "read" : authHeader === "Bearer st.write" ? "write" : null;
+ appendFileSync(process.env.FIXTURE_CALLS, "metadata " + (permission || "unexpected") + "\n");
+ if (!permission) throw new Error("Unexpected fixture metadata authentication");
+ return new Response(JSON.stringify({ workspace: "project-fixture", permissions: [process.env.FIXTURE_PERMISSION || permission], scopes: [{ environment: "prod", secretPath: process.env.FIXTURE_PATH || "/" }], expiresAt: "2999-01-01T00:00:00Z" }));
+};
+FIXTURE
-NODE_OPTIONS="--import=$TMP/fetch.mjs" MOCK_PERMISSION="write" INFISICAL_UM_READ_TOKEN="read-fake" INFISICAL_UM_WRITE_TOKEN="st.fake-write" \
- bash "$SRC" delete FIRST >/dev/null
-grep -qx 'delete st.fake-write' "$INFISICAL_MOCK_LOG" || fail "delete did not use the write token"
-[ "$(grep -c '^names read-fake$' "$INFISICAL_MOCK_LOG")" -eq 3 ] \
- || fail "delete did not verify through the read token before and after"
+run_helper() {
+ local inputs=()
+ while [ "$#" -gt 0 ] && [ "$1" != -- ]; do inputs+=("$1"); shift; done
+ [ "${1:-}" = -- ] || fail "fixture requires argument separator"
+ shift
+ env -i PATH="$TMP/bin:/usr/bin:/bin" HOME="$TMP/home" \
+ NODE_OPTIONS="--import=$TMP/fetch.mjs" INFISICAL_UM_PROJECT_ID=project-fixture \
+ INFISICAL_DOMAIN=https://wrong.invalid TOKEN=fake-alt \
+ INFISICAL_CLIENT_ID=fixture-client INFISICAL_CLIENT_SECRET=fixture-secret \
+ INFISICAL_UM_CLIENT_ID=fixture-client INFISICAL_UM_CLIENT_SECRET=fixture-secret \
+ INFISICAL_UNIVERSAL_AUTH_CLIENT_ID=fixture-client INFISICAL_UNIVERSAL_AUTH_CLIENT_SECRET=fixture-secret \
+ INFISICAL_UNIVERSAL_AUTH_ACCESS_TOKEN=fake-access \
+ INFISICAL_AUTOMATION_CLIENT_ID=fixture-client INFISICAL_AUTOMATION_CLIENT_SECRET=fixture-secret \
+ FIXTURE_CALLS="$TMP/calls" FIXTURE_DELETED="$TMP/deleted" FIXTURE_OUTPUT="$TMP/all-output" \
+ SOURCE_KEY=fake-source "${inputs[@]}" "$NODE_BIN" "$TMP/run.mjs" "$SRC" "$@"
+}
+clear_calls() { : >"$TMP/calls"; }
+expect_no_auth() {
+ local expected="$1"; shift
+ clear_calls
+ if run_helper "$@" >"$TMP/out" 2>"$TMP/err"; then fail "unsafe binding unexpectedly succeeded"; fi
+ grep -Fq -- "$expected" "$TMP/err" || fail "missing fixed refusal diagnostic"
+ [ ! -s "$TMP/calls" ] || fail "refused input reached metadata, CLI or a retired reader"
+}
-if INFISICAL_UM_READ_TOKEN="read-fake" bash "$SRC" set SOURCE_KEY >/dev/null 2>&1; then
- fail "a read token was accepted for set"
-fi
-[ "$(grep -c '^set ' "$INFISICAL_MOCK_LOG")" -eq 1 ] \
- || fail "set ran without a write-capable credential"
+bash -n "$SRC" || fail "bash syntax"
+clear_calls
+run_helper INFISICAL_UM_READ_TOKEN=st.read -- names >"$TMP/out" || fail "CLI transport disagreed with verified metadata"
+grep -qx 'metadata read' "$TMP/calls" && grep -qx 'names read' "$TMP/calls" || fail "verified read route"
+grep -qx FIRST "$TMP/out" && grep -qx SECOND "$TMP/out" || fail "names-only output"
+run_helper INFISICAL_TOKEN=st.read -- has FIRST >/dev/null || fail "service-token read alias"
-INFISICAL_UM_CLIENT_ID="um-id" INFISICAL_UM_CLIENT_SECRET="um-secret" \
- bash "$SRC" names >/dev/null
-grep -qx 'names mock-session' "$INFISICAL_MOCK_LOG" || fail "explicit UM machine identity was not retained"
-INFISICAL_UM_CLIENT_ID="um-id" INFISICAL_UM_CLIENT_SECRET="um-secret" \
- bash "$SRC" set SOURCE_KEY >/dev/null
-grep -qx 'set mock-session' "$INFISICAL_MOCK_LOG" || fail "explicit UM machine identity write was not retained"
+clear_calls
+if run_helper INFISICAL_UM_READ_TOKEN=st.read FIXTURE_PATH=/wrong -- names >/dev/null 2>&1; then fail "wrong-folder metadata accepted"; fi
+grep -qx 'metadata read' "$TMP/calls" || fail "wrong-folder fixture did not reach real verifier"
+if grep -q '^names ' "$TMP/calls"; then fail "wrong-folder metadata reached CLI"; fi
+clear_calls
+if run_helper INFISICAL_UM_WRITE_TOKEN=st.write FIXTURE_PERMISSION=read -- set SOURCE_KEY >/dev/null 2>&1; then fail "read-only metadata accepted for write"; fi
+if grep -q '^set ' "$TMP/calls"; then fail "wrong permission reached write"; fi
-if INFISICAL_TOKEN="generic-read-bearer" bash "$SRC" set SOURCE_KEY >/dev/null 2>&1; then
- fail "generic read bearer was accepted for set"
-fi
-if INFISICAL_UM_WRITE_TOKEN="opaque-bearer" bash "$SRC" set SOURCE_KEY >/dev/null 2>&1; then
- fail "opaque bearer falsely attested write permissions"
-fi
-[ "$(grep -c '^set ' "$INFISICAL_MOCK_LOG")" -eq 2 ] || fail "unverified bearer reached a write"
+clear_calls
+run_helper INFISICAL_TOKEN=st.read INFISICAL_UM_READ_TOKEN=st.read INFISICAL_UM_WRITE_TOKEN=st.write -- set SOURCE_KEY >"$TMP/out"
+grep -qx 'metadata write' "$TMP/calls" && grep -qx 'set write' "$TMP/calls" || fail "verified stdin write"
+clear_calls
+run_helper INFISICAL_UM_READ_TOKEN=st.read INFISICAL_UM_WRITE_TOKEN=st.write -- delete FIRST >"$TMP/out"
+grep -qx 'delete write' "$TMP/calls" || fail "shared delete route"
+[ "$(grep -c '^names read$' "$TMP/calls")" -eq 2 ] || fail "delete must verify presence before and after"
-if INFISICAL_CLIENT_ID="generic-id" INFISICAL_CLIENT_SECRET="generic-secret" \
- bash "$SRC" names >/dev/null 2>&1; then
- fail "generic machine-identity credentials were accepted"
-fi
+expect_no_auth 'INFISICAL_UM_READ_TOKEN service token required' -- names
+expect_no_auth 'INFISICAL_UM_WRITE_TOKEN service token required' INFISICAL_TOKEN=st.read -- set SOURCE_KEY
+expect_no_auth 'INFISICAL_UM_READ_TOKEN service token required' INFISICAL_UM_READ_TOKEN=opaque-fixture INFISICAL_UM_CLIENT_ID=fixture-client INFISICAL_UM_CLIENT_SECRET=fixture-secret -- names
+expect_no_auth 'INFISICAL_UM_WRITE_TOKEN service token required' INFISICAL_UM_WRITE_TOKEN=opaque-fixture -- set SOURCE_KEY
+expect_no_auth 'INFISICAL_UM_READ_TOKEN service token required' INFISICAL_UM_CLIENT_ID=fixture-client INFISICAL_UM_CLIENT_SECRET=fixture-secret -- names
+expect_no_auth 'INFISICAL_UM_WRITE_TOKEN service token required' INFISICAL_UM_CLIENT_ID=fixture-client INFISICAL_UM_CLIENT_SECRET=fixture-secret -- set SOURCE_KEY
+expect_no_auth 'Invalid secret key name.' INFISICAL_UM_WRITE_TOKEN=st.write -- set 'SOURCE_KEY;false'
+expect_no_auth 'Invalid secret key name.' INFISICAL_UM_WRITE_TOKEN=st.write -- set SOURCE_KEY --bad
+expect_no_auth 'Invalid secret key name.' INFISICAL_UM_READ_TOKEN=st.read -- has '[A-Z]*'
+expect_no_auth 'Invalid secret key name.' INFISICAL_UM_WRITE_TOKEN=st.write -- delete FIRST 'bad key'
+expect_no_auth 'INFISICAL_UM_WRITE_TOKEN service token required' UPTIMEROBOT_API_KEY=fake-platform -- sync-platforms
+expect_no_auth 'INFISICAL_UM_WRITE_TOKEN service token required' INFISICAL_UM_WRITE_TOKEN=opaque-fixture UPTIMEROBOT_API_KEY=fake-platform -- sync-platforms
+expect_no_auth 'INFISICAL_UM_READ_TOKEN service token required' INFISICAL_UM_WRITE_TOKEN=st.write -- delete FIRST
+expect_no_auth 'INFISICAL_UM_READ_TOKEN service token required' INFISICAL_UM_READ_TOKEN=opaque-fixture INFISICAL_UM_WRITE_TOKEN=st.write -- delete FIRST
+expect_no_auth 'INFISICAL_UM_WRITE_TOKEN service token required' -- sync-platforms
+expect_no_auth 'Infisical target configuration rejected.' INFISICAL_BASE_URL=https://wrong.invalid INFISICAL_UM_READ_TOKEN=st.read -- names
-if grep -q 'INFISICAL_AUTOMATION_' "$SRC"; then
- fail "shared Automation credentials remain in the helper"
-fi
-if grep -q '\${INFISICAL_CLIENT_ID:-\|\${INFISICAL_CLIENT_SECRET:-' "$SRC"; then
- fail "generic machine-identity credentials remain in the helper"
-fi
+for region in app us eu; do
+ origin="https://$region.infisical.com"
+ case "$region" in
+ app) targets=("INFISICAL_BASE_URL=$origin/api") ;;
+ us) targets=("INFISICAL_API_URL=$origin/api") ;;
+ eu) targets=("INFISICAL_BASE_URL=$origin/api" "INFISICAL_API_URL=https://wrong.invalid") ;;
+ esac
+ clear_calls
+ rm -f "$TMP/deleted"
+ run_helper "FIXTURE_ORIGIN=$origin" "${targets[@]}" INFISICAL_UM_WRITE_TOKEN=st.write -- set SOURCE_KEY >"$TMP/out" || fail "regional write transport"
+ run_helper "FIXTURE_ORIGIN=$origin" "${targets[@]}" INFISICAL_UM_READ_TOKEN=st.read INFISICAL_UM_WRITE_TOKEN=st.write -- delete FIRST >"$TMP/out" || fail "regional read/delete transport"
+ [ "$(grep -Fxc "metadata-origin $origin" "$TMP/calls")" -eq 3 ] || fail "regional metadata origin mismatch"
+ [ "$(grep -Fxc "cli-origin $origin" "$TMP/calls")" -eq 4 ] || fail "regional CLI origin mismatch"
+done
-printf 'ok infisical-secrets-safe offline auth checks\n'
+clear_calls
+if run_helper SOURCE_KEY= -- set SOURCE_KEY >"$TMP/out"; then fail "empty synced source accepted"; fi
+grep -Fq 'not available in synced environment' "$TMP/out" || fail "source absence diagnostic"
+[ ! -s "$TMP/calls" ] || fail "absent source attempted authentication"
+clear_calls
+run_helper INFISICAL_UM_WRITE_TOKEN=st.write UPTIMEROBOT_API_KEY=fake-platform GITHUB_MCP_TOKEN=fake-github INFISICAL_ST_CLIENT_SECRET=fake-retired -- sync-platforms >"$TMP/out"
+[ "$(grep -c '^set write$' "$TMP/calls")" -eq 2 ] || fail "fixed platform map did not copy only present supported sources"
+if grep -q 'INFISICAL_ST_CLIENT_SECRET\|retired-reader\|unexpected-' "$TMP/calls"; then fail "retired source or reader reached"; fi
+grep -Fq 'Held back on purpose (not copied automatically)' "$TMP/out" || fail "held-back warning disappeared"
+clear_calls
+run_helper UPTIMEROBOT_API_KEY=fake-platform -- sync-platforms --dry-run >"$TMP/out"
+[ ! -s "$TMP/calls" ] || fail "dry run authenticated or wrote"
+for value in fake-source fake-platform fake-github fake-retired fake-remote opaque-fixture fake-alt fixture-client fixture-secret fake-access st.read st.write; do
+ if grep -Fq "$value" "$TMP/all-output" "$TMP/calls"; then fail "fixture value disclosed"; fi
+done
+if grep -q 'fleet-secrets\|universal-auth\|INFISICAL_ST_CLIENT_SECRET' "$SRC"; then fail "retired source remains active in helper"; fi
+printf 'ok infisical-secrets-safe offline synced-source and service-token checks\n'
diff --git a/scripts/test-local-collector-runtime.mjs b/scripts/test-local-collector-runtime.mjs
index f3d04bb93..76d9f4974 100755
--- a/scripts/test-local-collector-runtime.mjs
+++ b/scripts/test-local-collector-runtime.mjs
@@ -1,7 +1,7 @@
#!/usr/bin/env node
import { execFileSync as rawExecFileSync, spawnSync as rawSpawnSync } from "node:child_process";
import { chmodSync, closeSync, constants, cpSync, existsSync, fstatSync, lstatSync, mkdtempSync, mkdirSync, openSync, readFileSync, readlinkSync, readdirSync, realpathSync, renameSync, rmSync, symlinkSync, truncateSync, writeFileSync } from "node:fs";
-import { createHash } from "node:crypto";
+import { createHash, randomUUID } from "node:crypto";
import { deflateSync } from "node:zlib";
import { tmpdir } from "node:os";
import { basename, dirname, join } from "node:path";
@@ -768,17 +768,31 @@ syncBuiltinESMExports();\n`);
const oldAfterRefresh = spawnSync(process.execPath, [updater, "--sha", firstSha, "--runtime-root", runtime], { env, encoding: "utf8" });
assert(oldAfterRefresh.status !== 0 && readlinkSync(join(runtime, "current")) === thirdRelease, "refreshed overlay cannot forward-activate an old commit");
const configuredLauncher = join(runtime, "current", "scripts", "collector-injector.mjs");
- const invalidLauncher = spawnSync(process.execPath, [configuredLauncher, "bad"], { encoding: "utf8" });
+ const invalidLauncher = spawnSync(process.execPath, [configuredLauncher, "bad"], { encoding: "utf8", timeout: 15000 });
assert(invalidLauncher.status !== 0, "symlinked configured launcher rejects invalid arguments");
const custody = join(root, "custody.json");
- const marker = join(root, "login-reached");
+ const marker = join(root, "service-token-requests");
+ const childMarker = join(root, "collector-spawned");
const hook = join(root, "mock-fetch.mjs");
- writeFileSync(custody, JSON.stringify({ clientId: "test-id", clientSecret: "test-sentinel-secret" }), { mode: 0o600 });
- writeFileSync(hook, "import { writeFileSync } from 'node:fs'; globalThis.fetch = async () => { writeFileSync(process.env.TEST_MARKER, 'reached'); return new Response('{}'); };\n");
- const testEnv = Object.fromEntries(Object.entries(process.env).filter(([key]) => !key.startsWith("INFISICAL_") && key !== "NODE_OPTIONS"));
- const mocked = spawnSync(process.execPath, ["--import", hook, configuredLauncher, "muse-code", "machine-identity", custody, "--dry-run"], { encoding: "utf8", env: { ...testEnv, TEST_MARKER: marker } });
- assert(mocked.status !== 0 && existsSync(marker), "symlinked launcher reaches mocked login after rollback");
- assert(!(mocked.stdout + mocked.stderr).includes("test-sentinel-secret"), "symlinked launcher never prints custody values");
+ const fixtureToken = `st.${randomUUID()}`;
+ writeFileSync(custody, JSON.stringify({ token: fixtureToken }), { mode: 0o600 });
+ writeFileSync(hook, `import { writeFileSync } from 'node:fs'; import cp from 'node:child_process'; import { syncBuiltinESMExports } from 'node:module';
+const calls = [];
+cp.spawn = () => { writeFileSync(process.env.TEST_CHILD_MARKER, 'forbidden'); throw new Error('child must not start'); }; syncBuiltinESMExports();
+globalThis.fetch = async (input, options) => {
+ const url = new URL(input);
+ calls.push(url.pathname); writeFileSync(process.env.TEST_MARKER, JSON.stringify(calls));
+ if (url.origin !== 'https://app.infisical.com' || options.headers.authorization !== 'Bearer ' + process.env.TEST_SERVICE_TOKEN || options.redirect !== 'error') throw new Error('unexpected request');
+ if (calls.length === 1 && url.pathname === '/api/v2/service-token') return new Response(JSON.stringify({ workspace: '86e35e51-91bc-4dfd-a045-4484726b9c40', permissions: ['read'], scopes: [{ environment: 'prod', secretPath: '/telemetry' }], expiresAt: '2999-01-01T00:00:00Z' }));
+ if (calls.length === 2 && url.pathname === '/api/v3/secrets/raw' && url.searchParams.get('workspaceId') === '86e35e51-91bc-4dfd-a045-4484726b9c40' && url.searchParams.get('environment') === 'prod' && url.searchParams.get('secretPath') === '/telemetry') return new Response(JSON.stringify({ secrets: [] }));
+ throw new Error('unexpected request');
+};\n`);
+ const mocked = spawnSync(process.execPath, ["--import", hook, configuredLauncher, "muse-code", "service-token", custody, "--dry-run"], { encoding: "utf8", env: { PATH: process.env.PATH, TEST_MARKER: marker, TEST_CHILD_MARKER: childMarker, TEST_SERVICE_TOKEN: fixtureToken }, timeout: 15000 });
+ assert(mocked.status === 1 && existsSync(marker), "symlinked launcher reaches service-token metadata after rollback");
+ assert(JSON.stringify(JSON.parse(readFileSync(marker, "utf8"))) === JSON.stringify(["/api/v2/service-token", "/api/v3/secrets/raw"]), "valid finite metadata precedes controlled missing-secrets refusal without login");
+ assert(!existsSync(childMarker), "missing secrets refuse before launching the collector");
+ assert(mocked.stdout === "" && mocked.stderr.trim() === "Collector credential injection failed.", "missing secrets emit only the fixed diagnostic");
+ assert(!(mocked.stdout + mocked.stderr).includes(fixtureToken), "symlinked launcher never prints custody values");
const invalid = spawnSync(
process.execPath,
diff --git a/scripts/test_ops_synced_credentials.py b/scripts/test_ops_synced_credentials.py
new file mode 100644
index 000000000..cd0297c75
--- /dev/null
+++ b/scripts/test_ops_synced_credentials.py
@@ -0,0 +1,192 @@
+"""Offline credential checks; never run either operational entrypoint."""
+
+import contextlib
+import importlib.util
+import io
+import os
+from pathlib import Path
+import signal
+import subprocess
+import tempfile
+import unittest
+from unittest import mock
+
+
+SCRIPTS = Path(__file__).resolve().parent
+
+
+class IsolatedOpsFixture(unittest.TestCase):
+ def setUp(self):
+ temporary = tempfile.TemporaryDirectory(prefix="ops-synced-credentials-")
+ self.addCleanup(temporary.cleanup)
+ self.home = Path(temporary.name)
+ self.bin = self.home / ".local" / "bin"
+ self.bin.mkdir(parents=True)
+ self.marker = self.home / "unexpected-operation"
+ for name in (
+ "fleet-secrets", "infisical", "security", "curl", "id", "tailscale",
+ "jq", "sed", "head", "awk", "sw_vers", "sysctl", "uname", "top",
+ "iostat", "vm_stat", "df", "pgrep", "ps", "pm2", "launchctl", "date",
+ ):
+ executable = self.bin / name
+ executable.write_text(
+ '#!/bin/sh\nprintf invoked >> "$FIXTURE_OPS_MARKER"\nexit 97\n',
+ encoding="utf-8",
+ )
+ executable.chmod(0o700)
+ self.environment = {
+ "HOME": str(self.home), "PATH": str(self.bin), "LC_ALL": "C",
+ "FIXTURE_OPS_MARKER": str(self.marker),
+ "FLEET_SECRETS_BIN": str(self.bin / "fleet-secrets"),
+ }
+
+ def tearDown(self):
+ self.assertFalse(self.marker.exists(), "credential or operational trap ran")
+
+
+class NamecheapSyncedCredentialsTests(IsolatedOpsFixture):
+ def setUp(self):
+ super().setUp()
+ self.stack = contextlib.ExitStack()
+ self.addCleanup(self.stack.close)
+ self.stack.enter_context(mock.patch.dict(os.environ, self.environment, clear=True))
+ self.guards = [
+ self.stack.enter_context(mock.patch(target, side_effect=AssertionError("unexpected operation")))
+ for target in (
+ "urllib.request.urlopen", "socket.getaddrinfo", "socket.create_connection",
+ "subprocess.Popen", "os.system",
+ )
+ ]
+ self.stdout = self.stack.enter_context(contextlib.redirect_stdout(io.StringIO()))
+ self.stderr = self.stack.enter_context(contextlib.redirect_stderr(io.StringIO()))
+ spec = importlib.util.spec_from_file_location("namecheap_credential_fixture", SCRIPTS / "namecheap.py")
+ self.module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(self.module)
+
+ def tearDown(self):
+ for guard in self.guards:
+ guard.assert_not_called()
+ self.assertEqual(self.stdout.getvalue(), "")
+ self.assertEqual(self.stderr.getvalue(), "")
+ super().tearDown()
+
+ def test_actual_getters_preserve_environment_quote_and_space_normalization(self):
+ os.environ.update({
+ "NAMECHEAP_API_KEY": ' "fixture-namecheap-key" ',
+ "NAMECHEAP_API_USER": " 'fixture-namecheap-user' ",
+ })
+ self.assertEqual(self.module.get_api_key(), "fixture-namecheap-key")
+ self.assertEqual(self.module.get_api_user(), "fixture-namecheap-user")
+
+ def test_actual_getters_follow_changed_then_removed_environment_values(self):
+ os.environ["NAMECHEAP_API_KEY"] = "fixture-first-key"
+ self.assertEqual(self.module.get_api_key(), "fixture-first-key")
+ os.environ["NAMECHEAP_API_KEY"] = "fixture-changed-key"
+ self.assertEqual(self.module.get_api_key(), "fixture-changed-key")
+ del os.environ["NAMECHEAP_API_KEY"]
+ self.assertIsNone(self.module.get_api_key())
+ self.assertIsNone(self.module.get_api_user())
+
+ def test_missing_and_blank_tuple_refuses_before_ip_discovery_or_api(self):
+ cases = (
+ ({}, "NAMECHEAP_API_KEY"),
+ ({"NAMECHEAP_API_USER": "fixture-namecheap-user"}, "NAMECHEAP_API_KEY"),
+ ({"NAMECHEAP_API_KEY": "fixture-namecheap-key"}, "NAMECHEAP_API_USER"),
+ ({"NAMECHEAP_API_KEY": " \t", "NAMECHEAP_API_USER": "fixture-namecheap-user"}, "NAMECHEAP_API_KEY"),
+ ({"NAMECHEAP_API_KEY": "fixture-namecheap-key", "NAMECHEAP_API_USER": '""'}, "NAMECHEAP_API_USER"),
+ ({"INFISICAL_TOKEN": "st.other", "USAGE_INGEST_TOKEN": "fixture-other-token"}, "NAMECHEAP_API_KEY"),
+ )
+ for values, missing in cases:
+ with self.subTest(missing=missing), mock.patch.dict(os.environ, {**self.environment, **values}, clear=True):
+ with mock.patch.object(self.module, "get_public_ip", side_effect=AssertionError("unexpected IP discovery")) as discover:
+ with self.assertRaises(ValueError) as error:
+ self.module.call_namecheap("namecheap.users.getBalances")
+ self.assertEqual(str(error.exception), f"{missing} required in the Infisical-synced environment")
+ discover.assert_not_called()
+
+ def test_explicit_api_credentials_skip_environment_getters_before_transport(self):
+ class StopBeforeTransport(Exception):
+ pass
+
+ with mock.patch.object(self.module, "get_api_key", side_effect=AssertionError("unexpected key lookup")) as key:
+ with mock.patch.object(self.module, "get_api_user", side_effect=AssertionError("unexpected user lookup")) as user:
+ with mock.patch.object(self.module, "get_public_ip", side_effect=StopBeforeTransport):
+ with self.assertRaises(StopBeforeTransport):
+ self.module.call_namecheap(
+ "namecheap.users.getBalances", api_user="fixture-explicit-user", api_key="fake-key",
+ )
+ key.assert_not_called()
+ user.assert_not_called()
+
+
+class WatchdogSyncedCredentialsTests(IsolatedOpsFixture):
+ def setUp(self):
+ super().setUp()
+ source = (SCRIPTS / "ops" / "mac-server-watchdog.sh").read_text(encoding="utf-8")
+ start = "set -euo pipefail\n"
+ end = '\nHOSTNAME="jays.services"\n'
+ self.assertEqual(source.count(start), 1)
+ self.assertEqual(source.count(end), 1)
+ self.assertLess(source.index(start), source.index(end))
+ # Only the actual auth prefix is executable here; all probes and POSTs
+ # are beyond the unique end marker and never enter the child program.
+ self.prefix = source[source.index(start):source.index(end)]
+
+ def run_prefix(self, values, expected=None):
+ environment = {
+ **self.environment,
+ "INGEST_URL": "http://127.0.0.1:9/unused-fixture",
+ **values,
+ }
+ program = self.prefix
+ if expected is not None:
+ environment["FIXTURE_EXPECTED_TOKEN"] = expected
+ program += '\n[[ "$TOKEN" == "$FIXTURE_EXPECTED_TOKEN" ]] || exit 91\n'
+ program += '[[ "$INGEST_URL" == "http://127.0.0.1:9/unused-fixture" ]] || exit 92\n'
+ with subprocess.Popen(
+ ["/bin/bash", "-s"], stdin=subprocess.PIPE, stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE, text=True, env=environment,
+ ) as child:
+ try:
+ stdout, stderr = child.communicate(program, timeout=15)
+ except subprocess.TimeoutExpired:
+ child.send_signal(signal.SIGKILL)
+ child.communicate(timeout=5)
+ self.fail("Watchdog auth fixture exceeded its 15 second deadline")
+ self.assertGreaterEqual(child.returncode, 0, "auth fixture terminated by signal")
+ self.assertEqual(stdout, "")
+ self.assertFalse(self.marker.exists(), "auth prefix attempted an external command")
+ for value in values.values():
+ if value.strip():
+ self.assertNotIn(value, stderr)
+ return child.returncode, stderr
+
+ def test_dedicated_value_wins_and_legacy_explicit_environment_alias_remains(self):
+ cases = (
+ ({"MAC_HEARTBEAT_INGEST_TOKEN": "fixture-dedicated"}, "fixture-dedicated"),
+ ({"USAGE_INGEST_TOKEN": "fixture-legacy"}, "fixture-legacy"),
+ ({"MAC_HEARTBEAT_INGEST_TOKEN": "fixture-dedicated", "USAGE_INGEST_TOKEN": "fixture-legacy"}, "fixture-dedicated"),
+ ({"MAC_HEARTBEAT_INGEST_TOKEN": " \t", "USAGE_INGEST_TOKEN": "fixture-legacy"}, "fixture-legacy"),
+ )
+ for values, expected in cases:
+ with self.subTest(names=tuple(values)):
+ self.assertEqual(self.run_prefix(values, expected), (0, ""))
+
+ def test_missing_or_blank_values_refuse_before_any_probe_or_lookup(self):
+ for values in ({}, {"MAC_HEARTBEAT_INGEST_TOKEN": ""}, {"MAC_HEARTBEAT_INGEST_TOKEN": " \t", "USAGE_INGEST_TOKEN": "\n "}):
+ with self.subTest(names=tuple(values)):
+ status, stderr = self.run_prefix(values)
+ self.assertEqual(status, 1)
+ self.assertEqual(stderr.strip(), "Error: MAC_HEARTBEAT_INGEST_TOKEN / USAGE_INGEST_TOKEN required in the Infisical-synced environment")
+
+ def test_unrelated_bootstrap_never_becomes_a_heartbeat_credential(self):
+ status, stderr = self.run_prefix({
+ "INFISICAL_TOKEN": "st.other", "TOKEN": "fixture-ambient-token",
+ "INFISICAL_UNIVERSAL_AUTH_CLIENT_ID": "fixture-client", "INFISICAL_UNIVERSAL_AUTH_CLIENT_SECRET": "fixture-secret",
+ })
+ self.assertEqual(status, 1)
+ self.assertIn("MAC_HEARTBEAT_INGEST_TOKEN / USAGE_INGEST_TOKEN", stderr)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/src/lib/__tests__/local-keys-bundle.test.ts b/src/lib/__tests__/local-keys-bundle.test.ts
index 51c2dbc3b..cd42f376c 100644
--- a/src/lib/__tests__/local-keys-bundle.test.ts
+++ b/src/lib/__tests__/local-keys-bundle.test.ts
@@ -10,6 +10,7 @@ import {
encryptPayload,
EXCLUDED_PROVIDERS,
PROVIDER_SOURCES,
+ runCli as runBundleCli,
} from "../../../scripts/local-keys-bundle.mjs";
const SCRIPT_PATH = path.resolve(__dirname, "../../../scripts/local-keys-bundle.mjs");
@@ -41,11 +42,21 @@ const TEST_ITERATIONS = 100000;
let tempDirectory: string;
let passphraseFile: string;
let secretsFile: string;
+let trapDirectory: string;
+let readerMarker: string;
-function runCli(args: string[]) {
- const result = spawnSync(process.execPath, [SCRIPT_PATH, ...args], {
- encoding: "utf8",
+function runNode(args: string[], syncedEnv: Record = {}) {
+ const childEnv: NodeJS.ProcessEnv = {
+ ...syncedEnv,
+ HOME: tempDirectory, PATH: trapDirectory, FIXTURE_READER_MARKER: readerMarker,
+ NODE_ENV: "test", VITEST: "true",
+ };
+ const result = spawnSync(process.execPath, args, {
+ encoding: "utf8", timeout: 15000, killSignal: "SIGKILL", maxBuffer: 128 * 1024,
+ env: childEnv,
});
+ if (result.error || result.signal || result.status === null) throw new Error("Bundle fixture child failed to complete");
+ expect(fs.existsSync(readerMarker)).toBe(false);
return {
status: result.status,
stdout: result.stdout ?? "",
@@ -54,6 +65,30 @@ function runCli(args: string[]) {
};
}
+function runCli(args: string[], syncedEnv: Record = {}) {
+ return runNode([SCRIPT_PATH, ...args], syncedEnv);
+}
+
+function runInProcess(args: string[], syncedEnv: Record = {}) {
+ const savedEnv = process.env;
+ const savedLog = console.log;
+ const lines: string[] = [];
+ try {
+ process.env = {
+ ...syncedEnv,
+ HOME: tempDirectory, PATH: trapDirectory, FIXTURE_READER_MARKER: readerMarker,
+ NODE_ENV: "test", VITEST: "true",
+ };
+ console.log = (...data: unknown[]) => { lines.push(data.map(String).join(" ")); };
+ expect(runBundleCli(args)).toBe(0);
+ expect(fs.existsSync(readerMarker)).toBe(false);
+ return lines.join("\n");
+ } finally {
+ process.env = savedEnv;
+ console.log = savedLog;
+ }
+}
+
function expectNoSecretValues(text: string) {
for (const value of FAKE_VALUES) {
expect(text).not.toContain(value);
@@ -62,6 +97,12 @@ function expectNoSecretValues(text: string) {
beforeAll(() => {
tempDirectory = fs.mkdtempSync(path.join(os.tmpdir(), "local-keys-bundle-test-"));
+ trapDirectory = path.join(tempDirectory, ".local", "bin");
+ fs.mkdirSync(trapDirectory, { recursive: true });
+ readerMarker = path.join(tempDirectory, "reader-invoked");
+ for (const name of ["fleet-secrets", "infisical", "security"]) {
+ fs.writeFileSync(path.join(trapDirectory, name), '#!/bin/sh\nprintf invoked >> "$FIXTURE_READER_MARKER"\nexit 99\n', { mode: 0o700 });
+ }
passphraseFile = path.join(tempDirectory, "passphrase.txt");
fs.writeFileSync(passphraseFile, `${ROUND_TRIP_PASSPHRASE}\n`, { mode: 0o600 });
secretsFile = path.join(tempDirectory, "fixture-secrets");
@@ -266,3 +307,212 @@ describe("local-keys-bundle mapping table", () => {
expect(new Set(mapped).size).toBe(mapped.length);
});
});
+
+describe("local-keys-bundle synced environment", () => {
+ it("keeps isolation controls fixed in the actual child when synced fields collide", () => {
+ const result = runNode(["--input-type=module", "-e", 'console.log(JSON.stringify(Object.fromEntries(["HOME", "PATH", "FIXTURE_READER_MARKER", "NODE_ENV", "VITEST"].map(name => [name, process.env[name]]))))'], {
+ HOME: "fixture-home", PATH: "fixture-path", FIXTURE_READER_MARKER: "fixture-marker",
+ NODE_ENV: "production", VITEST: "false",
+ });
+ expect(result.status).toBe(0);
+ expect(JSON.parse(result.stdout)).toEqual({
+ HOME: tempDirectory, PATH: trapDirectory, FIXTURE_READER_MARKER: readerMarker,
+ NODE_ENV: "test", VITEST: "true",
+ });
+ });
+
+ it("lists only catalog key presence, including empty values, without reading values", () => {
+ const result = runCli(["list"], { OPENAI_ADMIN_KEY: "", UNRELATED_FIXTURE_SECRET: "fixture-unrelated-value" });
+ expect(result.status).toBe(0);
+ expect(result.stdout).toContain("Name Presence");
+ expect(result.stdout).toContain("Present means the name exists; it does not verify a usable value.");
+ expect(result.stdout).toMatch(/openai\s+OPENAI_ADMIN_KEY\s+Present/);
+ expect(result.stdout).toMatch(/openrouter\s+OPENROUTER_ADMIN_KEY\s+Absent/);
+ expect(result.combined).not.toContain("UNRELATED_FIXTURE_SECRET");
+ expect(result.combined).not.toContain("fixture-unrelated-value");
+
+ const savedEnv = process.env;
+ const savedLog = console.log;
+ const lines: string[] = [];
+ try {
+ const presenceEnv: NodeJS.ProcessEnv = { NODE_ENV: "test", VITEST: "true" };
+ process.env = Object.defineProperty(presenceEnv, "OPENAI_ADMIN_KEY", {
+ enumerable: true, get() { throw new Error("list must never read a provider value"); },
+ });
+ console.log = (...data: unknown[]) => { lines.push(data.map(String).join(" ")); };
+ expect(runBundleCli(["list"])).toBe(0);
+ } finally {
+ process.env = savedEnv;
+ console.log = savedLog;
+ }
+ expect(lines.join("\n")).toMatch(/openai\s+OPENAI_ADMIN_KEY\s+Present/);
+ });
+
+ it("builds and verifies only the fixed catalog's synced values with private output", () => {
+ const outPath = path.join(tempDirectory, "synced.umkeys");
+ const result = runCli(["build", "--passphrase-file", passphraseFile, "--out", outPath, "--iterations", String(TEST_ITERATIONS)], {
+ OPENROUTER_ADMIN_KEY: FAKE_OPENROUTER,
+ OPENAI_ADMIN_KEY: "", ANTHROPIC_ADMIN_KEY: " \t ",
+ XAI_MANAGEMENT_KEY: FAKE_XAI, XAI_TEAM_ID: FAKE_XAI_TEAM,
+ BACKBLAZE_MASTER_KEY_ID: FAKE_B2_KEY_ID, BACKBLAZE_MASTER_APPLICATION_KEY: FAKE_B2_APP_KEY,
+ UNRELATED_FIXTURE_SECRET: "fixture-unrelated-value",
+ INFISICAL_TOKEN: "st.fixture-bootstrap", INFISICAL_UM_CLIENT_SECRET: "fixture-retired-value",
+ });
+ expect(result.status).toBe(0);
+ expectNoSecretValues(result.combined);
+ expect(result.combined).not.toContain("fixture-unrelated-value");
+ expect(result.combined).not.toContain("fixture-retired-value");
+ const descriptor = fs.openSync(outPath, "r");
+ let envelopeText: string;
+ try {
+ expect(fs.fstatSync(descriptor).mode & 0o777).toBe(0o600);
+ envelopeText = fs.readFileSync(descriptor, "utf8");
+ } finally {
+ fs.closeSync(descriptor);
+ }
+ const payload = decryptEnvelope(JSON.parse(envelopeText), ROUND_TRIP_PASSPHRASE);
+ expect(payload.secrets).toEqual([
+ { provider: "openrouter", apiKey: FAKE_OPENROUTER },
+ { provider: "xai", apiKey: FAKE_XAI, teamId: FAKE_XAI_TEAM },
+ { provider: "backblaze", apiKey: `${FAKE_B2_KEY_ID}:${FAKE_B2_APP_KEY}` },
+ ]);
+ expect(runCli(["verify", "--passphrase-file", passphraseFile, outPath]).status).toBe(0);
+ });
+
+ it("refuses an absent or partial catalog without a reader call or partial output", () => {
+ const cases: Array> = [{}, { XAI_MANAGEMENT_KEY: FAKE_XAI }, { BACKBLAZE_MASTER_KEY_ID: FAKE_B2_KEY_ID }];
+ for (const [index, env] of cases.entries()) {
+ const outPath = path.join(tempDirectory, `absent-${index}.umkeys`);
+ const result = runCli(["build", "--passphrase-file", passphraseFile, "--out", outPath, "--iterations", String(TEST_ITERATIONS)], env);
+ expect(result.status).toBe(1);
+ expect(result.stderr).toContain("No provider keys found to bundle");
+ expectNoSecretValues(result.combined);
+ expect(fs.existsSync(outPath)).toBe(false);
+ }
+ const listed = runCli(["list"], { XAI_MANAGEMENT_KEY: FAKE_XAI });
+ expect(listed.stdout).toContain("Partial (XAI_MANAGEMENT_KEY is set but XAI_TEAM_ID is missing)");
+ expect(fs.readdirSync(tempDirectory).filter((name) => name.includes(".tmp-"))).toEqual([]);
+ });
+
+ it("keeps explicit fixture-file precedence over synced values", () => {
+ const outPath = path.join(tempDirectory, "fixture-precedence.umkeys");
+ const result = runCli(["build", "--passphrase-file", passphraseFile, "--out", outPath, "--providers", "openrouter", "--secrets-file", secretsFile, "--iterations", String(TEST_ITERATIONS)], {
+ OPENROUTER_ADMIN_KEY: "fixture-env-must-not-win",
+ });
+ expect(result.status).toBe(0);
+ const payload = decryptEnvelope(JSON.parse(fs.readFileSync(outPath, "utf8")), ROUND_TRIP_PASSPHRASE);
+ expect(payload.secrets).toEqual([{ provider: "openrouter", apiKey: FAKE_OPENROUTER }]);
+ });
+
+ for (const [label, value] of Object.entries({ empty: "", whitespace: " \t\n " })) {
+ it(`refuses ${label} provider values without writing a bundle`, () => {
+ const outPath = path.join(tempDirectory, `blank-${label}.umkeys`);
+ const result = runCli(["build", "--passphrase-file", passphraseFile, "--out", outPath, "--iterations", String(TEST_ITERATIONS)], {
+ OPENAI_ADMIN_KEY: value,
+ });
+ expect(result.status).toBe(1);
+ expect(result.stderr).toContain("No provider keys found to bundle");
+ expectNoSecretValues(result.combined);
+ expect(fs.existsSync(outPath)).toBe(false);
+ expect(fs.readdirSync(tempDirectory).filter((name) => name.includes(".tmp-"))).toEqual([]);
+ });
+ }
+});
+
+describe("local-keys-bundle in-process CLI boundaries", () => {
+ it("builds and verifies the complete synced catalog with private atomic output and config", () => {
+ const syncedEnv: Record = {};
+ for (const source of PROVIDER_SOURCES) {
+ if (source.apiKeyEnv) syncedEnv[source.apiKeyEnv] = FAKE_OPENROUTER;
+ if (source.teamIdEnv) syncedEnv[source.teamIdEnv] = FAKE_XAI_TEAM;
+ for (const name of source.compositeEnvs ?? []) syncedEnv[name] = FAKE_B2_APP_KEY;
+ }
+ const configPath = path.join(tempDirectory, "in-process-config.json");
+ const config = { format: "usage-monitor-local-export", formatVersion: 1, providers: [] };
+ fs.writeFileSync(configPath, JSON.stringify(config), { mode: 0o600 });
+ const outPath = path.join(tempDirectory, "in-process.umkeys");
+ const output = runInProcess(["build", "--passphrase-file", passphraseFile, "--out", outPath,
+ "--config", configPath, "--iterations", String(TEST_ITERATIONS)], syncedEnv);
+ expect(output).toContain(`Included providers (${PROVIDER_SOURCES.length})`);
+ expectNoSecretValues(output);
+ const descriptor = fs.openSync(outPath, "r");
+ try {
+ expect(fs.fstatSync(descriptor).mode & 0o777).toBe(0o600);
+ const payload = decryptEnvelope(JSON.parse(fs.readFileSync(descriptor, "utf8")), ROUND_TRIP_PASSPHRASE);
+ expect(payload.config).toEqual(config);
+ expect(payload.secrets.map((secret: { provider: string }) => secret.provider)).toEqual(PROVIDER_SOURCES.map((source: { provider: string }) => source.provider));
+ } finally {
+ fs.closeSync(descriptor);
+ }
+ const verified = runInProcess(["verify", "--passphrase-file", passphraseFile, outPath]);
+ expect(verified).toContain(`Providers (${PROVIDER_SOURCES.length})`);
+ expect(verified).toContain("Config section embedded: yes");
+ expectNoSecretValues(verified);
+ expect(fs.readdirSync(tempDirectory).filter((name) => name.includes(".tmp-"))).toEqual([]);
+ });
+
+ it("uses the explicit fixture source for names and selected build values", () => {
+ const fixturePath = path.join(tempDirectory, "in-process-secrets");
+ fs.writeFileSync(fixturePath, `# fixture\nignored line\nexport OPENROUTER_ADMIN_KEY='${FAKE_OPENROUTER}'\nXAI_MANAGEMENT_KEY=${FAKE_XAI}\nBACKBLAZE_MASTER_KEY_ID=${FAKE_B2_KEY_ID}\n`, { mode: 0o600 });
+ const listed = runInProcess(["list", "--secrets-file", fixturePath]);
+ expect(listed).toContain("Partial (missing BACKBLAZE_MASTER_APPLICATION_KEY)");
+ expect(listed).toContain("Partial (XAI_MANAGEMENT_KEY is set but XAI_TEAM_ID is missing)");
+ expectNoSecretValues(listed);
+ const outPath = path.join(tempDirectory, "in-process-fixture.umkeys");
+ const output = runInProcess(["build", "--passphrase-file", passphraseFile, "--out", outPath,
+ "--providers", " openrouter, ", "--secrets-file", fixturePath, "--iterations", String(TEST_ITERATIONS)],
+ { OPENROUTER_ADMIN_KEY: "fixture-other" });
+ expectNoSecretValues(output);
+ expect(decryptEnvelope(JSON.parse(fs.readFileSync(outPath, "utf8")), ROUND_TRIP_PASSPHRASE).secrets).toEqual([{ provider: "openrouter", apiKey: FAKE_OPENROUTER }]);
+ });
+
+ it("refuses absent, blank, and partial synced tuples before creating any output", () => {
+ const outPath = path.join(tempDirectory, "in-process-refused.umkeys");
+ const cases: Array> = [{}, { OPENAI_ADMIN_KEY: " \t " },
+ { XAI_MANAGEMENT_KEY: FAKE_XAI }, { BACKBLAZE_MASTER_KEY_ID: FAKE_B2_KEY_ID }];
+ for (const env of cases) {
+ expect(() => runInProcess(["build", "--passphrase-file", passphraseFile, "--out", outPath], env)).toThrow(/No provider keys found/);
+ expect(fs.existsSync(outPath)).toBe(false);
+ }
+ expect(fs.readdirSync(tempDirectory).filter((name) => name.includes(".tmp-"))).toEqual([]);
+ });
+
+ it("removes its temporary file if the atomic rename fails", () => {
+ const outPath = path.join(tempDirectory, "existing-directory");
+ fs.mkdirSync(outPath);
+ expect(() => runInProcess(["build", "--passphrase-file", passphraseFile, "--out", outPath,
+ "--iterations", String(TEST_ITERATIONS)], { OPENROUTER_ADMIN_KEY: FAKE_OPENROUTER })).toThrow(/EISDIR|ENOTDIR/);
+ expect(fs.readdirSync(outPath)).toEqual([]);
+ expect(fs.readdirSync(tempDirectory).filter((name) => name.includes(".tmp-"))).toEqual([]);
+ });
+
+ it("rejects invalid source, config, passphrase, and CLI inputs without output", () => {
+ const outPath = path.join(tempDirectory, "invalid-input.umkeys");
+ const base = ["build", "--passphrase-file", passphraseFile, "--out", outPath];
+ const missingPath = path.join(tempDirectory, "missing-fixture");
+ const invalidConfig = path.join(tempDirectory, "invalid-config.json");
+ fs.writeFileSync(invalidConfig, "{}", { mode: 0o600 });
+ const emptyPassphrase = path.join(tempDirectory, "empty-passphrase");
+ fs.writeFileSync(emptyPassphrase, "\n", { mode: 0o600 });
+ const publicPassphrase = path.join(tempDirectory, "public-passphrase");
+ fs.writeFileSync(publicPassphrase, "fixture-pass", { mode: 0o600 });
+ fs.chmodSync(publicPassphrase, 0o644);
+ const cases: Array<[string[], RegExp]> = [
+ [[], /Usage:/], [["list", "--unknown"], /Unknown flag/], [["list", "--secrets-file"], /needs a value/],
+ [["build"], /Missing required flag/], [[...base, "--providers", "twilio"], /is excluded/],
+ [[...base, "--providers", "fixture"], /Unknown provider/], [[...base, "--config", missingPath], /missing or not valid JSON/],
+ [[...base, "--config", invalidConfig], /complete/], [[...base, "--secrets-file", missingPath], /Cannot read secrets file/],
+ [["build", "--passphrase-file", missingPath, "--out", outPath], /Cannot read passphrase/],
+ [["build", "--passphrase-file", emptyPassphrase, "--out", outPath], /Passphrase file is empty/],
+ [["build", "--passphrase-file", publicPassphrase, "--out", outPath], /group- or world-readable/],
+ [[...base, "--iterations", "0"], /below the minimum/], [[...base, "--iterations", "999999999"], /above the maximum/],
+ [[...base, "--iterations", "fixture"], /must be an integer/], [["verify", "--passphrase-file", passphraseFile], /Usage: verify/],
+ [["verify", "--passphrase-file", passphraseFile, missingPath], /missing or not valid JSON/],
+ ];
+ for (const [args, error] of cases) {
+ expect(() => runInProcess(args, { OPENROUTER_ADMIN_KEY: FAKE_OPENROUTER })).toThrow(error);
+ expect(fs.existsSync(outPath)).toBe(false);
+ }
+ expect(fs.readdirSync(tempDirectory).filter((name) => name.includes(".tmp-"))).toEqual([]);
+ });
+});