Files
streamline/satellite/test/agent_account_monitor.test.ts
T
2026-11-16 17:26:44 -08:00

500 lines
21 KiB
TypeScript

import { afterEach, describe, expect, test } from "bun:test";
import { chmodSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import {
clearAgentAccountDrain,
isAgentAccountClaimDrained,
readAgentAccountDrain,
updateAgentAccountDrain,
writeAgentAccountDrain,
type AgentAccountDrainState,
} from "../src/security_telemetry/agent_account_gate";
import {
cursorIdentityFromConfig,
cursorSessionCookieValue,
cursorSnapshotFromUsage,
createCursorAccountAdapter,
} from "../src/security_telemetry/cursor_account_adapter";
import { primaryQuotaBelow, type AgentAccountIdentity } from "../src/security_telemetry/agent_account_adapter";
import {
buildTokenAlertPayload,
postTokenAlert,
TOKEN_ALERT_URL,
} from "../src/security_telemetry/token_alert";
import {
captureHeadlessLoginUrl,
handleSecurityAccountExhausted,
monitorSecurityAccountAfterSuccess,
startAgentAccountRecoveryMonitor,
} from "../src/security_telemetry/security_account_manager";
const dirs: string[] = [];
function tempState(): string {
const dir = mkdtempSync(path.join(tmpdir(), "streamline-agent-account-"));
dirs.push(dir);
return dir;
}
afterEach(() => {
createCursorAccountAdapter().finishReauth();
for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });
});
describe("persistent agent account claim gate", () => {
test("drains every claim loop until the persisted state is cleared", () => {
const stateDir = tempState();
expect(isAgentAccountClaimDrained(stateDir)).toBe(false);
const state: AgentAccountDrainState = {
schema_version: 1,
provider: "cursor",
reason: "TOKEN_EXHAUSTED",
task_id: "sec-1",
execution_id: "sec-1:run:1",
phase: "run",
cluster_name: "security-android-a",
node_id: "sat-1",
account: "owner@example.com",
card_id: "sec-1:run:1",
recovery_id: "recovery-1",
login_url: null,
drained_at: "2026-08-31T00:00:00.000Z",
updated_at: "2026-08-31T00:00:00.000Z",
};
writeAgentAccountDrain(state, stateDir);
expect(isAgentAccountClaimDrained(stateDir)).toBe(true);
expect(readAgentAccountDrain(stateDir)).toMatchObject({ task_id: "sec-1", provider: "cursor" });
updateAgentAccountDrain({ login_url: "https://cursor.example/login", updated_at: "later" }, stateDir);
expect(readAgentAccountDrain(stateDir)?.login_url).toBe("https://cursor.example/login");
expect(clearAgentAccountDrain(stateDir)).toBe(true);
expect(isAgentAccountClaimDrained(stateDir)).toBe(false);
});
test("fails closed when the durable gate is corrupt", () => {
const stateDir = tempState();
const file = path.join(stateDir, "agent-account-drain.json");
writeFileSync(file, "{", "utf8");
expect(isAgentAccountClaimDrained(stateDir)).toBe(true);
expect(readAgentAccountDrain(stateDir)?.recovery_id).toBe("corrupt-state");
});
});
const identity: AgentAccountIdentity = {
account_id: "auth0|user_abc",
email: "owner@example.com",
display_name: "Owner",
organization_id: "team-1",
organization_name: "Security",
auth_method: "browser_login",
plan: null,
};
describe("Cursor account adapter pure contract", () => {
test("reads identity and builds the WorkOS session cookie without logging the JWT", () => {
expect(cursorIdentityFromConfig({
authInfo: {
authId: "auth0|user_abc", email: "owner@example.com", displayName: "Owner",
teamId: 7, teamName: "Security", userId: 42,
},
})).toMatchObject({
account_id: "auth0|user_abc",
email: "owner@example.com",
organization_id: "7",
});
expect(cursorSessionCookieValue("header.payload.signature", "auth0|user_abc"))
.toBe("user_abc::header.payload.signature");
expect(cursorSessionCookieValue("user_abc::jwt", "auth0|user_abc"))
.toBe("user_abc::jwt");
});
test("normalises legacy enterprise individual and team windows", () => {
const snapshot = cursorSnapshotFromUsage({
membershipType: "enterprise",
billingCycleEnd: "2026-09-01T00:00:00.000Z",
individualUsage: { overall: { enabled: true, used: 100_005, limit: 100_000, remaining: 0 } },
teamUsage: { onDemand: { enabled: true, used: 915_880_392, limit: 1_031_680_000, remaining: 115_799_608 } },
}, identity, new Date("2026-08-31T00:00:00.000Z"));
expect(snapshot.account.plan).toBe("enterprise");
expect(snapshot.runnable).toBe(true); // team pool is still available
expect(primaryQuotaBelow(snapshot, 5)).toMatchObject({ scope: "individual", remaining_percent: 0 });
});
test("normalises Cursor's newer Auto/API percent shape", () => {
const snapshot = cursorSnapshotFromUsage({
membershipType: "pro",
billingCycleEnd: "2026-09-01T00:00:00.000Z",
individualUsage: {
plan: { enabled: true, autoPercentUsed: 96.5, apiPercentUsed: 20 },
},
}, identity);
expect(snapshot.quotas).toEqual(expect.arrayContaining([
expect.objectContaining({ scope: "cursor_auto_composer", remaining_percent: 3.5, primary: true }),
expect.objectContaining({ scope: "cursor_api_usage", remaining_percent: 80, primary: true }),
]));
});
test("captures a headless login URL without waiting for authorization", async () => {
const dir = tempState();
const fake = path.join(dir, "cursor-agent");
writeFileSync(fake, `#!/bin/sh
case "$1" in
logout) exit 0 ;;
login) test "$NO_OPEN_BROWSER" = "1" || exit 9; printf '%s\\n' "$$" > "$CURSOR_TEST_PID_FILE"; printf 'Open https://cursor.example/authorize?id=test\\n'; sleep 30 ;;
status|whoami) printf 'Not logged in\\n'; exit 1 ;;
esac
`, "utf8");
chmodSync(fake, 0o755);
const previous = process.env.CURSOR_BIN;
const previousPidFile = process.env.CURSOR_TEST_PID_FILE;
const pidFile = path.join(dir, "login.pid");
process.env.CURSOR_BIN = fake;
process.env.CURSOR_TEST_PID_FILE = pidFile;
const adapter = createCursorAccountAdapter();
try {
expect(await adapter.beginReauth({ resetCredentials: true })).toMatchObject({
kind: "browser_url",
verification_uri: "https://cursor.example/authorize?id=test",
});
const pid = Number(readFileSync(pidFile, "utf8").trim());
expect(() => process.kill(pid, 0)).not.toThrow();
} finally {
adapter.finishReauth();
if (previous === undefined) delete process.env.CURSOR_BIN;
else process.env.CURSOR_BIN = previous;
if (previousPidFile === undefined) delete process.env.CURSOR_TEST_PID_FILE;
else process.env.CURSOR_TEST_PID_FILE = previousPidFile;
}
});
test("keeps the active account while capturing an early-rotation login URL", async () => {
const logs: string[] = [];
const adapter = {
id: "cursor-login",
provider: "cursor" as const,
readIdentity: () => identity,
probeAccount: async () => { throw new Error("not used"); },
beginReauth: async ({ resetCredentials }: { resetCredentials: boolean }) => {
expect(resetCredentials).toBe(false);
return {
kind: "browser_url" as const,
verification_uri: "https://cursor.example/authorize?id=warning",
user_code: null,
issued_at: "2026-09-10T00:00:00.000Z",
};
},
checkAuth: async () => ({ state: "AUTHENTICATED" as const, account: "owner@example.com" }),
finishReauth: () => {},
};
expect(await captureHeadlessLoginUrl(adapter, (_level, message) => logs.push(message)))
.toBe("https://cursor.example/authorize?id=warning");
expect(logs).toEqual([]);
});
test("concurrent reset requests share one logout and preserve the first live login", async () => {
const dir = tempState();
const fake = path.join(dir, "cursor-agent");
writeFileSync(fake, `#!/bin/sh
printf '%s\\n' "$1" >> "$CURSOR_TEST_LOGIN_DIR/calls"
case "$1" in
logout) sleep 0.05; exit 0 ;;
login) printf '%s' "$$" > "$CURSOR_TEST_LOGIN_DIR/pid"; printf 'Open https://cursor.example/authorize?id=first\\n'; exec sleep 30 ;;
esac
`, "utf8");
chmodSync(fake, 0o755);
const previousBin = process.env.CURSOR_BIN;
const previousDir = process.env.CURSOR_TEST_LOGIN_DIR;
process.env.CURSOR_BIN = fake;
process.env.CURSOR_TEST_LOGIN_DIR = dir;
const a = createCursorAccountAdapter(), b = createCursorAccountAdapter();
try {
const challenges = await Promise.all([
a.beginReauth({ resetCredentials: true }),
b.beginReauth({ resetCredentials: true }),
]);
challenges.push(await a.beginReauth({ resetCredentials: false }));
challenges.push(await b.beginReauth({ resetCredentials: true }));
expect(new Set(challenges.map((challenge) => challenge.verification_uri)).size).toBe(1);
expect(new Set(challenges.map((challenge) => challenge.issued_at)).size).toBe(1);
expect(readFileSync(path.join(dir, "calls"), "utf8").trim().split("\n")).toEqual(["logout", "login"]);
expect(() => process.kill(Number(readFileSync(path.join(dir, "pid"), "utf8")), 0)).not.toThrow();
expect(a.reauthProcessState?.()).toMatchObject({ state: "waiting" });
} finally {
a.finishReauth();
if (previousBin === undefined) delete process.env.CURSOR_BIN; else process.env.CURSOR_BIN = previousBin;
if (previousDir === undefined) delete process.env.CURSOR_TEST_LOGIN_DIR; else process.env.CURSOR_TEST_LOGIN_DIR = previousDir;
}
});
test("reads structured auth status without confusing missing account details with missing credentials", async () => {
const dir = tempState();
const fake = path.join(dir, "cursor-agent");
const output = path.join(dir, "status.json");
const configPath = path.join(dir, "cli-config.json");
writeFileSync(configPath, JSON.stringify({ authInfo: { authId: "old", email: "stale@example.com" } }));
writeFileSync(fake, `#!/bin/sh
test "$1" = whoami && test "$2" = --format && test "$3" = json || exit 9
cat "$CURSOR_TEST_STATUS_JSON"
`, "utf8");
chmodSync(fake, 0o755);
const previousBin = process.env.CURSOR_BIN;
const previousOutput = process.env.CURSOR_TEST_STATUS_JSON;
process.env.CURSOR_BIN = fake;
process.env.CURSOR_TEST_STATUS_JSON = output;
const adapter = createCursorAccountAdapter({ configPath });
try {
writeFileSync(output, JSON.stringify({ status: "authenticated", isAuthenticated: true, userInfo: { email: "fresh@example.com" } }));
expect(await adapter.checkAuth()).toEqual({ state: "AUTHENTICATED", account: "fresh@example.com" });
writeFileSync(output, JSON.stringify({ status: "authenticated", isAuthenticated: true, message: "Logged in (unable to fetch user details)" }));
expect(await adapter.checkAuth()).toEqual({ state: "AUTHENTICATED", account: null });
writeFileSync(output, JSON.stringify({ status: "authenticated", isAuthenticated: true, userInfo: { userId: 123 } }));
expect(await adapter.checkAuth()).toEqual({ state: "AUTHENTICATED", account: null });
writeFileSync(output, JSON.stringify({ status: "unauthenticated", isAuthenticated: false }));
expect(await adapter.checkAuth()).toEqual({ state: "UNAUTHENTICATED", account: null });
writeFileSync(output, "network request failed");
expect(await adapter.checkAuth()).toMatchObject({ state: "UNKNOWN" });
} finally {
if (previousBin === undefined) delete process.env.CURSOR_BIN; else process.env.CURSOR_BIN = previousBin;
if (previousOutput === undefined) delete process.env.CURSOR_TEST_STATUS_JSON; else process.env.CURSOR_TEST_STATUS_JSON = previousOutput;
}
});
});
describe("account recovery polling", () => {
test("API-key mode skips login and quota probes, drains on exhaustion, and resumes after key replacement", async () => {
const dir = tempState();
const keyFile = path.join(dir, "cursor-key");
const old = {
mode: process.env.STREAMLINE_CURSOR_AUTH_MODE,
keyFile: process.env.STREAMLINE_CURSOR_API_KEY_FILE,
stateDir: process.env.SECURITY_TELEMETRY_DIR,
fetch: globalThis.fetch,
};
process.env.STREAMLINE_CURSOR_AUTH_MODE = "api-key";
process.env.STREAMLINE_CURSOR_API_KEY_FILE = keyFile;
process.env.SECURITY_TELEMETRY_DIR = dir;
writeFileSync(keyFile, "first-key\n", { mode: 0o600 });
const calls: string[] = [];
globalThis.fetch = (async () => { calls.push("fetch"); throw new Error("unexpected HTTP request"); }) as typeof fetch;
const adapter = {
...createCursorAccountAdapter(),
readIdentity: () => { calls.push("identity"); return null; },
probeAccount: async () => { calls.push("quota"); throw new Error("unexpected quota probe"); },
beginReauth: async () => { calls.push("login"); throw new Error("unexpected login"); },
checkAuth: async () => { calls.push("whoami"); return { state: "UNAUTHENTICATED" as const, account: null }; },
onReauthProcessExit: () => { calls.push("subscribe"); return () => {}; },
};
const now = new Date().toISOString();
writeAgentAccountDrain({
schema_version: 1, provider: "cursor", reason: "TOKEN_READ_FAILED", task_id: "old",
execution_id: "old:run:1", phase: "run", cluster_name: "pns", node_id: "sat-1",
account: "old", card_id: "old", recovery_id: "old", login_url: null, drained_at: now, updated_at: now,
});
const oldState = readAgentAccountDrain()!;
const stop = startAgentAccountRecoveryMonitor(() => {}, 10, { adapter });
const context = { security: { id: "sec-api", attempts: 0, clusters: ["pns"] }, phase: "run" as const, provider: "cursor" as const, nodeId: "sat-1" };
try {
for (let i = 0; i < 50 && readAgentAccountDrain(); i++) await Bun.sleep(10);
expect(readAgentAccountDrain()).toBeNull();
writeAgentAccountDrain({ ...oldState, reason: "TOKEN_DWINDLING" });
expect(isAgentAccountClaimDrained()).toBe(false);
for (let i = 0; i < 50 && readAgentAccountDrain(); i++) await Bun.sleep(10);
expect(readAgentAccountDrain()).toBeNull();
await monitorSecurityAccountAfterSuccess(context, () => {}, adapter);
await handleSecurityAccountExhausted(context, "usage_limit_exceeded", () => {});
const drained = readAgentAccountDrain();
expect(drained).toMatchObject({ reason: "TOKEN_EXHAUSTED", task_id: "sec-api", login_url: null });
expect(drained?.api_key_fingerprint).toMatch(/^[0-9a-f]{64}$/);
expect(JSON.stringify(drained)).not.toContain("first-key");
expect(isAgentAccountClaimDrained()).toBe(true);
await Bun.sleep(30);
expect(isAgentAccountClaimDrained()).toBe(true);
writeFileSync(keyFile, "replacement-key\n");
for (let i = 0; i < 50 && isAgentAccountClaimDrained(); i++) await Bun.sleep(10);
expect(isAgentAccountClaimDrained()).toBe(false);
expect(calls).toEqual([]);
} finally {
stop();
globalThis.fetch = old.fetch;
if (old.mode === undefined) delete process.env.STREAMLINE_CURSOR_AUTH_MODE; else process.env.STREAMLINE_CURSOR_AUTH_MODE = old.mode;
if (old.keyFile === undefined) delete process.env.STREAMLINE_CURSOR_API_KEY_FILE; else process.env.STREAMLINE_CURSOR_API_KEY_FILE = old.keyFile;
if (old.stateDir === undefined) delete process.env.SECURITY_TELEMETRY_DIR; else process.env.SECURITY_TELEMETRY_DIR = old.stateDir;
}
});
test("a restored login clears the global gate so all task types may claim again", async () => {
const dir = tempState();
const fake = path.join(dir, "cursor-agent");
writeFileSync(fake, `#!/bin/sh
if [ "$1" = whoami ]; then printf '✓ Logged in as restored@example.com\\n'; exit 0; fi
exit 0
`, "utf8");
chmodSync(fake, 0o755);
const previousBin = process.env.CURSOR_BIN;
const previousState = process.env.SECURITY_TELEMETRY_DIR;
process.env.CURSOR_BIN = fake;
process.env.SECURITY_TELEMETRY_DIR = dir;
writeAgentAccountDrain({
schema_version: 1,
provider: "cursor",
reason: "TOKEN_EXHAUSTED",
task_id: "sec-restore",
execution_id: "sec-restore:run:1",
phase: "run",
cluster_name: "security",
node_id: "sat-1",
account: "old@example.com",
card_id: "sec-restore:run:1",
recovery_id: "recovery-restore",
login_url: null,
drained_at: new Date().toISOString(),
updated_at: new Date().toISOString(),
});
const logs: string[] = [];
const stop = startAgentAccountRecoveryMonitor((_level, message) => logs.push(message), 10, {
adapter: {
...createCursorAccountAdapter(),
async probeAccount() {
return cursorSnapshotFromUsage({
individualUsage: { overall: { enabled: true, used: 20, limit: 100, remaining: 80 } },
}, { ...identity, email: "restored@example.com" });
},
},
});
try {
for (let i = 0; i < 40 && isAgentAccountClaimDrained(); i++) await Bun.sleep(50);
expect(isAgentAccountClaimDrained()).toBe(false);
expect(logs.some((message) => message.includes("global task claiming resumed"))).toBe(true);
} finally {
stop();
if (previousBin === undefined) delete process.env.CURSOR_BIN;
else process.env.CURSOR_BIN = previousBin;
if (previousState === undefined) delete process.env.SECURITY_TELEMETRY_DIR;
else process.env.SECURITY_TELEMETRY_DIR = previousState;
}
});
});
describe("token alert contract", () => {
test("uses the temporary security alert service", () => {
expect(TOKEN_ALERT_URL).toBe("http://10.37.81.28:3100/api/v1/lark-card");
});
test("puts every server-required field in card_info.message and redacts credentials", () => {
const payload = buildTokenAlertPayload({
eventType: "TOKEN_EXHAUSTED",
alertLevel: "critical",
taskId: "sec-1",
executionId: "sec-1:run:1",
phase: "run",
clusterName: "security-android-a",
nodeId: "sat-1",
provider: "cursor",
account: identity,
loginUrl: "https://cursor.example/login",
reason: "Bearer secret-token eyJabc.def.ghi",
}, new Date("2026-08-31T00:00:00.000Z"));
expect(payload).toMatchObject({
schema_version: 1,
occurred_at: "2026-08-31T00:00:00.000Z",
alert_level: "critical",
card_info: { source: "streamline" },
});
expect(payload.card_info.card_id).toMatch(/^sec-1:run:1:[0-9a-f-]{36}$/);
const message = payload.card_info.message;
for (const value of [
"event_type=TOKEN_EXHAUSTED", "cluster_name=security-android-a", "node_id=sat-1",
"agent_type=cursor", "current_account=owner@example.com", "login_url=https://cursor.example/login",
]) expect(message).toContain(value);
expect(message).not.toContain("secret-token");
expect(message).not.toContain("eyJabc.def.ghi");
});
test("generates a fresh card id for every lark-card request body", () => {
const context = {
eventType: "TOKEN_EXHAUSTED" as const,
alertLevel: "critical" as const,
taskId: "sec-1",
executionId: "sec-1:run:1",
phase: "run" as const,
clusterName: "security-android-a",
nodeId: "sat-1",
provider: "cursor" as const,
account: identity,
loginUrl: "https://cursor.example/login",
};
const first = buildTokenAlertPayload(context, new Date("2026-08-31T00:00:00.000Z"));
const second = buildTokenAlertPayload(context, new Date("2026-08-31T00:00:00.000Z"));
expect(first.card_info.card_id).not.toBe(second.card_info.card_id);
expect(first.card_info.card_id.startsWith("sec-1:run:1:")).toBe(true);
expect(second.card_info.card_id.startsWith("sec-1:run:1:")).toBe(true);
});
test("uses a valid Cursor login page when a warning has no generated URL", () => {
const payload = buildTokenAlertPayload({
eventType: "TOKEN_DWINDLING",
alertLevel: "warning",
taskId: "sec-low",
executionId: "sec-low:run:1",
phase: "run",
clusterName: "default",
nodeId: "sat-low",
provider: "cursor",
account: identity,
quota: null,
loginUrl: null,
});
expect(payload.card_info.message).toContain("login_url=https://cursor.com/login");
expect(payload.card_info.message).not.toContain("login_url=not_generated");
});
test("posts the exact lark-card request body", async () => {
const payload = buildTokenAlertPayload({
eventType: "TOKEN_READ_FAILED",
alertLevel: "warning",
taskId: "sec-2",
executionId: "sec-2:evaluate:1",
phase: "evaluate",
clusterName: "default",
nodeId: "sat-2",
provider: "cursor",
account: identity,
reason: "keychain unavailable",
});
let seen: { url: string; body: string } | null = null;
const fakeFetch = (async (input: string | URL | Request, init?: RequestInit) => {
seen = {
url: String(input),
body: String(init?.body || ""),
};
return new Response("", { status: 204 });
}) as typeof fetch;
expect(await postTokenAlert(payload, { fetchImpl: fakeFetch })).toEqual({ ok: true, error: null });
expect(seen).toEqual({
url: TOKEN_ALERT_URL,
body: JSON.stringify(payload),
});
});
test("turns lark-card connection failures into a non-throwing result", async () => {
const payload = buildTokenAlertPayload({
eventType: "TOKEN_DWINDLING",
alertLevel: "warning",
taskId: "sec-3",
executionId: "sec-3:run:1",
phase: "run",
clusterName: "default",
nodeId: "sat-3",
provider: "cursor",
account: identity,
});
const failingFetch = (async () => {
throw new Error("connection refused");
}) as typeof fetch;
expect(await postTokenAlert(payload, { fetchImpl: failingFetch })).toEqual({
ok: false,
error: "connection refused",
});
});
});