Skip to content
Merged
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
213 changes: 213 additions & 0 deletions api/openapi-desktop-installations.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,213 @@
import { expect, test } from "bun:test";
import { readFileSync } from "node:fs";
import { join } from "node:path";
import { parse } from "yaml";
import { RecordDesktopInstallationBody } from "../app/src/lib/api/generated/product-events/product-events.zod";

/**
* recordDesktopInstallation, as the spec sets it out for both ways OpenBot Desktop signs in: the
* window's page sends it with its own session once it has traded the sign-in's code, and Desktop
* sends it with its own sign-in when it signs in itself. One address, outside any organization,
* an Idempotency-Key, and a body of one random (version 4) UUID and nothing else, which the server
* reads with the same generated schema, made strict.
*/

type Schema = {
$ref?: string;
type?: string;
format?: string;
pattern?: string;
additionalProperties?: boolean;
required?: string[];
properties?: Record<string, Schema>;
};
type Operation = {
operationId: string;
description?: string;
security?: Record<string, string[]>[];
parameters?: { $ref: string }[];
requestBody?: {
required?: boolean;
content: Record<
string,
{ schema: Schema; examples?: Record<string, { $ref: string }> }
>;
};
responses: Record<string, unknown>;
};

const spec = parse(
readFileSync(join(import.meta.dir, "openapi.yaml"), "utf8"),
) as {
paths: Record<string, Record<string, Operation>>;
components: {
securitySchemes: Record<
string,
{ flows?: { authorizationCode?: { scopes?: Record<string, string> } } }
>;
schemas: Record<string, Schema>;
parameters: Record<
string,
{ name: string; in: string; required?: boolean }
>;
examples: Record<string, { value: unknown }>;
};
};

const PATH = "/api/v2/people/me/desktop-installations";
const item = spec.paths[PATH] ?? {};
const operation = item.post as Operation;

test("the address takes only POST, with an Idempotency-Key, and answers 204", () => {
const methods = [
"get",
"put",
"post",
"delete",
"patch",
"head",
"options",
"trace",
];
expect(Object.keys(item).filter((key) => methods.includes(key))).toEqual([
"post",
]);
expect(operation.operationId).toBe("recordDesktopInstallation");
const parameters = (operation.parameters ?? []).map(
(parameter) =>
spec.components.parameters[parameter.$ref.split("/").pop() as string],
);
expect(parameters).toContainEqual(
expect.objectContaining({
name: "Idempotency-Key",
in: "header",
required: true,
}),
);
// The one success, also the answer where product telemetry is off and the report is dropped.
expect(
Object.keys(operation.responses).filter((code) => code.startsWith("2")),
).toEqual(["204"]);
// Nothing comes back with the 204.
expect(
(operation.responses["204"] as { content?: unknown }).content,
).toBeUndefined();
// Outside an organization, so no organization can be not found.
expect(item.parameters).toBeUndefined();
expect(Object.keys(operation.responses)).not.toContain("404");
});

test("the window's page sends it with its session, and Desktop with its own sign-in; nothing else may", () => {
// The page in Desktop's window holds a web session; Desktop's own sign-in is an appOAuth token.
// An API key is automation, not a sign-in from an installation, so it is not offered.
expect(operation.security).toEqual([
{ webSession: [] },
{ appOAuth: ["conversations:write"] },
]);
// The scope is the one the other product events ask for.
const nudge = spec.paths[
"/api/v2/organizations/{organizationId}/nudge-events"
]?.post as Operation;
expect(nudge.security).toContainEqual({ appOAuth: ["conversations:write"] });
});

test("Desktop's one scope, openbot, stands for the scope the operation needs", () => {
// Desktop asks for `openbot` and offline_access alone (connected/address.rs), and `openbot` is
// every other scope of appOAuth, so a sign-in that holds only `openbot` may send it.
const scopes = Object.keys(
spec.components.securitySchemes.appOAuth?.flows?.authorizationCode
?.scopes ?? {},
);
expect(scopes).toContain("openbot");
const needed = (operation.security ?? []).flatMap(
(entry) => entry.appOAuth ?? [],
);
expect(needed.length).toBeGreaterThan(0);
for (const scope of needed) expect(scopes).toContain(scope);
const address = readFileSync(
join(import.meta.dir, "../desktop/src-tauri/src/connected/address.rs"),
"utf8",
);
expect(address).toContain('const OPENBOT: &str = "openbot";');
});

