File size: 12,116 Bytes
f3cf1cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
import { afterEach, beforeEach, describe, expect, mock, test } from "bun:test";
import {
  createWorkspace,
  CoreRequestError,
  ensureOidcClient,
  listWorkspaces,
  refreshLoginToken,
  revokeLogin,
  SessionExpiredError,
  type CliWorkspace,
} from "./api";
import type { CliCredentials } from "./credentials";
import { loopbackLogin } from "./loopback-login";
import { startFakeOidcIssuer, type FakeOidcIssuer } from "./testing/fake-oidc-issuer";
import { expectLoopbackPortsFree, freeLoopbackPorts } from "./testing/loopback";

const credentials = {
  token: "token",
  coreUrl: "https://core.example.test",
};

// `mock.restore()` only reverts spies; it leaves a plain `globalThis.fetch = ...`
// assignment in place, so without this the mocked fetch below escapes into every
// test file that happens to run after this one in the same process.
const realFetch = globalThis.fetch;
afterEach(() => {
  mock.restore();
  globalThis.fetch = realFetch;
});

function signInSettingsServer(path: string, answer: () => Response) {
  const requests: string[] = [];
  const server = Bun.serve({
    hostname: "127.0.0.1",
    port: 0,
    fetch(request) {
      const url = new URL(request.url);
      requests.push(url.pathname);
      return url.pathname === path ? answer() : new Response("not found", { status: 404 });
    },
  });
  return { url: `http://127.0.0.1:${server.port}`, requests, stop: () => server.stop(true) };
}

describe("ensureOidcClient", () => {
  let idp: FakeOidcIssuer;
  const stops: Array<() => void> = [];
  afterEach(() => {
    for (const stop of stops.splice(0)) stop();
  });

  async function issuer() {
    idp = await startFakeOidcIssuer({ publicClientId: "mentra-cli" });
    stops.push(() => idp.stop());
    return idp;
  }

  test("uses MENTRA_CLI_OIDC_ISSUER and MENTRA_CLI_CLIENT_ID when both are set, without asking Core", async () => {
    await issuer();
    const core = signInSettingsServer("/api/cli/config", () => Response.json({ issuer: "unused", clientId: "unused" }));
    stops.push(core.stop);
    const config = await ensureOidcClient({ oidcIssuer: idp.issuer, cliClientId: "mentra-cli", coreUrl: core.url });
    expect(config.serverMetadata().issuer).toBe(idp.issuer);
    expect(config.clientMetadata()).toMatchObject({ client_id: "mentra-cli", id_token_signed_response_alg: "EdDSA" });
    expect(core.requests).toEqual([]);
  });

  test("asks Core's /api/cli/config otherwise", async () => {
    await issuer();
    const core = signInSettingsServer("/api/cli/config", () => Response.json({ issuer: idp.issuer, clientId: "mentra-cli" }));
    stops.push(core.stop);
    const config = await ensureOidcClient({ oidcIssuer: "", cliClientId: "", coreUrl: core.url });
    expect(config.serverMetadata().revocation_endpoint).toBe(`${idp.issuer}/revoke`);
    expect(config.clientMetadata().client_id).toBe("mentra-cli");
    expect(core.requests).toEqual(["/api/cli/config"]);
  });

  test("a Core without CLI sign-in says so", async () => {
    const core = signInSettingsServer("/api/cli/config", () =>
      Response.json({ error: "not_configured", error_description: "off" }, { status: 404 }),
    );
    stops.push(core.stop);
    await expect(ensureOidcClient({ coreUrl: core.url })).rejects.toThrow(`The Core at ${core.url} does not offer CLI sign-in.`);
  });

  test("a Core that does not answer with sign-in settings says so", async () => {
    const core = signInSettingsServer("/api/cli/config", () => Response.json({ issuer: "" }));
    stops.push(core.stop);
    await expect(ensureOidcClient({ coreUrl: core.url })).rejects.toThrow(`The Core at ${core.url} did not provide CLI sign-in settings.`);
  });

  test("only one of the two variables is refused", async () => {
    await expect(ensureOidcClient({ oidcIssuer: "https://account.example.test", cliClientId: "" })).rejects.toThrow(
      "Set both MENTRA_CLI_OIDC_ISSUER and MENTRA_CLI_CLIENT_ID, or neither.",
    );
  });

  test("a plain-HTTP issuer off this machine is refused before any request", async () => {
    const core = signInSettingsServer("/api/cli/config", () =>
      Response.json({ issuer: "http://account.example.test", clientId: "mentra-cli" }),
    );
    stops.push(core.stop);
    await expect(ensureOidcClient({ coreUrl: core.url })).rejects.toThrow("must be an HTTPS URL");
  });
});

