Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions api/client-boundary.allow.ts
Original file line number Diff line number Diff line change
Expand Up @@ -426,9 +426,9 @@ export const ALLOWED: Allowed[] = [
},
{
file: "desktop/src-tauri/src/move_to_cloud.rs",
what: /^\/api\/v2\/(people\/me\/organizations|organizations\/\{\}\{path\})$/,
what: /^\/api\/v2\/(people\/me\/(organizations|desktop-installations)|organizations\/\{\}\{path\})$/,
rule: "hand-built-v2",
why: "the move to OpenBot Cloud, from Rust, which has no generated client: the export from the OpenBot on this computer and the import into OpenBot Cloud, in the organization each answers for the person",
why: "the move to OpenBot Cloud, from Rust, which has no generated client: the export from the OpenBot on this computer and the import into OpenBot Cloud, in the organization each answers for the person, and the installation told to OpenBot Cloud after the move's sign-in (recordDesktopInstallation, held to the spec by api/openapi-desktop-installations.test.ts)",
},
{
file: "desktop/src-tauri/src/move_to_cloud/tests.rs",
Expand Down
81 changes: 81 additions & 0 deletions api/openapi-desktop-installations.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -211,3 +211,84 @@ test("the description says which servers may receive the id, every caller, and t
);
expect(text).toContain("accepted and dropped, whoever sends it");
});