test("the body is one random (version 4) UUID named installationId and nothing else", () => {
expect(operation.requestBody?.required).toBe(true);
const media = operation.requestBody?.content["application/json"];
const ref = media?.schema.$ref?.split("/").pop() as string;
const schema = spec.components.schemas[ref] as Schema;
expect(schema.additionalProperties).toBe(false);
expect(schema.required).toEqual(["installationId"]);
expect(Object.keys(schema.properties ?? {})).toEqual(["installationId"]);
expect(schema.properties?.installationId).toMatchObject({
type: "string",
format: "uuid",
pattern:
"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-4[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$",
});

// The spec's own example is one the generated schema accepts.
const example =
spec.components.examples[
media?.examples?.signedIn?.$ref.split("/").pop() as string
];
expect(RecordDesktopInstallationBody.safeParse(example?.value).success).toBe(
true,
);
// Upper-case hex is still a version 4 UUID.
expect(
RecordDesktopInstallationBody.safeParse({
installationId: "3F2C9A64-8E1B-4C7D-9A35-0B6E2D4F1C88",
}).success,
).toBe(true);
expect(
RecordDesktopInstallationBody.safeParse({ installationId: "not-a-uuid" })
.success,
).toBe(false);
expect(RecordDesktopInstallationBody.safeParse({}).success).toBe(false);
// A UUID of any other version is refused: v1 carries a time and a hardware address, v7 a time,
// and the nil UUID is no installation's.
for (const other of [
"6ba7b810-9dad-11d1-80b4-00c04fd430c8",
"01890a5d-ac96-774b-bcce-b302099a8057",
"00000000-0000-0000-0000-000000000000",
]) {
expect(
RecordDesktopInstallationBody.safeParse({ installationId: other })
.success,
).toBe(false);
}
// Read strictly, as the server reads it (the spec's additionalProperties: false, checked above),
// anything beside the UUID is refused.
expect(
RecordDesktopInstallationBody.strict().safeParse(example?.value).success,
).toBe(true);
for (const extra of [
{ email: "a@b.example" },
{ organizationId: "org_1" },
{ signInPath: "window" },
]) {
expect(
RecordDesktopInstallationBody.strict().safeParse({
...(example?.value as object),
...extra,
}).success,
).toBe(false);
}
});