describe("refresh and revocation", () => {
  let idp: FakeOidcIssuer;
  let freePorts: number[] = [];
  beforeEach(async () => {
    freePorts = await freeLoopbackPorts();
  });
  afterEach(async () => {
    idp?.stop();
    await expectLoopbackPortsFree(freePorts);
  });

  async function signedIn(): Promise<CliCredentials> {
    idp = await startFakeOidcIssuer({ publicClientId: "mentra-cli" });
    const config = await ensureOidcClient({ oidcIssuer: idp.issuer, cliClientId: "mentra-cli" });
    let browser: Promise<unknown> | undefined;
    const result = await loopbackLogin(config, {
      openBrowser: async (url) => {
        browser = idp.approveInBrowser(url, { sub: "mu_1", email: "ada@example.com" });
        return true;
      },
      print: () => {},
    });
    await browser;
    return {
      token: result.accessToken,
      refreshToken: result.refreshToken,
      expiresAt: new Date(result.expiresAt).toISOString(),
      mentraUserId: result.subject,
      email: result.email,
      issuer: idp.issuer,
      clientId: "mentra-cli",
      coreUrl: "https://core.example.test",
      storedAt: new Date().toISOString(),
    };
  }

  test("refresh rotates the refresh token", async () => {
    const login = await signedIn();
    const refreshed = await refreshLoginToken(login);
    expect(refreshed.token).not.toBe(login.token);
    expect(refreshed.refreshToken).not.toBe(login.refreshToken);
    expect(refreshed).toMatchObject({ mentraUserId: "mu_1", email: "ada@example.com", coreUrl: login.coreUrl });
    expect(idp.refreshTokenActive(login.refreshToken)).toBe(false);
    expect(idp.refreshTokenActive(refreshed.refreshToken)).toBe(true);
    expect(idp.accessTokenOwner(refreshed.token)).toMatchObject({ sub: "mu_1" });
  });

  test("reusing a spent refresh token is a session expiry and ends the grant", async () => {
    const login = await signedIn();
    const refreshed = await refreshLoginToken(login);
    const error = await refreshLoginToken(login).catch((caught: unknown) => caught);
    expect(error).toBeInstanceOf(SessionExpiredError);
    expect((error as Error).message).toBe("Session expired. Run `mentra login`.");
    expect(idp.refreshTokenActive(refreshed.refreshToken)).toBe(false);
  });

  test("revokeLogin revokes the refresh token at the revocation endpoint, which then fails (L09)", async () => {
    const login = await signedIn();
    expect(await revokeLogin(login)).toEqual({ confirmed: true });
    expect(idp.revocations).toEqual([{ token: login.refreshToken, hint: "refresh_token", clientId: "mentra-cli" }]);
    await expect(refreshLoginToken(login)).rejects.toBeInstanceOf(SessionExpiredError);
  });

  test("revokeLogin ends only this login", async () => {
    const first = await signedIn();
    const idpForBoth = idp;
    const config = await ensureOidcClient({ oidcIssuer: idp.issuer, cliClientId: "mentra-cli" });
    let browser: Promise<unknown> | undefined;
    const second = await loopbackLogin(config, {
      openBrowser: async (url) => {
        browser = idpForBoth.approveInBrowser(url, { sub: "mu_1" });
        return true;
      },
      print: () => {},
    });
    await browser;
    expect(await revokeLogin(first)).toEqual({ confirmed: true });
    expect(idp.refreshTokenActive(second.refreshToken)).toBe(true);
  });

  test("revokeLogin is not confirmed when the revocation endpoint fails", async () => {
    const login = await signedIn();
    idp.failRevocation = true;
    expect(await revokeLogin(login)).toEqual({ confirmed: false });
    expect(idp.refreshTokenActive(login.refreshToken)).toBe(true);
  });

  test("revokeLogin is not confirmed when the sign-in server cannot be reached", async () => {
    const login = await signedIn();
    idp.stop();
    expect(await revokeLogin(login)).toEqual({ confirmed: false });
  });
});

