Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

Remote teammates: tighter calls to the other server (review on #7113)

Bugfixer 25fbdb975b24d
diff --git a/server/remote-teammates.test.ts b/server/remote-teammates.test.ts
index fd9779bdff..7b836e005a 100644
--- a/server/remote-teammates.test.ts
+++ b/server/remote-teammates.test.ts
@@ -52,6 +52,8 @@ describe("remoteAddress", () => {
expect(remoteAddress("http://192.168.1.20:8799", "b1").base).toBe("http://192.168.1.20:8799");
expect(() => remoteAddress("http://maus.example.com", "b1")).toThrow(/open internet/);
expect(() => remoteAddress("ftp://maus.example.com", "b1")).toThrow(/https/);
+ // A blob: URL's origin is the https one inside it.
+ expect(() => remoteAddress("blob:https://maus.example.com/x", "b1")).toThrow(/must start with https/);
expect(() => remoteAddress("https://me:[email protected]", "b1")).toThrow(/without a sign-in/);
expect(() => remoteAddress("maus", "b1")).toThrow(/not a server address/);
});
@@ -102,7 +104,7 @@ describe("RemoteTeammates", () => {
writeFileSync(file, "{not json");
const store = new RemoteTeammates({ file });
expect(store.list()).toEqual([]);
- expect(() => store.add({ name: "Far", address: "https://maus.example.com", botId: "b1", key: KEY })).toThrow(/could not be read/);
+ expect(() => store.add({ name: "Far", address: "https://maus.example.com", botId: "b1", key: KEY })).toThrow(/could not be read.*restart OpenMausBot/);
expect(readFileSync(file, "utf8")).toBe("{not json");
});
@@ -195,12 +197,12 @@ describe("calling a teammate's Bot API", () => {
it("never connects to a name that resolves to a link-local, metadata or reserved address", async () => {
for (const address of ["169.254.169.254", "fe80::1", "fd00:ec2::254", "::ffff:169.254.169.254", "64:ff9b::a9fe:a9fe", "::a9fe:a9fe", "100.100.100.200", "fe80::1%eth0"]) expect(notAServerAddress(address)).toBe(true);
for (const address of ["127.0.0.1", "100.64.1.2", "192.168.1.5", "::1", "not an address"]) expect(notAServerAddress(address)).toBe(false);
- const lookupWith = (answer: Array<{ address: string; family: number }>) => {
+ const lookupWith = (answer: Array<{ address: string; family: number }>, privateOnly = false) => {
const resolve = ((_host: string, options: { all?: boolean }, callback: (...args: unknown[]) => void) => {
if (options.all) callback(null, answer);
else callback(null, answer[0]!.address, answer[0]!.family);
}) as unknown as LookupFunction;
- const lookup = serverOnlyLookup(resolve);
+ const lookup = serverOnlyLookup(resolve, privateOnly);
return (all: boolean) => new Promise<{ error: NodeJS.ErrnoException | null; address: unknown }>((done) => {
lookup("far.example.com", { all }, (error, address) => done({ error, address }));
});
@@ -209,6 +211,36 @@ describe("calling a teammate's Bot API", () => {
expect(metadata.error).toMatchObject({ code: "ENOTSERVER", message: "far.example.com resolves to 169.254.169.254, a link-local, metadata or reserved address, not another server" });
expect((await lookupWith([{ address: "100.64.1.2", family: 4 }, { address: "fe80::1", family: 6 }])(true)).error).toMatchObject({ code: "ENOTSERVER" });
expect(await lookupWith([{ address: "100.64.1.2", family: 4 }])(false)).toEqual({ error: null, address: "100.64.1.2" });
+ // Plain http: a private-network name must stay on this computer or a private network, or the key goes out unencrypted.
+ expect(await lookupWith([{ address: "93.184.216.34", family: 4 }])(false)).toEqual({ error: null, address: "93.184.216.34" });
+ expect((await lookupWith([{ address: "93.184.216.34", family: 4 }], true)(false)).error).toMatchObject({
+ code: "ENOTSERVER", message: "far.example.com resolves to 93.184.216.34, on the open internet, where plain http isn't encrypted",
+ });
+ expect((await lookupWith([{ address: "192.168.1.5", family: 4 }, { address: "2606:4700::1", family: 6 }], true)(true)).error).toMatchObject({ code: "ENOTSERVER" });
+ for (const address of ["127.0.0.1", "::1", "100.64.1.2", "192.168.1.5", "10.0.0.7", "fd12::1"]) {
+ expect(await lookupWith([{ address, family: address.includes(":") ? 6 : 4 }], true)(false)).toEqual({ error: null, address });
+ }
+ });
+
+ it("takes an answer only about the thread it went on in", async () => {
+ let answer: unknown = { reply: "hi", thread: "other" };
+ const fetch = (async () => new Response(JSON.stringify(answer), { status: "reply" in (answer as object) ? 200 : 202 })) as typeof globalThis.fetch;
+ const far = teammate("https://maus.example.com");
+ expect(await readRemote(far, "t1", { fetch })).toEqual({ ok: false, problem: "bad_answer", status: 200 });
+ expect(await sendToRemote(far, { message: "x", thread: "t1" }, { fetch })).toEqual({ ok: false, problem: "bad_answer", status: 200 });
+ // A message that starts a thread takes the one the other server gives.
+ expect(await sendToRemote(far, { message: "x" }, { fetch })).toEqual({ ok: true, answer: { reply: "hi", thread: "other" } });
+ answer = { thread: "t1", status: "working" };
+ expect(await readRemote(far, "t1", { fetch })).toEqual({ ok: true, answer: { thread: "t1", status: "working" } });
+ });
+
+ it("never passes on the key when the other server echoes it in an error", async () => {
+ const said = `bad key ${KEY} for ${"x".repeat(280)}${KEY}`;
+ const fetch = (async () => new Response(JSON.stringify({ error: said }), { status: 401 })) as typeof globalThis.fetch;
+ const result = await readRemote(teammate("https://maus.example.com"), "t1", { fetch });
+ expect(result).toMatchObject({ ok: false, problem: "wrong_key", status: 401 });
+ expect(JSON.stringify(result)).not.toContain("k".repeat(16));
+ expect(result).toMatchObject({ detail: expect.stringMatching(/^bad key \[key\] for x/) });
});
it("never sends the key to a saved link-local, metadata or reserved IP literal, which connects without a lookup", async () => {
diff --git a/server/remote-teammates.ts b/server/remote-teammates.ts
index 45273f6d3c..e3b4c1d555 100644
--- a/server/remote-teammates.ts
+++ b/server/remote-teammates.ts
@@ -19,7 +19,10 @@ import { parseJson } from "./schema.ts";
export const MAX_REMOTE_TEAMMATES = 50;
/** The Bot API's wait is at most 300 s; past that plus this margin the other server isn't answering. */
+const MAX_WAIT_S = 300;
const CALL_MARGIN_MS = 15_000;
+/** The connection may stay quiet as long as the longest call: undici's own 300 s header and body timers would end a full wait first. */
+const LONGEST_CALL_MS = MAX_WAIT_S * 1000 + CALL_MARGIN_MS;
const CHECK_TIMEOUT_MS = 15_000;
const MAX_ANSWER_BYTES = 1_000_000;
const DETAIL_CHARS = 300;
@@ -40,23 +43,34 @@ export function notAServerAddress(address: string): boolean {
return isIP(address.split("%", 1)[0]!) !== 0 && NOT_A_SERVER.has(addressClass(address, NONE_OWN));
}
+const onOpenInternet = (address: string): boolean => isIP(address.split("%", 1)[0]!) !== 0 && addressClass(address, NONE_OWN) === "public";
+
/** Resolves a name as the system does, then refuses it when any address it gives is link-local, metadata or reserved,
- * so a DNS name can't carry a teammate key where a typed address may not go. Runs for every connection a call makes. */
-export function serverOnlyLookup(resolve: LookupFunction = dnsLookup as LookupFunction): LookupFunction {
+ * so a DNS name can't carry a teammate key where a typed address may not go. Runs for every connection a call makes.
+ * `privateOnly` is for plain http: a private-network name (`*.local`, `*.ts.net`) that resolves onto the open internet
+ * would send the key unencrypted. */
+export function serverOnlyLookup(resolve: LookupFunction = dnsLookup as LookupFunction, privateOnly = false): LookupFunction {
return (hostname, options, callback) => resolve(hostname, options, (error, address, family) => {
const found = typeof address === "string" ? [address] : (address ?? []).map((entry) => entry.address);
- const refused = error ? undefined : found.find(notAServerAddress);
+ const refused = error ? undefined : found.find((one) => notAServerAddress(one) || (privateOnly && onOpenInternet(one)));
if (refused === undefined) return (callback as (...args: unknown[]) => void)(error, address, family);
- callback(Object.assign(new Error(`${hostname} resolves to ${refused}, a link-local, metadata or reserved address, not another server`), { code: "ENOTSERVER" }), "", 0);
+ const why = notAServerAddress(refused) ? "a link-local, metadata or reserved address, not another server" : "on the open internet, where plain http isn't encrypted";
+ callback(Object.assign(new Error(`${hostname} resolves to ${refused}, ${why}`), { code: "ENOTSERVER" }), "", 0);
});
}
-let teammateAgent: Agent | undefined;
+/** One for https, one for plain http (private addresses only). */
+const teammateAgents = new Map<boolean, Agent>();
/** fetch whose every connection goes through {@link serverOnlyLookup}. */
async function teammateFetch(url: string, init: RequestInit): Promise<Response> {
const { Agent: UndiciAgent, fetch: undiciFetch } = await import("undici");
- teammateAgent ??= new UndiciAgent({ connect: { lookup: serverOnlyLookup() } });
- return undiciFetch(url, { ...init, dispatcher: teammateAgent } as Parameters<typeof undiciFetch>[1]) as unknown as Promise<Response>;
+ const plain = new URL(url).protocol === "http:";
+ let agent = teammateAgents.get(plain);
+ if (!agent) {
+ agent = new UndiciAgent({ connect: { lookup: serverOnlyLookup(undefined, plain) }, headersTimeout: LONGEST_CALL_MS, bodyTimeout: LONGEST_CALL_MS });
+ teammateAgents.set(plain, agent);
+ }
+ return undiciFetch(url, { ...init, dispatcher: agent } as Parameters<typeof undiciFetch>[1]) as unknown as Promise<Response>;
}
const recordSchema = z.object({
@@ -100,6 +114,8 @@ export function remoteAddress(address: string, botId?: string): { base: string;
} catch {
throw new RemoteTeammateError("that is not a server address; give it like https://maus.example.com", 400);
}
+ // A blob: URL's origin is the https one inside it, so the origin check alone would take it.
+ if (url.protocol !== "https:" && url.protocol !== "http:") throw new RemoteTeammateError("the address must start with https:// (or http:// on a private network)", 400);
if (url.username || url.password || url.search || url.hash) throw new RemoteTeammateError("give the server's address without a sign-in, ? or #", 400);
if (!allowedServerOrigin(url.origin)) {
throw new RemoteTeammateError(url.protocol === "http:" ? `http://${url.host} is on the open internet and plain http isn't encrypted; use its https:// address` : "the address must start with https:// (or http:// on a private network)", 400);
@@ -175,7 +191,7 @@ export class RemoteTeammates {
}
private assertWritable(): void {
- if (this.unreadable) throw new RemoteTeammateError("The saved teammates on other servers could not be read. Repair remote-teammates.json before changing them.", 503);
+ if (this.unreadable) throw new RemoteTeammateError("The saved teammates on other servers could not be read. Repair remote-teammates.json and restart OpenMausBot before changing them.", 503);
}
/** Writes `teammates` and only then keeps them, so a failed write leaves the list as the file has it. */
@@ -205,18 +221,18 @@ export interface RemoteCallOptions {
/** Sends the other bot a message, as any Bot API caller would; `thread` goes on in a thread an earlier answer gave. */
export function sendToRemote(teammate: RemoteTeammate, call: { message: string; thread?: string; wait?: number }, options: RemoteCallOptions = {}): Promise<RemoteResult> {
- const wait = Number.isFinite(call.wait) ? Math.min(300, Math.max(0, call.wait!)) : 50;
+ const wait = Number.isFinite(call.wait) ? Math.min(MAX_WAIT_S, Math.max(0, call.wait!)) : 50;
return callRemote(teammate, "", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ message: call.message, ...(call.thread !== undefined ? { thread: call.thread } : {}), wait }),
- }, Math.ceil(wait * 1000) + CALL_MARGIN_MS, options);
+ }, Math.ceil(wait * 1000) + CALL_MARGIN_MS, options, call.thread);
}
/** Reads a thread an earlier answer gave: its reply once the other bot is done, or what it is doing now. */
export function readRemote(teammate: RemoteTeammate, thread: string, options: RemoteCallOptions = {}): Promise<RemoteResult> {
if (!THREAD_ID.test(thread)) return Promise.resolve({ ok: false, problem: "no_thread" });
- return callRemote(teammate, `?thread=${encodeURIComponent(thread)}`, { method: "GET" }, CHECK_TIMEOUT_MS, options);
+ return callRemote(teammate, `?thread=${encodeURIComponent(thread)}`, { method: "GET" }, CHECK_TIMEOUT_MS, options, thread);
}
/** Whether the other server takes this key, without starting anything there: a read of a thread that can't exist is
@@ -230,7 +246,8 @@ export async function checkRemote(teammate: RemoteTeammate, options: RemoteCallO
return { ok: false, problem: "bad_answer", status: 200 };
}
-async function callRemote(teammate: RemoteTeammate, query: string, init: RequestInit, timeoutMs: number, options: RemoteCallOptions): Promise<RemoteResult> {
+/** `thread`: the thread the call goes on in, which its answer must be about; a call that starts one takes the thread it is given. */
+async function callRemote(teammate: RemoteTeammate, query: string, init: RequestInit, timeoutMs: number, options: RemoteCallOptions, thread?: string): Promise<RemoteResult> {
const timeout = AbortSignal.timeout(timeoutMs);
const signal = options.signal ? AbortSignal.any([options.signal, timeout]) : timeout;
let response: Response;
@@ -260,10 +277,12 @@ async function callRemote(teammate: RemoteTeammate, query: string, init: Request
body = undefined;
}
if (response.status === 200 || response.status === 202) {
- const answer = parseAnswer(body, response.status);
+ const answer = parseAnswer(body, response.status, thread);
return answer ? { ok: true, answer } : { ok: false, problem: "bad_answer", status: response.status };
}
- const detail = typeof (body as { error?: unknown })?.error === "string" ? clip((body as { error: string }).error, DETAIL_CHARS) : undefined;
+ // A server that echoes the key back must not hand it to whoever reads the result; it goes before the clip, so no part is left.
+ const said = (body as { error?: unknown } | undefined)?.error;
+ const detail = typeof said === "string" ? clip(said.split(teammate.key).join("[key]"), DETAIL_CHARS) : undefined;
const retryAfter = Number(response.headers.get("retry-after"));
return {
ok: false, problem: PROBLEM_BY_STATUS[response.status] ?? (response.status >= 500 ? "failed" : "bad_answer"), status: response.status,
@@ -287,10 +306,10 @@ const PROBLEM_BY_STATUS: Record<number, RemoteProblem> = {
};
/** Only the two shapes docs/bot-api.md promises; a proxy's page or anything else is not an answer. */
-function parseAnswer(body: unknown, status: number): BotApiReply | null {
+function parseAnswer(body: unknown, status: number, expected?: string): BotApiReply | null {
if (!body || typeof body !== "object") return null;
const { reply, thread, status: state } = body as Record<string, unknown>;
- if (typeof thread !== "string" || !THREAD_ID.test(thread)) return null;
+ if (typeof thread !== "string" || !THREAD_ID.test(thread) || (expected !== undefined && thread !== expected)) return null;
if (status === 200) return typeof reply === "string" ? { reply, thread } : null;
return state === "working" || state === "needs_approval" ? { thread, status: state } : null;
}