test("the description says which servers may receive the id, every caller, and the dedupe key", () => {
// One line of prose each, so a reader of the spec alone knows who may receive the id: OpenBot
// Cloud only, never a self-hosted OpenBot; that Move to Cloud's sign-in is a caller beside the
// window's page; and what makes two sends count once.
const text = (operation.description ?? "").replace(/\s+/g, " ");
expect(text).toContain("OpenBot Cloud only");
expect(text).toContain(
"A self-hosted OpenBot never receives it from Desktop.",
);
expect(text).toContain("Move to Cloud's sign-in");
expect(text).toContain(
"Its event id is made from the deployment, the caller's pseudonym and the installation id in lower case",
);
expect(text).toContain("accepted and dropped, whoever sends it");
});
60 changes: 60 additions & 0 deletions api/openapi.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -13944,6 +13944,50 @@ paths:
$ref: '#/components/responses/ServerError'
default:
$ref: '#/components/responses/UnexpectedError'
/api/v2/people/me/desktop-installations:
post:
tags:
- Product events
operationId: recordDesktopInstallation
summary: Record the OpenBot Desktop installation the caller signed in from
description: 'Tell OpenBot that the caller signed in from this OpenBot Desktop installation, by the random id its usage data is sent under at the sign-in, so usage data can join what the installation did before the sign-in with what the caller does after it. OpenBot Cloud only: Desktop''s usage-data switch is consent to CopilotKit, not to a company''s own server, so Desktop hands the id over, or sends it itself, only when the address it signed in to is OpenBot Cloud. A self-hosted OpenBot never receives it from Desktop. One operation serves every way Desktop signs in to OpenBot Cloud. Where Desktop''s window holds the sign-in, Desktop hands the window''s page the id with the sign-in''s code, and the page sends it with its own session once it has traded the code, with keepalive, so it still leaves when the page goes on. Where Desktop signs in itself, as Move to Cloud''s sign-in does, Desktop sends it with that sign-in. Desktop hands the id over only while the person shares usage data, and nothing is sent without that. An installation is the person''s, not an organization''s, and the page has just signed in and names none, so the address names none either. The id is a random (version 4) UUID, made by the installation, and names nothing about the person or the computer; any other version, which could carry a time or a hardware address, is refused. It is best effort: a client sends it once per sign-in with a new Idempotency-Key, waits on nothing, and treats any answer but 204 alike, never retrying, so a server without the operation, which answers 404, changes nothing. Each accepted report goes out with the rest of OpenBot''s product telemetry, beside the caller''s pseudonym, never their email or account id. Its event id is made from the deployment, the caller''s pseudonym and the installation id in lower case, so it repeats for the same caller and installation: when the window and Move to Cloud both send it for one person, distinct ids still count the link once. It joins the two; it merges no one. Where this OpenBot has product telemetry switched off, a valid report is accepted and dropped, whoever sends it.'
security:
- webSession: []
- appOAuth:
- conversations:write
parameters:
- $ref: '#/components/parameters/IdempotencyKey'
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/DesktopInstallation'
examples:
signedIn:
$ref: '#/components/examples/DesktopInstallationSignedIn'
responses:
'204':
description: The report is accepted, including where product telemetry is switched off and it is dropped.
headers:
X-Request-Id:
$ref: '#/components/headers/RequestId'
'400':
$ref: '#/components/responses/InvalidRequest'
'401':
$ref: '#/components/responses/Unauthenticated'
'403':
$ref: '#/components/responses/Forbidden'
'409':
$ref: '#/components/responses/IdempotencyConflict'
'413':
$ref: '#/components/responses/PayloadTooLarge'
'429':
$ref: '#/components/responses/TooManyRequests'
'500':
$ref: '#/components/responses/ServerError'
default:
$ref: '#/components/responses/UnexpectedError'
/api/v2/organizations/{organizationId}/teams:
parameters:
- $ref: '#/components/parameters/OrganizationId'
Expand Down Expand Up @@ -41279,6 +41323,18 @@ components:
description: The organizations to deal with first, as getAccountDeletion lists them.
items:
$ref: '#/components/schemas/AccountDeletionBlocker'
DesktopInstallation:
type: object
description: The OpenBot Desktop installation the caller signed in from, by the random (version 4) UUID it keeps for its usage data. Names nothing about the computer, or about the person, who is the caller.
additionalProperties: false
required:
- installationId
properties:
installationId:
type: string
format: uuid
pattern: ^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-4[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$
description: The random (version 4) UUID OpenBot Desktop sends its usage data under at the sign-in; Desktop's own events carry it as their `deployment_id`. Desktop makes a new one when usage data is turned off and on again, or when the account it is tied to changes or signs out. Any other UUID version is refused.
TeamSource:
type: string
description: 'Where a team comes from. openbot is a team made here. directory is a group of the company''s directory, kept in step with it: its name and its people are the directory''s and can''t be changed here.'
Expand Down Expand Up @@ -63509,6 +63565,10 @@ components:
value:
status: deleting
blockers: []
DesktopInstallationSignedIn:
summary: The caller signed in to OpenBot Cloud from OpenBot Desktop.
value:
installationId: 3f2c9a64-8e1b-4c7d-9a35-0b6e2d4f1c88
TeamPageLast:
summary: An organization's teams, on one page.
value:
Expand Down
1 change: 1 addition & 0 deletions api/openapi/common.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -399,6 +399,7 @@ paths:
/api/v2/people/me/invitations/{invitationId}/decline: { $ref: './organizations.yaml#/paths/~1api~1v2~1people~1me~1invitations~1{invitationId}~1decline' }
/api/v2/people/me/account-deletion: { $ref: './accounts.yaml#/paths/~1api~1v2~1people~1me~1account-deletion' }
/api/v2/people/me/account-deletion/cancel: { $ref: './accounts.yaml#/paths/~1api~1v2~1people~1me~1account-deletion~1cancel' }
/api/v2/people/me/desktop-installations: { $ref: './conversations.yaml#/paths/~1api~1v2~1people~1me~1desktop-installations' }
/api/v2/organizations/{organizationId}/teams: { $ref: './teams.yaml#/paths/~1api~1v2~1organizations~1{organizationId}~1teams' }
/api/v2/organizations/{organizationId}/teams/{teamId}: { $ref: './teams.yaml#/paths/~1api~1v2~1organizations~1{organizationId}~1teams~1{teamId}' }
/api/v2/organizations/{organizationId}/teams/{teamId}/members: { $ref: './teams.yaml#/paths/~1api~1v2~1organizations~1{organizationId}~1teams~1{teamId}~1members' }
Expand Down
Loading
Loading