function workspaceSummary(workspaceId: string, name: string): CliWorkspace {
  return {
    workspaceId,
    name,
    status: "active",
    authorizationRevision: 1,
    membership: { membershipId: `mem_${workspaceId}`, role: "owner" },
    capabilities: [],
  };
}

/** Records every request and answers each with `answer`. */
function recordFetch(answer: (url: string, init?: RequestInit) => Response) {
  const requests: Array<{ url: string; init?: RequestInit }> = [];
  globalThis.fetch = mock(async (url: string | URL | Request, init?: RequestInit) => {
    requests.push({ url: String(url), init });
    return answer(String(url), init);
  }) as unknown as typeof fetch;
  return requests;
}

describe("Core's workspace API", () => {
  test("lists the signed-in person's workspaces with their bearer, and names no workspace in a header", async () => {
    const requests = recordFetch(() => Response.json({ items: [workspaceSummary("ws_1", "Team One")] }));
    expect(await listWorkspaces(credentials)).toEqual([workspaceSummary("ws_1", "Team One")]);
    expect(requests).toHaveLength(1);
    expect(requests[0]?.url).toBe("https://core.example.test/api/workspaces");
    expect(requests[0]?.init?.headers).toEqual({ accept: "application/json", authorization: "Bearer token" });
  });

  test("creates a workspace as JSON", async () => {
    const requests = recordFetch(() => Response.json({ ...workspaceSummary("ws_new", "New Team"), capabilities: [] }, { status: 201 }));
    expect(await createWorkspace(credentials, "New Team")).toMatchObject({ workspaceId: "ws_new", name: "New Team" });
    expect(requests[0]?.url).toBe("https://core.example.test/api/workspaces");
    expect(requests[0]?.init).toMatchObject({
      method: "POST",
      body: JSON.stringify({ name: "New Team" }),
      headers: { "content-type": "application/json", authorization: "Bearer token" },
    });
  });

  test("a refusal keeps Core's status, code and explanation", async () => {
    recordFetch(() => Response.json({ error: "workspace_limit", error_description: "You already have a workspace" }, { status: 409 }));
    const error = await createWorkspace(credentials, "Second").catch((caught: unknown) => caught);
    expect(error).toBeInstanceOf(CoreRequestError);
    expect(error).toMatchObject({ status: 409, code: "workspace_limit", message: "You already have a workspace" });
  });

  test("a refused access token is renewed once and the request retried with the new one", async () => {
    const requests = recordFetch((_url, init) =>
      (init?.headers as Record<string, string>).authorization === "Bearer fresh"
        ? Response.json({ items: [] })
        : Response.json({ error: "unauthorized" }, { status: 401 }),
    );
    const refused: string[] = [];
    const session = { ...credentials, renewToken: async (token: string) => (refused.push(token), "fresh") };
    expect(await listWorkspaces(session)).toEqual([]);
    expect(refused).toEqual(["token"]);
    expect(requests.map((request) => (request.init?.headers as Record<string, string>).authorization)).toEqual([
      "Bearer token",
      "Bearer fresh",
    ]);
    // Later requests of the command carry the renewed token.
    expect(session.token).toBe("fresh");
  });

  test("without a renewed token the refusal stands", async () => {
    const requests = recordFetch(() => Response.json({ error: "unauthorized" }, { status: 401 }));
    const error = await listWorkspaces({ ...credentials, renewToken: async () => null }).catch((caught: unknown) => caught);
    expect(error).toMatchObject({ status: 401, code: "unauthorized" });
    expect(requests).toHaveLength(1);
  });
});