openclaw/src/gateway/server.auth.compat-baseline.test.ts
clay-datacurve 7b61ca1b06
Session management improvements and dashboard API (#50101)
* fix: make cleanup "keep" persist subagent sessions indefinitely

* feat: expose subagent session metadata in sessions list

* fix: include status and timing in sessions_list tool

* fix: hide injected timestamp prefixes in chat ui

* feat: push session list updates over websocket

* feat: expose child subagent sessions in subagents list

* feat: add admin http endpoint to kill sessions

* Emit session.message websocket events for transcript updates

* Estimate session costs in sessions list

* Add direct session history HTTP and SSE endpoints

* Harden dashboard session events and history APIs

* Add session lifecycle gateway methods

* Add dashboard session API improvements

* Add dashboard session model and parent linkage support

* fix: tighten dashboard session API metadata

* Fix dashboard session cost metadata

* Persist accumulated session cost

* fix: stop followup queue drain cfg crash

* Fix dashboard session create and model metadata

* fix: stop guessing session model costs

* Gateway: cache OpenRouter pricing for configured models

* Gateway: add timeout session status

* Fix subagent spawn test config loading

* Gateway: preserve operator scopes without device identity

* Emit user message transcript events and deduplicate plugin warnings

* feat: emit sessions.changed lifecycle event on subagent spawn

Adds a session-lifecycle-events module (similar to transcript-events)
that emits create events when subagents are spawned. The gateway
server.impl.ts listens for these events and broadcasts sessions.changed
with reason=create to SSE subscribers, so dashboards can pick up new
subagent sessions without polling.

* Gateway: allow persistent dashboard orchestrator sessions

* fix: preserve operator scopes for token-authenticated backend clients

Backend clients (like agent-dashboard) that authenticate with a valid gateway
token but don't present a device identity were getting their scopes stripped.
The scope-clearing logic ran before checking the device identity decision,
so even when evaluateMissingDeviceIdentity returned 'allow' (because
roleCanSkipDeviceIdentity passed for token-authed operators), scopes were
already cleared.

Fix: also check decision.kind before clearing scopes, so token-authenticated
operators keep their requested scopes.

* Gateway: allow operator-token session kills

* Fix stale active subagent status after follow-up runs

* Fix dashboard image attachments in sessions send

* Fix completed session follow-up status updates

* feat: stream session tool events to operator UIs

* Add sessions.steer gateway coverage

* Persist subagent timing in session store

* Fix subagent session transcript event keys

* Fix active subagent session status in gateway

* bump session label max to 512

* Fix gateway send session reactivation

* fix: publish terminal session lifecycle state

* feat: change default session reset to effectively never

- Change DEFAULT_RESET_MODE from "daily" to "idle"
- Change DEFAULT_IDLE_MINUTES from 60 to 0 (0 = disabled/never)
- Allow idleMinutes=0 through normalization (don't clamp to 1)
- Treat idleMinutes=0 as "no idle expiry" in evaluateSessionFreshness
- Default behavior: mode "idle" + idleMinutes 0 = sessions never auto-reset
- Update test assertion for new default mode

* fix: prep session management followups (#50101) (thanks @clay-datacurve)

---------

Co-authored-by: Tyler Yust <TYTYYUST@YAHOO.COM>
2026-03-19 12:12:30 +09:00

276 lines
8.6 KiB
TypeScript

import os from "node:os";
import path from "node:path";
import { afterAll, beforeAll, describe, expect, test } from "vitest";
import {
BACKEND_GATEWAY_CLIENT,
connectReq,
CONTROL_UI_CLIENT,
ConnectErrorDetailCodes,
getFreePort,
openWs,
originForPort,
rpcReq,
restoreGatewayToken,
startGatewayServer,
testState,
} from "./server.auth.shared.js";
function expectAuthErrorDetails(params: {
details: unknown;
expectedCode: string;
canRetryWithDeviceToken?: boolean;
recommendedNextStep?: string;
}) {
const details = params.details as
| {
code?: string;
canRetryWithDeviceToken?: boolean;
recommendedNextStep?: string;
}
| undefined;
expect(details?.code).toBe(params.expectedCode);
if (params.canRetryWithDeviceToken !== undefined) {
expect(details?.canRetryWithDeviceToken).toBe(params.canRetryWithDeviceToken);
}
if (params.recommendedNextStep !== undefined) {
expect(details?.recommendedNextStep).toBe(params.recommendedNextStep);
}
}
async function expectSharedOperatorScopesPreserved(
port: number,
auth: { token?: string; password?: string },
) {
const ws = await openWs(port);
try {
const res = await connectReq(ws, {
...auth,
scopes: ["operator.admin"],
device: null,
});
expect(res.ok).toBe(true);
const adminRes = await rpcReq(ws, "set-heartbeats", { enabled: false });
expect(adminRes.ok).toBe(true);
expect((adminRes.payload as { enabled?: boolean } | undefined)?.enabled).toBe(false);
} finally {
ws.close();
}
}
describe("gateway auth compatibility baseline", () => {
describe("token mode", () => {
let server: Awaited<ReturnType<typeof startGatewayServer>>;
let port = 0;
let prevToken: string | undefined;
beforeAll(async () => {
prevToken = process.env.OPENCLAW_GATEWAY_TOKEN;
testState.gatewayAuth = { mode: "token", token: "secret" };
process.env.OPENCLAW_GATEWAY_TOKEN = "secret";
port = await getFreePort();
server = await startGatewayServer(port);
});
afterAll(async () => {
await server.close();
restoreGatewayToken(prevToken);
});
test("keeps valid shared-token connect behavior unchanged", async () => {
const ws = await openWs(port);
try {
const res = await connectReq(ws, { token: "secret" });
expect(res.ok).toBe(true);
} finally {
ws.close();
}
});
test("keeps requested scopes for shared-token operator connects without device identity", async () => {
await expectSharedOperatorScopesPreserved(port, { token: "secret" });
});
test("returns stable token-missing details for control ui without token", async () => {
const ws = await openWs(port, { origin: originForPort(port) });
try {
const res = await connectReq(ws, {
skipDefaultAuth: true,
client: { ...CONTROL_UI_CLIENT },
});
expect(res.ok).toBe(false);
expect(res.error?.message ?? "").toContain("Control UI settings");
expectAuthErrorDetails({
details: res.error?.details,
expectedCode: ConnectErrorDetailCodes.AUTH_TOKEN_MISSING,
canRetryWithDeviceToken: false,
recommendedNextStep: "update_auth_configuration",
});
} finally {
ws.close();
}
});
test("provides one-time retry hint for shared token mismatches", async () => {
const ws = await openWs(port);
try {
const res = await connectReq(ws, { token: "wrong" });
expect(res.ok).toBe(false);
expect(res.error?.message ?? "").toContain("gateway token mismatch");
expectAuthErrorDetails({
details: res.error?.details,
expectedCode: ConnectErrorDetailCodes.AUTH_TOKEN_MISMATCH,
canRetryWithDeviceToken: true,
recommendedNextStep: "retry_with_device_token",
});
} finally {
ws.close();
}
});
test("keeps explicit device token mismatch semantics stable", async () => {
const ws = await openWs(port);
try {
const res = await connectReq(ws, {
skipDefaultAuth: true,
deviceToken: "not-a-valid-device-token",
});
expect(res.ok).toBe(false);
expect(res.error?.message ?? "").toContain("device token mismatch");
expectAuthErrorDetails({
details: res.error?.details,
expectedCode: ConnectErrorDetailCodes.AUTH_DEVICE_TOKEN_MISMATCH,
canRetryWithDeviceToken: false,
recommendedNextStep: "update_auth_credentials",
});
} finally {
ws.close();
}
});
test("keeps local backend device-token reconnects out of pairing", async () => {
const identityPath = path.join(
os.tmpdir(),
`openclaw-backend-device-${process.pid}-${port}.json`,
);
const { loadOrCreateDeviceIdentity, publicKeyRawBase64UrlFromPem } =
await import("../infra/device-identity.js");
const { approveDevicePairing, requestDevicePairing, rotateDeviceToken } =
await import("../infra/device-pairing.js");
const identity = loadOrCreateDeviceIdentity(identityPath);
const pending = await requestDevicePairing({
deviceId: identity.deviceId,
publicKey: publicKeyRawBase64UrlFromPem(identity.publicKeyPem),
clientId: BACKEND_GATEWAY_CLIENT.id,
clientMode: BACKEND_GATEWAY_CLIENT.mode,
role: "operator",
scopes: ["operator.admin"],
});
await approveDevicePairing(pending.request.requestId);
const rotated = await rotateDeviceToken({
deviceId: identity.deviceId,
role: "operator",
scopes: ["operator.admin"],
});
expect(rotated.ok).toBe(true);
const rotatedToken = rotated.ok ? rotated.entry.token : "";
expect(rotatedToken).toBeTruthy();
const ws = await openWs(port);
try {
const res = await connectReq(ws, {
skipDefaultAuth: true,
client: { ...BACKEND_GATEWAY_CLIENT },
deviceIdentityPath: identityPath,
deviceToken: rotatedToken,
scopes: ["operator.admin"],
});
expect(res.ok).toBe(true);
expect((res.payload as { type?: string } | undefined)?.type).toBe("hello-ok");
} finally {
ws.close();
}
});
});
describe("password mode", () => {
let server: Awaited<ReturnType<typeof startGatewayServer>>;
let port = 0;
let prevToken: string | undefined;
beforeAll(async () => {
prevToken = process.env.OPENCLAW_GATEWAY_TOKEN;
testState.gatewayAuth = { mode: "password", password: "secret" };
delete process.env.OPENCLAW_GATEWAY_TOKEN;
port = await getFreePort();
server = await startGatewayServer(port);
});
afterAll(async () => {
await server.close();
restoreGatewayToken(prevToken);
});
test("keeps valid shared-password connect behavior unchanged", async () => {
const ws = await openWs(port);
try {
const res = await connectReq(ws, { password: "secret" });
expect(res.ok).toBe(true);
} finally {
ws.close();
}
});
test("returns stable password mismatch details", async () => {
const ws = await openWs(port);
try {
const res = await connectReq(ws, { password: "wrong" });
expect(res.ok).toBe(false);
expectAuthErrorDetails({
details: res.error?.details,
expectedCode: ConnectErrorDetailCodes.AUTH_PASSWORD_MISMATCH,
canRetryWithDeviceToken: false,
recommendedNextStep: "update_auth_credentials",
});
} finally {
ws.close();
}
});
test("keeps requested scopes for shared-password operator connects without device identity", async () => {
await expectSharedOperatorScopesPreserved(port, { password: "secret" });
});
});
describe("none mode", () => {
let server: Awaited<ReturnType<typeof startGatewayServer>>;
let port = 0;
let prevToken: string | undefined;
beforeAll(async () => {
prevToken = process.env.OPENCLAW_GATEWAY_TOKEN;
testState.gatewayAuth = { mode: "none" };
delete process.env.OPENCLAW_GATEWAY_TOKEN;
port = await getFreePort();
server = await startGatewayServer(port);
});
afterAll(async () => {
await server.close();
restoreGatewayToken(prevToken);
});
test("keeps auth-none loopback behavior unchanged", async () => {
const ws = await openWs(port);
try {
const res = await connectReq(ws, { skipDefaultAuth: true });
expect(res.ok).toBe(true);
} finally {
ws.close();
}
});
});
});