test("Desktop's own sender asks exactly what the spec takes: POST, this address, installationId, an Idempotency-Key, and only 204 counts", () => {
// Move to Cloud's sign-in sends it itself (desktop/src-tauri/src/move_to_cloud.rs), so its
// request is held to the operation here rather than only to a fake in its own tests.
const sender = readFileSync(
join(import.meta.dir, "../desktop/src-tauri/src/move_to_cloud.rs"),
"utf8",
);
expect(sender).toContain(
`pub const DESKTOP_INSTALLATIONS_PATH: &str = "${PATH}";`,
);
const start = sender.indexOf("pub fn record_desktop_installation(");
expect(start).toBeGreaterThan(-1);
const body = sender.slice(start, sender.indexOf("\n}\n", start));
expect(body).toContain(".post(");
expect(body).not.toMatch(/\.(get|put|patch|delete)\(/);
// The body's one property, by the spec's own name for it.
const schema = spec.components.schemas.DesktopInstallation as Schema;
const names = Object.keys(schema.properties ?? {});
expect(names).toEqual(["installationId"]);
expect(body).toContain(`json!({ "${names[0]}": installation_id })`);
expect(body).toContain('.header("Idempotency-Key", uuid::Uuid::new_v4()');
// An installation is the person's: the request names no organization.
expect(body).not.toContain("OpenBot-Organization");
// The spec's one success; anything else is a refusal, and nothing is sent again.
expect(body).toMatch(/204 => Ok\(\(\)\)/);
expect(body).toContain("redirect::Policy::none()");
});

test("the request Desktop's sender makes, as its own test receives it, is one the spec takes", () => {
// desktop/src-tauri/src/move_to_cloud/tests.rs holds the sender's bytes to this file.
const request = JSON.parse(
readFileSync(
join(
import.meta.dir,
"../app/tests/fixtures/desktop-installation-request.json",
),
"utf8",
),
) as {
method: string;
path: string;
content_type: string;
installation_id: string;
body: string;
idempotency_key: string;
absent_headers: string[];
};
expect(request.method.toLowerCase()).toBe("post");
expect(spec.paths[request.path]?.post).toBe(operation);
expect(Object.keys(operation.requestBody?.content ?? {})).toEqual([
request.content_type,
]);
const body = JSON.parse(request.body);
expect(RecordDesktopInstallationBody.strict().parse(body)).toEqual({
installationId: request.installation_id,
});
const key = (
spec.components.parameters.IdempotencyKey as unknown as {
schema: { minLength: number; maxLength: number };
}
).schema;
expect(request.idempotency_key.length).toBeGreaterThanOrEqual(key.minLength);
expect(request.idempotency_key.length).toBeLessThanOrEqual(key.maxLength);
expect(request.absent_headers).toContain("openbot-organization");
});

test("the window's hand-off key is the one the page reads", () => {
const desktop = readFileSync(
join(import.meta.dir, "../desktop/src-tauri/src/connected/window.rs"),
"utf8",
);
const page = readFileSync(
join(import.meta.dir, "../app/src/lib/auth/window-session.ts"),
"utf8",
);
expect(desktop).toContain('append_pair("installation_id", id)');
expect(page).toContain(
'export const INSTALLATION_ID_KEY = "installation_id";',
);
});
10 changes: 8 additions & 2 deletions app/src/lib/api/request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,12 @@ export type ApiRequestOptions = RequestInit & {
* `revalidated` in lib/api/revalidated.ts.
*/
kept?: { etag: string; body: unknown };
/**
* `false` for a best-effort write that a refusal must leave as it is: a hosted sign-in needing
* renewal (401 `HOSTED_SIGN_IN_RENEWAL_REQUIRED`) starts no renewal, and the write is not kept to be
* sent again. The window's report of a Desktop installation (lib/auth/window-session.ts).
*/
renew?: false;
};

/**
Expand Down Expand Up @@ -69,13 +75,13 @@ export async function apiRequest<T>(
url: string,
options: ApiRequestOptions = {},
): Promise<T> {
const { fallback, onResponse, kept, ...init } = options;
const { fallback, onResponse, kept, renew, ...init } = options;
if (kept) {
const headers = new Headers(init.headers);
headers.set("If-None-Match", kept.etag);
init.headers = headers;
}
const response = await clientRequest(url, init, fallback);
const response = await clientRequest(url, init, fallback, renew);
onResponse?.(response);
if (response.status === 304 && kept) return kept.body as T;
if (response.status === 204) return undefined as T;
Expand Down
79 changes: 74 additions & 5 deletions app/src/lib/auth/window-session.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import { tryClient } from "@/lib/client";
import { recordDesktopInstallation } from "@/lib/api/generated/product-events/product-events";
import { idempotencyKey } from "@/lib/api/request";
import { ClientError, tryClient } from "@/lib/client";
import type { WindowSignInFailure } from "@/lib/desktop/window-sign-in";
import { signInReturnPath } from "./resume";

Expand All @@ -10,6 +12,13 @@ import { signInReturnPath } from "./resume";
* reaches a server or a log, and it is taken off the address at once, so neither the history nor a
* reload has it. The page then asks this OpenBot, from its own origin, for a session in exchange
* (`POST /api/auth/window/session`), and the answer sets the session cookie as any sign-in does.
*
* On OpenBot Cloud, while the person shares usage data, Desktop also puts its installation's
* usage-data id in the fragment (`&installation_id=…`). Once the code is traded, the page tells
* OpenBot Cloud which installation signed in (`recordDesktopInstallation`), so usage data can join
* what the installation did before the sign-in with what the person does after it. Desktop decides:
* it never puts the id in the fragment for a company's OpenBot, its staging copy, or with usage data
* off, and the page sends only what it was given.
*/

/** Where the window's code is swapped for a session. Sign-in's own, outside the API. */
Expand All @@ -21,8 +30,21 @@ export type WindowSignIn = {
codeVerifier: string | null;
/** A path on this app, or home. Never another origin. */
next: string;
/**
* The OpenBot Desktop installation's usage-data id, a random (version 4) UUID, when Desktop put one
* in. Null when it didn't (another OpenBot than Cloud, usage data off, an older Desktop) or when
* what it put is not one.
*/
installationId: string | null;
};

/** The fragment's key for the installation's id, as Desktop writes it (connected/window.rs). */
export const INSTALLATION_ID_KEY = "installation_id";

/** A random (version 4) UUID, in either case: the only id the operation takes. */
const VERSION_4_UUID =
/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;

/**
* Read the code, its verifier and where to go from the address's fragment, and take the fragment off
* the address and out of the history at once.
Expand All @@ -37,9 +59,51 @@ export function takeWindowSignIn(): WindowSignIn {
code: fragment.get("code") || null,
codeVerifier: fragment.get("code_verifier") || null,
next: signInReturnPath(fragment.get("next")) ?? "/",
installationId: onlyInstallationId(fragment.getAll(INSTALLATION_ID_KEY)),
};
}

/** The one id Desktop put in, when it is one: none, two or a malformed one is no id at all. */
function onlyInstallationId(given: string[]): string | null {
const [id] = given;
return given.length === 1 && VERSION_4_UUID.test(id) ? id : null;
}

/**
* Tell OpenBot which Desktop installation the person just signed in from. Best effort, once per
* sign-in: a new Idempotency-Key, no retry, and with keepalive, so it still leaves as the page goes
* on. Never throws. Only a 204 counts: anything else is logged by its status alone, never with the
* id or what came back. An OpenBot without the operation answers 404, which changes nothing.
*/
export async function recordInstallation(
installationId: string,
): Promise<void> {
let status = 0;
try {
await recordDesktopInstallation(
{ installationId },
{ "Idempotency-Key": idempotencyKey() },
{
keepalive: true,
// A refusal asking for the hosted sign-in to be renewed starts no renewal here, and the
// report is not kept to be sent again: it is sent once, and the window goes on.
renew: false,
onResponse: (response) => {
status = response.status;
},
},
);
} catch (error) {
if (error instanceof ClientError) status = error.status;
if (status) console.warn(NOT_RECORDED, status);
else console.warn("The Desktop installation could not be recorded.");
return;
}
if (status !== 204) console.warn(NOT_RECORDED, status);
}

const NOT_RECORDED = "The Desktop installation was not recorded.";

/** How the swap ended: signed in, or why not. */
export type WindowSessionAnswer =
| { signedIn: true }
Expand Down Expand Up @@ -78,22 +142,27 @@ export async function redeemWindowSignIn(
/** What the page does with the window, kept here so a test can stand in for it. */
export const windowSessionDeps = {
go: (path: string) => window.location.replace(path),
record: recordInstallation,
};

let once: Promise<WindowSessionAnswer> | null = null;

/**
* Take the fragment and swap its code, once per page however often the page is drawn: the code is
* spent by the first try. Signed in, the window goes on to `next`, replacing this page in the
* history.
* spent by the first try. Signed in, the page records the installation when Desktop gave its id,
* without waiting for the answer, and the window goes on to `next`, replacing this page in the
* history. A failed swap records nothing.
*/
export function finishWindowSignIn(): Promise<WindowSessionAnswer> {
once ??= (async (): Promise<WindowSessionAnswer> => {
const { code, codeVerifier, next } = takeWindowSignIn();
const { code, codeVerifier, next, installationId } = takeWindowSignIn();
if (!code || !codeVerifier)
return { signedIn: false, reason: "invalid_code" };
const answer = await redeemWindowSignIn(code, codeVerifier);
if (answer.signedIn) windowSessionDeps.go(next);
if (answer.signedIn) {
if (installationId) void windowSessionDeps.record(installationId);
windowSessionDeps.go(next);
}
return answer;
})();
return once;
Expand Down
14 changes: 12 additions & 2 deletions app/src/lib/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -353,6 +353,8 @@ async function refusal(
fallback: string | undefined,
/** The request that was refused, as it was sent, for a write a renewal sends again. */
sent?: { path: string; init: RequestInit },
/** `false`: a refusal that asks for a renewal starts none (`ApiRequestOptions.renew`). */
renew?: false,
): Promise<ClientError> {
const body = (await response.json().catch(() => null)) as {
error?: unknown;
Expand Down Expand Up @@ -385,7 +387,7 @@ async function refusal(
* A hosted OpenBot's sign-in needing renewal, which is never being signed out: renewed in the
* background, and the write it interrupted is sent again once the page is back.
*/
if (renewalRequired(error))
if (renew !== false && renewalRequired(error))
renewHostedSignIn(
response.headers.get(SIGN_IN_HEADER),
sent ? await keepPendingWrite(sent.path, sent.init) : null,
Expand All @@ -404,12 +406,20 @@ export async function clientRequest(
path: string,
init: RequestInit,
fallback?: string,
/** `false`: a refusal that asks for a renewal starts none, and nothing is kept to send again. */
renew?: false,
): Promise<Response> {
const response = await request(path, init);
// A 304 is an answer only to a request that named the copy it holds (`If-None-Match`).
if (response.status === 304 && new Headers(init.headers).has("If-None-Match"))
return response;
if (!response.ok) throw await refusal(response, fallback, { path, init });
if (!response.ok)
throw await refusal(
response,
fallback,
renew === false ? undefined : { path, init },
renew,
);
return response;
}

Expand Down
Loading
Loading