Skip to content

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

44.6 KB
Raw Blame
// "Sign in with Boat" against a local stand-in for Boat (server/testing/fake-boat-oauth.ts): nothing here reaches boat.dev.
import { createServer, request, type IncomingMessage, type Server } from "node:http";
import type { AddressInfo } from "node:net";
import { mkdtempSync, readFileSync, statSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";

import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";

import { BOAT_SIGN_IN_MARK } from "../shared/boat-sign-in.ts";
import { boatFetch } from "./boat.ts";
import { BOAT_SIGN_IN_CALLBACK_PATH, BOAT_SIGN_IN_CLIENT_ID, BOAT_SIGN_IN_PORTS, BOAT_SIGN_IN_SCOPES, BoatSignIn, boatScopeFor, type BoatSignInPersistence } from "./boat-sign-in.ts";
import { createBoatSignInHost, type BoatSignInHost } from "./boat-sign-in-host.ts";
import { BOAT_SIGN_IN_ENV, BOAT_SIGN_IN_FILE, createBoatSignInStore, type BoatSignInStore } from "./boat-sign-in-store.ts";
import { createBoatSignInStore as createDesktopBoatSignInStore } from "../electron/boat-sign-in-store.mjs";
import { createSecureCredentialState } from "../electron/secure-credential-state.mjs";
import { setBoatSignIn } from "./boat-sign-in-use.ts";
import { loadConfig, WORKSPACE_CREDENTIAL_ENV, type AppConfig } from "./config.ts";
import { json } from "./harness/http.ts";
import { redactSecretsInText } from "./redact.ts";
import type { RequestAuth } from "./request-auth.ts";
import { PASS } from "./routes/table.ts";
import { removeTempDir } from "./testing/cleanup.ts";
import { startFakeBoat, type FakeBoat } from "./testing/fake-boat-oauth.ts";
import { excludedWorkspaceAuthPath } from "./workspace-backup-policy.ts";

const PORT = 18799;
const REDIRECTS = BOAT_SIGN_IN_PORTS.map((port) => `http://127.0.0.1:${port}${BOAT_SIGN_IN_CALLBACK_PATH}`);
const SIGNED_IN: AppConfig = { box: { signIn: true } };
const MINUTE = 60_000;

let fake: FakeBoat;
let clock = 1_800_000_000_000;
const savedApi = process.env.OMB_BOAT_API;
const savedKey = process.env.BOX_TOKEN;

/** What was saved, in order, beside the bearers the fake saw: the order is the proof of "saved before used". */
function memory(initial: string | null = null) {
  const state = { value: initial, writes: [] as Array<string | null>, events: [] as string[], fail: false, boatCallsAtSave: [] as number[] };
  const persistence: BoatSignInPersistence = {
    read: () => state.value,
    latest: async () => state.value,
    async write(value) {
      if (state.fail) throw new Error("disk full");
      state.value = value;
      state.writes.push(value);
      state.events.push(`saved:${value ? JSON.parse(value).access : "nothing"}`);
      state.boatCallsAtSave.push(fake.counts.api);
    },
  };
  return { state, persistence };
}

function signInWith(persistence: BoatSignInPersistence, more: Partial<ConstructorParameters<typeof BoatSignIn>[0]> = {}) {
  const signIn = new BoatSignIn({ persistence, api: () => fake.api, now: () => clock, pause: async () => {}, ...more });
  setBoatSignIn(signIn);
  return signIn;
}

async function connect(signIn: BoatSignIn, choice?: Parameters<FakeBoat["approve"]>[1], owner = "owner") {
  const back = new URL(fake.approve(signIn.start(owner, PORT).url, choice));
  const answer = await signIn.callback(back.host, back.search);
  // What connecting itself asked Boat (the account's name) is not what a test counts.
  fake.counts.api = 0;
  fake.bearers.length = 0;
  return { back, answer };
}

const advance = (ms: number) => { clock += ms; fake.advance(ms); };
const tokensOf = (value: string | null) => JSON.parse(value ?? "{}") as { access: string; refresh: string };

beforeAll(async () => {
  fake = await startFakeBoat(BOAT_SIGN_IN_CLIENT_ID, REDIRECTS);
  process.env.OMB_BOAT_API = fake.api;
});
afterAll(async () => {
  await fake.close();
  if (savedApi === undefined) delete process.env.OMB_BOAT_API; else process.env.OMB_BOAT_API = savedApi;
  if (savedKey === undefined) delete process.env.BOX_TOKEN; else process.env.BOX_TOKEN = savedKey;
});
beforeEach(() => {
  delete process.env.BOX_TOKEN;
  fake.requireOrg(false);
  for (const key of Object.keys(fake.counts) as Array<keyof FakeBoat["counts"]>) fake.counts[key] = 0;
  fake.bearers.length = 0;
});
afterEach(() => {
  setBoatSignIn(null);
  vi.restoreAllMocks();
});

describe("signing in", () => {
  it("asks Boat for the least it needs with PKCE, exchanges the code once and keeps the tokens to itself", async () => {
    const { state, persistence } = memory();
    const signIn = signInWith(persistence);
    const started = new URL(signIn.start("owner", PORT).url);
    expect(started.origin + started.pathname).toBe(`${fake.origin}/api/box/oauth2/authorize`);
    expect(Object.fromEntries(started.searchParams)).toMatchObject({
      response_type: "code", client_id: BOAT_SIGN_IN_CLIENT_ID, redirect_uri: `http://127.0.0.1:${PORT}/api/boat/oauth/callback`,
      scope: BOAT_SIGN_IN_SCOPES.join(" "), code_challenge_method: "S256",
    });
    for (const never of ["billing.write", "ssh", "environment.read", "environment.write", "environment.values.read", "sandbox.delete-own", "sandbox.fork", "agent.prompt", "host", "network.write", "snapshot.read", "snapshot.write"]) {
      expect(BOAT_SIGN_IN_SCOPES as readonly string[]).not.toContain(never);
    }
    expect(signIn.status(false, "owner")).toMatchObject({ available: true, state: "none", pending: true });

    const back = new URL(fake.approve(started.href));
    const answer = await signIn.callback(back.host, back.search);
    expect(answer).toMatchObject({ status: 200, title: "Signed in to Boat" });
    const { access, refresh } = tokensOf(state.value);
    expect(access).toMatch(/^boat_/);
    expect(refresh).toMatch(/^boatrt_/);
    expect(JSON.stringify(answer)).not.toContain(back.searchParams.get("code")!);
    expect(fake.counts.token).toBe(1);

    const status = signIn.status(false, "owner");
    expect(status).toEqual({ available: true, state: "connected", account: "[email protected]", missingScopes: [], used: true, keySaved: false, last: { outcome: "connected" } });
    expect(JSON.stringify(status)).not.toContain(access);
    expect(JSON.stringify(status)).not.toContain(refresh);

    const listed = await boatFetch(SIGNED_IN, "/sandboxes?limit=1");
    expect(listed.status).toBe(200);
    expect(fake.bearers.at(-1)).toBe(access);
  });

  it("refuses a callback whose state is not the one it sent, is repeated, comes for another address or comes too late", async () => {
    const { state, persistence } = memory();
    const signIn = signInWith(persistence);
    expect((await signIn.callback(`127.0.0.1:${PORT}`, "?code=x&state=y")).status).toBe(400);

    const good = new URL(fake.approve(signIn.start("owner", PORT).url));
    const code = good.searchParams.get("code")!, sent = good.searchParams.get("state")!;
    for (const search of [`?code=${code}&state=${sent}x`, `?code=${code}`, `?code=${code}&state=${sent}&state=${sent}`, `?code=${code}&state=`]) {
      expect((await signIn.callback(good.host, search)).status, search).toBe(400);
    }
    expect((await signIn.callback("127.0.0.1:8799", good.search)).status).toBe(400);
    expect((await signIn.callback("evil.example", good.search)).status).toBe(400);
    expect(fake.counts.token).toBe(0);
    expect(state.value).toBeNull();
    // None of those spent the real one.
    expect((await signIn.callback(good.host, good.search)).status).toBe(200);

    const late = new URL(fake.approve(signIn.start("owner", PORT).url));
    clock += 11 * MINUTE;
    expect((await signIn.callback(late.host, late.search)).status).toBe(400);
  });

  it("a newer start makes the older link worthless", async () => {
    const signIn = signInWith(memory().persistence);
    const older = new URL(fake.approve(signIn.start("owner", PORT).url));
    signIn.start("owner", PORT);
    expect((await signIn.callback(older.host, older.search)).status).toBe(400);
    expect(fake.counts.token).toBe(0);
  });

  it("a person who cancels on Boat's screen connects nothing and is told so", async () => {
    const { state, persistence } = memory();
    const signIn = signInWith(persistence);
    const { answer } = await connect(signIn, { deny: true });
    expect(answer).toMatchObject({ status: 200, title: "Sign-in cancelled" });
    expect(state.value).toBeNull();
    expect(fake.counts.token).toBe(0);
    expect(signIn.status(false, "owner")).toEqual({ available: true, state: "none", keySaved: false, last: { outcome: "cancelled" } });
  });

  it("a callback link opened a second time exchanges nothing", async () => {
    const signIn = signInWith(memory().persistence);
    const { back, answer } = await connect(signIn);
    expect(answer.status).toBe(200);
    expect((await signIn.callback(back.host, back.search)).status).toBe(400);
    expect(fake.counts.token).toBe(1);
    expect(signIn.status(false).state).toBe("connected");
  });

  it("a code Boat no longer accepts ends as a plain failure, never a connection", async () => {
    const { state, persistence } = memory();
    const signIn = signInWith(persistence);
    const first = new URL(fake.approve(signIn.start("owner", PORT).url));
    const code = first.searchParams.get("code")!;
    await signIn.callback(first.host, first.search);
    await signIn.signOut();
    // The same code again under a fresh state: Boat answers invalid_grant.
    const again = new URL(signIn.start("owner", PORT).url);
    const answer = await signIn.callback(first.host, `?code=${code}&state=${again.searchParams.get("state")}&iss=${encodeURIComponent(fake.origin)}`);
    expect(answer.status).toBe(400);
    expect(state.value).toBeNull();
    expect(signIn.status(false, "owner").last).toEqual({ outcome: "failed" });
  });

  it("an answer that names another issuer is refused", async () => {
    const signIn = signInWith(memory().persistence);
    const back = new URL(fake.approve(signIn.start("owner", PORT).url));
    back.searchParams.set("iss", "https://elsewhere.example");
    expect((await signIn.callback(back.host, back.search)).status).toBe(400);
    expect(fake.counts.token).toBe(0);
  });

  it("signing in again while the held token is due for renewal: the account check may renew it, and nothing waits on itself", async () => {
    const { state, persistence } = memory();
    const checks: number[] = [];
    const signIn = signInWith(persistence, {
      // What the server does before a new account replaces the one in use: it asks Boat with the credential held now.
      beforeConnect: async () => { checks.push((await boatFetch(SIGNED_IN, "/sandboxes?limit=1")).status); return null; },
    });
    await connect(signIn);
    const first = tokensOf(state.value);
    advance(58 * MINUTE);
    const { answer } = await connect(signIn);
    expect(answer.status).toBe(200);
    expect(checks).toEqual([401, 200]);
    expect(fake.counts.refresh).toBe(1);
    expect(tokensOf(state.value).refresh).not.toBe(first.refresh);
    expect((await boatFetch(SIGNED_IN, "/sandboxes")).status).toBe(200);
  });

  it("a refused or unsaved sign-in over a working one leaves the working one working: nothing is revoked", async () => {
    const { state, persistence } = memory();
    let refusal: string | null = null;
    const signIn = signInWith(persistence, { beforeConnect: async () => refusal });
    await connect(signIn);
    const kept = state.value;
    refusal = "stop active bot work and computer control before changing the Boat account";
    const refused = await connect(signIn);
    expect(refused.answer).toMatchObject({ status: 400, text: expect.stringContaining("stop active bot work") });
    refusal = null;
    state.fail = true;
    expect((await connect(signIn)).answer.status).toBe(400);
    state.fail = false;
    expect(fake.counts.revoke).toBe(0);
    expect(state.value).toBe(kept);
    expect(signIn.status(false, "owner")).toMatchObject({ state: "connected", last: { outcome: "not-saved" } });
    expect((await boatFetch(SIGNED_IN, "/sandboxes")).status).toBe(200);
  });

  it("a refused first sign-in gives back what Boat issued", async () => {
    const { state, persistence } = memory();
    const signIn = signInWith(persistence, { beforeConnect: async () => "that Boat account cannot access the remembered cloud computers from this installation" });
    expect((await connect(signIn)).answer.status).toBe(400);
    expect(fake.counts.revoke).toBe(1);
    expect(state.value).toBeNull();
    expect(signIn.status(false, "owner")).toEqual({ available: true, state: "none", keySaved: false, last: { outcome: "refused" } });
  });

  it("signing in again does not revoke: a revoke would end the new connection too", async () => {
    const signIn = signInWith(memory().persistence);
    await connect(signIn);
    await connect(signIn);
    expect(fake.counts.revoke).toBe(0);
    expect((await boatFetch(SIGNED_IN, "/sandboxes")).status).toBe(200);
  });
});

describe("renewing", () => {
  it("saves the new refresh token before the new access token is used", async () => {
    const { state, persistence } = memory();
    const signIn = signInWith(persistence);
    await connect(signIn);
    const before = tokensOf(state.value);
    state.events.length = 0;
    state.boatCallsAtSave.length = 0;
    advance(56 * MINUTE);
    const response = await boatFetch(SIGNED_IN, "/sandboxes");
    expect(response.status).toBe(200);
    const after = tokensOf(state.value);
    expect(after.refresh).not.toBe(before.refresh);
    expect(after.access).not.toBe(before.access);
    expect(fake.bearers).toEqual([after.access]);
    expect(state.events).toEqual([`saved:${after.access}`]);
    // Saved while no Boat call had yet been made with it.
    expect(state.boatCallsAtSave).toEqual([0]);
    expect(fake.counts.refresh).toBe(1);
  });

  it("ten callers at once cause one refresh", async () => {
    const signIn = signInWith(memory().persistence);
    await connect(signIn);
    advance(58 * MINUTE);
    const release = fake.holdRefreshes();
    const calls = Array.from({ length: 10 }, () => boatFetch(SIGNED_IN, "/sandboxes"));
    await vi.waitFor(() => expect(fake.counts.refresh).toBe(1));
    release();
    const answers = await Promise.all(calls);
    expect(answers.map((answer) => answer.status)).toEqual(Array(10).fill(200));
    expect(fake.counts.refresh).toBe(1);
    expect(new Set(fake.bearers).size).toBe(1);
    expect(fake.liveConnections()).toBeGreaterThan(0);
  });

  it("asks once more when the answer is lost, and gets the same new tokens", async () => {
    const { state, persistence } = memory();
    const signIn = signInWith(persistence);
    await connect(signIn);
    const before = tokensOf(state.value);
    advance(58 * MINUTE);
    fake.loseNextRefreshAnswer();
    expect((await boatFetch(SIGNED_IN, "/sandboxes")).status).toBe(200);
    expect(fake.counts.refresh).toBe(2);
    expect(tokensOf(state.value).refresh).not.toBe(before.refresh);
    expect(signIn.status(false).state).toBe("connected");
  });

  it("when Boat says invalid_grant it asks the person to sign in again and never tries again", async () => {
    const { state, persistence } = memory();
    const signIn = signInWith(persistence);
    await connect(signIn);
    const before = tokensOf(state.value);
    advance(58 * MINUTE);
    fake.disconnect();
    const first = await boatFetch(SIGNED_IN, "/sandboxes");
    expect(first.status).toBe(401);
    expect(await first.json()).toMatchObject({ boatSignIn: true, message: expect.stringContaining("sign in to Boat again") });
    expect(signIn.status(true)).toMatchObject({ state: "needs-sign-in", used: true, keySaved: true });
    const stored = tokensOf(state.value);
    expect(stored.refresh).toBe("");
    expect(JSON.stringify(state.value)).not.toContain(before.refresh);
    for (let i = 0; i < 3; i += 1) expect((await boatFetch(SIGNED_IN, "/sandboxes")).status).toBe(401);
    expect(fake.counts.refresh).toBe(1);
    // Never the pasted key in its place without being asked: nothing reached Boat at all.
    expect(fake.counts.api).toBe(0);
    // Signing in again is the way out.
    expect((await connect(signIn)).answer.status).toBe(200);
    expect((await boatFetch(SIGNED_IN, "/sandboxes")).status).toBe(200);
  });

  it("does not hand out a renewed token it could not save, and saves it before trying anything else", async () => {
    const { state, persistence } = memory();
    const signIn = signInWith(persistence);
    await connect(signIn);
    advance(58 * MINUTE);
    state.fail = true;
    await expect(boatFetch(SIGNED_IN, "/sandboxes")).rejects.toThrow(/could not be saved/);
    expect(fake.counts.api).toBe(0);
    await expect(boatFetch(SIGNED_IN, "/sandboxes")).rejects.toThrow(/could not be saved/);
    expect(fake.counts.refresh).toBe(1);
    state.fail = false;
    expect((await boatFetch(SIGNED_IN, "/sandboxes")).status).toBe(200);
    expect(fake.counts.refresh).toBe(1);
    expect(fake.bearers).toEqual([tokensOf(state.value).access]);
  });

  it("keeps using a token that is still good while Boat cannot be reached, then says so; the connection is kept", async () => {
    const { state, persistence } = memory();
    let down = false;
    const unreachable: typeof fetch = async (input, init) => {
      if (down) throw Object.assign(new TypeError("fetch failed"), { cause: { code: "ECONNREFUSED" } });
      return fetch(input, init);
    };
    const signIn = signInWith(persistence, { fetch: unreachable });
    await connect(signIn);
    advance(56 * MINUTE);
    down = true;
    expect(await signIn.accessToken()).toBe(tokensOf(state.value).access);
    advance(5 * MINUTE);
    await expect(signIn.accessToken()).rejects.toMatchObject({ problem: "unreachable" });
    expect(signIn.status(false).state).toBe("connected");
    down = false;
    advance(MINUTE);
    expect(await signIn.accessToken()).toBe(tokensOf(state.value).access);
    expect(fake.counts.refresh).toBe(1);
  });

  it("a second server process on the same store takes the renewed tokens and never sends the spent one", async () => {
    const { state, persistence } = memory();
    const first = signInWith(persistence);
    await connect(first);
    const second = new BoatSignIn({ persistence, api: () => fake.api, now: () => clock, pause: async () => {} });
    advance(58 * MINUTE);
    const renewed = await first.accessToken();
    expect(fake.counts.refresh).toBe(1);
    expect(await second.accessToken()).toBe(renewed);
    expect(fake.counts.refresh).toBe(1);
    expect(tokensOf(state.value).access).toBe(renewed);
  });

  it("a token Boat refuses before its time is renewed once and the call repeated", async () => {
    const { state, persistence } = memory();
    const signIn = signInWith(persistence);
    await connect(signIn);
    const stale = tokensOf(state.value).access;
    advance(2 * MINUTE);
    // Something else renewed this connection moments ago (its tokens never reached this store): the access token here is dead.
    const other = new BoatSignIn({ persistence: memory(state.value).persistence, api: () => fake.api, now: () => clock + 58 * MINUTE, pause: async () => {} });
    const fresh = await other.accessToken();
    setBoatSignIn(signIn);
    const response = await boatFetch(SIGNED_IN, "/sandboxes");
    expect(response.status).toBe(200);
    expect(fake.bearers).toEqual([stale, fresh]);
    expect(tokensOf(state.value).access).toBe(fresh);
  });
});

describe("what the person allowed", () => {
  it("a feature whose scope was unticked says so and is never sent; the rest works", async () => {
    const signIn = signInWith(memory().persistence);
    await connect(signIn, { scopes: BOAT_SIGN_IN_SCOPES.filter((scope) => scope !== "sandbox.create" && scope !== "exec") });
    expect(signIn.status(false).missingScopes).toEqual(["sandbox.create", "exec"]);
    expect((await boatFetch(SIGNED_IN, "/sandboxes?limit=1")).status).toBe(200);
    const sent = fake.counts.api;
    const created = await boatFetch(SIGNED_IN, "/sandboxes", { method: "POST", body: "{}" });
    expect(created.status).toBe(403);
    expect(await created.json()).toMatchObject({ error: "api_key_action_forbidden", boatSignIn: true, message: expect.stringMatching(/does not let this app create a cloud computer: "sandbox\.create" was not allowed/) });
    const ran = await boatFetch(SIGNED_IN, "/sandboxes/bx_1/commands", { method: "POST", body: "{}" });
    expect(((await ran.json()) as { message: string }).message).toContain("run commands on a cloud computer");
    expect(fake.counts.api).toBe(sent);
  });

  it("a sign-in that cannot see sandboxes, or names no organization, is refused in its own words, never as a rejected API key", async () => {
    const { state, persistence } = memory();
    const signIn = signInWith(persistence, { beforeConnect: async () => "boat.dev rejected the Boat API key — update it in Settings → AI → Other services" });
    const blind = await connect(signIn, { scopes: BOAT_SIGN_IN_SCOPES.filter((scope) => scope !== "sandbox.read") });
    expect(blind.answer).toMatchObject({ status: 400, text: expect.stringContaining("keep \"sandbox.read\" ticked") });
    fake.requireOrg(true);
    const several = await connect(signIn);
    expect(several.answer).toMatchObject({ status: 400, text: expect.stringContaining("tick one organization only on Boat's screen") });
    for (const answer of [blind.answer, several.answer]) expect(answer.text).not.toContain("API key");
    expect(state.value).toBeNull();
    expect(signIn.status(false, "owner").last).toEqual({ outcome: "refused" });
  });

  it("without account.read it connects and shows no account", async () => {
    const signIn = signInWith(memory().persistence);
    await connect(signIn, { scopes: BOAT_SIGN_IN_SCOPES.filter((scope) => scope !== "account.read") });
    const status = signIn.status(false);
    expect(status).toMatchObject({ state: "connected", missingScopes: ["account.read"] });
    expect(status.account).toBeUndefined();
  });

  it("a sign-in made when only sandbox.delete-own was asked for stays signed in; Boat's refusal to delete says what to do", async () => {
    const signIn = signInWith(memory().persistence);
    await connect(signIn, { scopes: [...BOAT_SIGN_IN_SCOPES.filter((scope) => scope !== "sandbox.delete"), "sandbox.delete-own"] });
    expect(signIn.status(false)).toMatchObject({ state: "connected", missingScopes: [] });
    const refused = await boatFetch(SIGNED_IN, "/sandboxes/bx_made_with_a_key", { method: "DELETE" });
    expect(refused.status).toBe(403);
    expect(await refused.json()).toMatchObject({ boatSignIn: true, message: expect.stringContaining("keep \"sandbox.delete\" ticked") });
  });

  it("with sandbox.delete unticked, a delete is not sent and says which permission is missing", async () => {
    const signIn = signInWith(memory().persistence);
    await connect(signIn, { scopes: BOAT_SIGN_IN_SCOPES.filter((scope) => scope !== "sandbox.delete") });
    expect(signIn.status(false).missingScopes).toEqual(["sandbox.delete"]);
    const refused = await boatFetch(SIGNED_IN, "/sandboxes/bx_1", { method: "DELETE" });
    expect(await refused.json()).toMatchObject({ error: "api_key_action_forbidden", message: expect.stringContaining("delete a cloud computer: \"sandbox.delete\" was not allowed") });
    expect(fake.counts.api).toBe(0);
  });

  it("Boat's own refusals of a sign-in are put in plain words, not called a rejected API key", async () => {
    const signIn = signInWith(memory().persistence);
    await connect(signIn);
    fake.requireOrg(true);
    const refused = await boatFetch(SIGNED_IN, "/sandboxes");
    expect(refused.status).toBe(400);
    expect(await refused.json()).toMatchObject({ error: "org_required", boatSignIn: true, message: expect.stringContaining("several organizations") });
  });

  it("knows which scope each call the app makes needs", () => {
    expect([
      boatScopeFor("GET", "/sandboxes?limit=1"), boatScopeFor("POST", "/sandboxes"), boatScopeFor("GET", "/sandboxes/bx_1"),
      boatScopeFor("PATCH", "/sandboxes/bx_1"), boatScopeFor("DELETE", "/sandboxes/bx_1"), boatScopeFor("POST", "/sandboxes/bx_1/resume"),
      boatScopeFor("POST", "/sandboxes/bx_1/stop"), boatScopeFor("POST", "/sandboxes/bx_1/commands"), boatScopeFor("GET", "/sandboxes/bx_1/commands/p1?tailBytes=1"),
      boatScopeFor("POST", "/sandboxes/bx_1/desktop?vnc=1"), boatScopeFor("GET", "/sandboxes/bx_1/files?path=a"), boatScopeFor("PUT", "/sandboxes/bx_1/files"),
      boatScopeFor("POST", "/sandboxes/bx_1/files/download-url"), boatScopeFor("POST", "/sandboxes/bx_1/files/upload-url"), boatScopeFor("GET", "/sandboxes/bx_1/artifacts?path=a"),
      boatScopeFor("GET", "/me"), boatScopeFor("GET", "/deletion-operations/op_1"),
    ]).toEqual(["sandbox.read", "sandbox.create", "sandbox.read", "sandbox.update", "sandbox.delete", "sandbox.resume", "sandbox.stop", "exec", "exec", "desktop",
      "file.read", "file.write", "file.read", "file.write", "file.read", "account.read", null]);
  });
});

describe("a pasted API key beside the sign-in", () => {
  it("a key alone is sent as it always was", async () => {
    setBoatSignIn(null);
    await boatFetch({ box: { token: "boat_pasted_key_0001" } }, "/sandboxes");
    expect(fake.bearers).toEqual(["boat_pasted_key_0001"]);
  });

  it("the one set last is used, the other stays, and removing one leaves the other", async () => {
    const { state, persistence } = memory();
    const signIn = signInWith(persistence);
    process.env.BOX_TOKEN = "boat_pasted_key_0002";
    expect(loadConfig().box).toEqual({ token: "boat_pasted_key_0002" });

    // Signed in after the key: the sign-in is used.
    await connect(signIn);
    expect(signIn.status(true)).toMatchObject({ state: "connected", used: true, keySaved: true });
    expect(loadConfig().box).toEqual({ token: "boat_pasted_key_0002", signIn: true });
    await boatFetch(loadConfig(), "/sandboxes");
    expect(fake.bearers.at(-1)).toBe(tokensOf(state.value).access);
    // A credential named by its token is exactly that one, whatever is in use.
    await boatFetch({ box: { token: "boat_pasted_key_0002" } }, "/sandboxes");
    expect(fake.bearers.at(-1)).toBe("boat_pasted_key_0002");
    await boatFetch({ box: { token: BOAT_SIGN_IN_MARK } }, "/sandboxes");
    expect(fake.bearers.at(-1)).toBe(tokensOf(state.value).access);

    // A key saved after the sign-in: the key is used, the sign-in stays connected.
    await signIn.preferKey();
    expect(signIn.status(true)).toMatchObject({ state: "connected", used: false });
    expect(loadConfig().box).toEqual({ token: "boat_pasted_key_0002" });
    await boatFetch(loadConfig(), "/sandboxes");
    expect(fake.bearers.at(-1)).toBe("boat_pasted_key_0002");

    // The key removed: the sign-in is what is left, and is used.
    delete process.env.BOX_TOKEN;
    expect(signIn.status(false)).toMatchObject({ state: "connected", used: true, keySaved: false });
    expect(loadConfig().box).toEqual({ signIn: true });

    // The sign-in removed: the key, saved again, is what is left.
    process.env.BOX_TOKEN = "boat_pasted_key_0002";
    expect(await signIn.signOut()).toEqual({ revoked: true });
    expect(fake.counts.revoke).toBe(1);
    expect(state.value).toBeNull();
    expect(signIn.status(true)).toEqual({ available: true, state: "none", keySaved: true });
    expect(loadConfig().box).toEqual({ token: "boat_pasted_key_0002" });
  });

  it("with sign-in not offered, nothing is read, started or used", async () => {
    const { state, persistence } = memory(JSON.stringify({ v: 1, refresh: "boatrt_x", access: "boat_x", expiresAt: clock + 60 * MINUTE, scopes: [], prefer: "signIn", connectedAt: 1 }));
    const signIn = signInWith(persistence, { enabled: false });
    expect(signIn.status(true)).toEqual({ available: false, state: "none", keySaved: true });
    expect(() => signIn.start("owner", PORT)).toThrow();
    expect(signIn.used(false)).toBe(false);
    expect((await signIn.callback(`127.0.0.1:${PORT}`, "?code=a&state=b")).status).toBe(400);
    expect(state.writes).toEqual([]);
  });

  it("only the three registered ports are ever a return address", () => {
    const signIn = signInWith(memory().persistence);
    expect(() => signIn.start("owner", 5199)).toThrow();
    expect(() => signIn.start("owner", 8800)).toThrow();
    for (const port of BOAT_SIGN_IN_PORTS) expect(new URL(signIn.start("owner", port).url).searchParams.get("redirect_uri")).toBe(`http://127.0.0.1:${port}/api/boat/oauth/callback`);
  });
});

describe("the tokens stay on the server", () => {
  it("are masked in anything logged and never written by the sign-in itself", async () => {
    const lines: string[] = [];
    for (const level of ["log", "info", "warn", "error", "debug"] as const) vi.spyOn(console, level).mockImplementation((...args) => { lines.push(args.map(String).join(" ")); });
    const { state, persistence } = memory();
    const signIn = signInWith(persistence);
    const { back } = await connect(signIn);
    const first = tokensOf(state.value);
    advance(58 * MINUTE);
    await boatFetch(SIGNED_IN, "/sandboxes");
    fake.disconnect();
    advance(58 * MINUTE);
    await boatFetch(SIGNED_IN, "/sandboxes");
    const second = tokensOf(state.writes.at(-2) ?? null);
    const all = lines.join("\n");
    for (const secret of [first.access, first.refresh, second.access, second.refresh, back.searchParams.get("code")!]) {
      if (secret) expect(all).not.toContain(secret);
    }
    await connect(signIn);
    const held = tokensOf(state.value);
    expect(redactSecretsInText(`curl -H "authorization: Bearer ${held.access}" and ${held.refresh}`)).not.toMatch(/boat_|boatrt_/);
  });

  it("the connection's environment name is stripped from everything a bot runs", () => {
    expect(WORKSPACE_CREDENTIAL_ENV).toContain(BOAT_SIGN_IN_ENV);
  });
});

describe("where the connection is kept", () => {
  let dir: string;
  beforeEach(() => { dir = mkdtempSync(join(tmpdir(), "omb-boat-sign-in-")); });
  afterEach(async () => { await removeTempDir(dir); });

  it("an app run from source keeps it in an owner-only file that no backup carries", async () => {
    const store = createBoatSignInStore({ dataDir: dir, env: {}, post: () => false });
    expect(store.persistence.read()).toBeNull();
    await store.persistence.write("{\"v\":1}");
    expect(readFileSync(join(dir, BOAT_SIGN_IN_FILE), "utf8")).toBe("{\"v\":1}");
    if (process.platform !== "win32") expect(statSync(join(dir, BOAT_SIGN_IN_FILE)).mode & 0o777).toBe(0o600);
    expect(await store.persistence.latest()).toBe("{\"v\":1}");
    expect(excludedWorkspaceAuthPath(BOAT_SIGN_IN_FILE)).toBe(true);
    await store.persistence.write(null);
    expect(store.persistence.read()).toBeNull();
  });

  it("in the packaged app a key saved beside a sign-in never waits on the queue it is saved through", async () => {
    // The app's real serialized credential writer, its real store, and the server's store, joined as the private port joins them.
    const credentials = createSecureCredentialState({}, async () => {});
    let server: BoatSignInStore;
    const desktop = createDesktopBoatSignInStore({ packaged: true, read: () => credentials.read(), update: (derive) => credentials.update(derive), log: () => {} });
    const port = { postMessage: (message: unknown) => { server.receive(message); } };
    server = createBoatSignInStore({ dataDir: dir, env: { [BOAT_SIGN_IN_ENV]: "" }, post: (message) => desktop.receive(port, message) });
    const signIn = signInWith(server.persistence);
    expect((await connect(signIn)).answer.status).toBe(200);
    const kept = () => JSON.parse(String(credentials.read().boatSignIn)) as { prefer: string; access: string };
    expect(kept().prefer).toBe("signIn");

    // The app saves a pasted key: the server's part of that save runs inside the writer's turn, as PUT /api/config does.
    let saving: Promise<void> | undefined;
    await credentials.update((document) => ({ ...document, boxToken: "boat_pasted_key_0003" }), async () => {
      saving = signIn.preferKey();
      // Used at once, though its save can only land after this turn ends.
      expect(signIn.used(true)).toBe(false);
    });
    await saving;
    expect(kept().prefer).toBe("key");
    expect(credentials.read().boxToken).toBe("boat_pasted_key_0003");

    // A renewal that comes due inside such a turn is started, not waited for, and is saved once the turn ends.
    advance(58 * MINUTE);
    expect(signIn.renewalDue()).toBe(true);
    const before = kept().access;
    let renewing: Promise<string> | undefined;
    await credentials.update((document) => document, async () => { renewing = signIn.accessToken(); });
    const renewed = await renewing!;
    expect(renewed).not.toBe(before);
    expect(kept()).toMatchObject({ access: renewed, prefer: "key" });
    expect(signIn.renewalDue()).toBe(false);
  });

  it("the packaged app's server reads it from its environment once, then asks the app to read and save", async () => {
    const env: NodeJS.ProcessEnv = { [BOAT_SIGN_IN_ENV]: "{\"v\":1}" };
    const kept = { value: "{\"v\":1}" as string | null };
    let answering = true;
    const store = createBoatSignInStore({
      dataDir: dir, env,
      post: (message) => {
        if (!answering) return false;
        if (message.op === "write") kept.value = message.value ?? null;
        queueMicrotask(() => store.receive({ type: "openmausbot:boat-sign-in-store-result", requestId: message.requestId, ok: true, ...(message.op === "read" ? { value: kept.value } : {}) }));
        return true;
      },
    });
    expect(env[BOAT_SIGN_IN_ENV]).toBeUndefined();
    expect(store.persistence.read()).toBe("{\"v\":1}");
    await store.persistence.write("{\"v\":2}");
    expect(kept.value).toBe("{\"v\":2}");
    expect(await store.persistence.latest()).toBe("{\"v\":2}");
    expect(() => statSync(join(dir, BOAT_SIGN_IN_FILE))).toThrow();
    answering = false;
    await expect(store.persistence.write("{\"v\":3}")).rejects.toThrow();
    expect(store.receive({ type: "something-else" })).toBe(false);
  });
});

describe("on the server", () => {
  const owner: RequestAuth = { kind: "loopback", scopes: [] } as unknown as RequestAuth;
  let dir: string;
  let http: Server;
  let origin: string;
  let host: BoatSignInHost;
  let cfg: AppConfig;
  const transitions = new Set<"box" | "vps">();

  const make = (more: Partial<Parameters<typeof createBoatSignInHost>[0]> = {}) => {
    cfg = loadConfig();
    host = createBoatSignInHost({
      desktop: true, hosted: false, port: PORT, dataDir: dir, cfg, env: {}, refresh: () => { Object.assign(cfg, loadConfig()); },
      managedBoatOwners: () => [], operationConflict: () => null, transitions, post: () => false, ...more,
    });
    // The clock of the host's own sign-in is the real one; nothing below waits on it.
    return host;
  };
  const call = (method: string, path: string, auth: RequestAuth = owner, headers: Record<string, string> = {}) => new Promise<{ status: number; body: any }>((done, fail) => {
    const req = { method, headers } as unknown as IncomingMessage;
    const chunks: string[] = [];
    const res = { headersSent: false, writableEnded: false, statusCode: 0, setHeader() {}, getHeader() { return undefined; },
      writeHead(status: number) { this.statusCode = status; this.headersSent = true; return this; },
      end(text?: string) { if (text) chunks.push(text); this.writableEnded = true; done({ status: this.statusCode, body: chunks.length ? JSON.parse(chunks.join("")) : null }); } };
    void host.routes({ req, res: res as never, url: new URL(path, "http://127.0.0.1"), path, method, auth, json, readBody: (async () => ({})) as never })
      .then((out) => { if (out === PASS) done({ status: 0, body: null }); }, fail);
  });
  const get = (path: string, method = "GET", headers: Record<string, string> = {}) => new Promise<{ status: number; headers: IncomingMessage["headers"]; text: string }>((done, fail) => {
    const target = new URL(path, origin);
    const req = request({ hostname: target.hostname, port: target.port, path: target.pathname + target.search, method, headers: { host: `127.0.0.1:${PORT}`, ...headers } }, (res) => {
      let text = "";
      res.on("data", (chunk) => { text += chunk; });
      res.on("end", () => done({ status: res.statusCode ?? 0, headers: res.headers, text }));
    });
    req.on("error", fail);
    req.end();
  });

  beforeEach(async () => {
    dir = mkdtempSync(join(tmpdir(), "omb-boat-sign-in-host-"));
    transitions.clear();
    http = createServer((req, res) => {
      void host.callback(req, res, new URL(req.url ?? "/", "http://127.0.0.1")).then((answered) => { if (!answered) res.writeHead(418).end(); });
    });
    await new Promise<void>((done) => http.listen(0, "127.0.0.1", done));
    origin = `http://127.0.0.1:${(http.address() as AddressInfo).port}`;
  });
  afterEach(async () => {
    await new Promise<void>((done) => { http.closeAllConnections(); http.close(() => done()); });
    await removeTempDir(dir);
  });

  it("the whole way: start, Boat's redirect, connected, a Boat call, disconnect", async () => {
    make();
    expect(host.statusPart()).toEqual({ keySaved: false, signIn: { available: true, state: "none", keySaved: false } });
    const started = await call("POST", "/api/boat/sign-in/start");
    expect(started.status).toBe(200);
    expect(Object.keys(started.body)).toEqual(["url"]);
    const back = new URL(fake.approve(started.body.url));
    const page = await get(back.pathname + back.search);
    expect(page.status).toBe(200);
    expect(page.headers["content-type"]).toBe("text/html; charset=utf-8");
    expect(page.text).toContain("Signed in to Boat");
    expect(page.text).toContain("You can close this tab");
    const stored = tokensOf(readFileSync(join(dir, BOAT_SIGN_IN_FILE), "utf8"));
    for (const secret of [back.searchParams.get("code")!, back.searchParams.get("state")!, stored.access, stored.refresh]) {
      expect(page.text).not.toContain(secret);
      expect(JSON.stringify(page.headers)).not.toContain(secret);
    }
    const status = host.statusPart();
    expect(status.signIn).toMatchObject({ state: "connected", account: "[email protected]", used: true, missingScopes: [] });
    expect(JSON.stringify(status)).not.toMatch(/boat_|boatrt_/);
    // The live config now names the sign-in, and a Boat call made with it carries the sign-in's bearer.
    expect(cfg.box?.signIn).toBe(true);
    expect((await boatFetch(cfg, "/sandboxes?limit=1")).status).toBe(200);
    expect(fake.bearers.at(-1)).toBe(stored.access);

    const out = await call("DELETE", "/api/boat/sign-in");
    expect(out).toEqual({ status: 200, body: { ok: true, revoked: true } });
    expect(fake.counts.revoke).toBe(1);
    expect(() => readFileSync(join(dir, BOAT_SIGN_IN_FILE))).toThrow();
    expect(cfg.box?.signIn).toBeUndefined();
    expect(host.statusPart().signIn).toEqual({ available: true, state: "none", keySaved: false });
  });

  it("the callback is a plain page for a browser's own navigation: GET only, no CORS, never a redirect", async () => {
    make();
    const started = await call("POST", "/api/boat/sign-in/start");
    const back = new URL(fake.approve(started.body.url));
    const posted = await get(back.pathname + back.search, "POST");
    expect(posted.status).toBe(405);
    for (const method of ["PUT", "DELETE", "OPTIONS", "HEAD"]) expect((await get(back.pathname + back.search, method)).status, method).toBe(405);
    expect(fake.counts.token).toBe(0);

    const tries = [
      "?state=wrong&code=x", "?error=access_denied&state=wrong", "", "?redirect_uri=https://evil.example&next=https://evil.example&state=x&code=y",
      `?code=x&state=${back.searchParams.get("state")}x&return_to=//evil.example`,
    ];
    for (const search of tries) {
      const answer = await get(`${BOAT_SIGN_IN_CALLBACK_PATH}${search}`, "GET", { origin: "https://evil.example" });
      expect(answer.status, search).toBe(400);
      expect(answer.headers.location).toBeUndefined();
      expect(Object.keys(answer.headers).filter((name) => name.startsWith("access-control-"))).toEqual([]);
      expect(answer.text).not.toContain("evil.example");
      expect(answer.headers["cache-control"]).toBe("no-store");
      expect(answer.headers["content-security-policy"]).toContain("default-src 'none'");
    }
    // A site that guesses the path gets nothing done, and the real answer still works afterwards.
    const real = await get(back.pathname + back.search, "GET", { origin: "https://evil.example" });
    expect(real.status).toBe(200);
    expect(real.headers.location).toBeUndefined();
    expect(Object.keys(real.headers).filter((name) => name.startsWith("access-control-"))).toEqual([]);
    expect((await get("/api/boat/oauth/callback/extra")).status).toBe(418);
  });

  it("only the desktop app's own page on this computer may start, cancel or disconnect", async () => {
    make();
    const strangers: Array<[string, RequestAuth, Record<string, string>]> = [
      ["a shared server's local caller", { kind: "loopback", scopes: [], trust: "service" } as unknown as RequestAuth, {}],
      ["a paired phone", { kind: "loopback", scopes: [], companionDevice: "phone-1" } as unknown as RequestAuth, {}],
      ["a companion request", owner, { "x-openmausbot-companion": "1" }],
      ["a signed-in session", { kind: "session", scopes: ["admin", "client"], session: {} } as unknown as RequestAuth, {}],
    ];
    for (const [who, auth, headers] of strangers) {
      for (const [method, path] of [["POST", "/api/boat/sign-in/start"], ["POST", "/api/boat/sign-in/cancel"], ["DELETE", "/api/boat/sign-in"]]) {
        expect((await call(method!, path!, auth, headers)).status, `${who} ${path}`).toBe(403);
      }
    }
    expect((await call("GET", "/api/boat/sign-in/start")).status).toBe(404);
    expect((await call("GET", "/api/config")).status).toBe(0);
  });

  it("is not offered on a self-hosted server, a hosted Cloud or any other port: paste a key only", async () => {
    for (const more of [{ desktop: false }, { hosted: true }, { port: 5199 }, { port: 8800 }]) {
      make(more);
      // Exactly what the config said before sign-in existed: nothing added.
      expect(host.statusPart(), JSON.stringify(more)).toEqual({});
      expect((await call("POST", "/api/boat/sign-in/start")).status).toBe(403);
      expect((await get(`${BOAT_SIGN_IN_CALLBACK_PATH}?code=a&state=b`)).status).toBe(404);
      expect(host.signIn.used(false)).toBe(false);
    }
    for (const port of BOAT_SIGN_IN_PORTS) expect(make({ port }).statusPart().signIn?.available).toBe(true);
  });

  it("a sign-in Boat has ended can always be disconnected: it is only forgotten", async () => {
    make();
    const back = new URL(fake.approve((await call("POST", "/api/boat/sign-in/start")).body.url));
    expect((await get(back.pathname + back.search)).status).toBe(200);
    fake.disconnect();
    // Found out by a call: the connection is now "sign in again".
    const stored = JSON.parse(readFileSync(join(dir, BOAT_SIGN_IN_FILE), "utf8"));
    writeFileSync(join(dir, BOAT_SIGN_IN_FILE), JSON.stringify({ ...stored, expiresAt: 0 }));
    make();
    Object.assign(cfg, loadConfig());
    expect(cfg.box?.signIn).toBe(true);
    expect((await boatFetch(cfg, "/sandboxes?limit=1")).status).toBe(401);
    expect(host.statusPart().signIn?.state).toBe("needs-sign-in");
    const revokes = fake.counts.revoke;
    expect(await call("DELETE", "/api/boat/sign-in")).toEqual({ status: 200, body: { ok: true, revoked: true } });
    expect(fake.counts.revoke).toBe(revokes);
    expect(host.statusPart().signIn).toEqual({ available: true, state: "none", keySaved: false });
  });

  it("cancelling in the app spends the link", async () => {
    make();
    const started = await call("POST", "/api/boat/sign-in/start");
    expect(host.statusPart().signIn?.pending).toBe(true);
    expect((await call("POST", "/api/boat/sign-in/cancel")).status).toBe(200);
    expect(host.statusPart().signIn?.pending).toBeUndefined();
    const back = new URL(fake.approve(started.body.url));
    expect((await get(back.pathname + back.search)).status).toBe(400);
  });

  it("does not connect while a cloud computer is busy or another account change is under way", async () => {
    let conflict: string | null = "stop active bot work and computer control before changing the Boat account";
    make({ operationConflict: () => conflict });
    let back = new URL(fake.approve((await call("POST", "/api/boat/sign-in/start")).body.url));
    let page = await get(back.pathname + back.search);
    expect(page.status).toBe(400);
    expect(page.text).toContain("stop active bot work");
    expect(host.statusPart().signIn).toMatchObject({ state: "none", last: { outcome: "refused" } });
    // What Boat issued for the refused sign-in was given back.
    expect(fake.counts.revoke).toBe(1);

    conflict = null;
    transitions.add("box");
    back = new URL(fake.approve((await call("POST", "/api/boat/sign-in/start")).body.url));
    page = await get(back.pathname + back.search);
    expect(page.status).toBe(400);
    expect(transitions.has("box")).toBe(true);
    transitions.clear();
    back = new URL(fake.approve((await call("POST", "/api/boat/sign-in/start")).body.url));
    expect((await get(back.pathname + back.search)).status).toBe(200);
    expect(transitions.size).toBe(0);
  });
});