-
Notifications
You must be signed in to change notification settings - Fork 1.2k
add deployment-wide user directory for user search #474
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
maxwellpeterson
wants to merge
2
commits into
main
Choose a base branch
from
mpeterson/user-directory
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
80 changes: 80 additions & 0 deletions
80
packages/workshop-backend/__integration__/user-directory-rpc.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,80 @@ | ||
| import { createExecutionContext } from "cloudflare:test"; | ||
| import { env, exports } from "cloudflare:workers"; | ||
| import { newWebSocketRpcSession, type RpcStub } from "capnweb"; | ||
| import type { PublicApi } from "@gadgets/workshop-shared/api"; | ||
| import { describe, expect, it } from "vitest"; | ||
| import server from "../src/server"; | ||
|
|
||
| const PASSWORD_HASH = new Uint8Array([1, 2, 3]); | ||
|
|
||
| async function connect(): Promise<RpcStub<PublicApi>> { | ||
| const response = await server.fetch(new Request("https://workshop.invalid/api", { | ||
| headers: { Upgrade: "websocket" }, | ||
| }), env, createExecutionContext()); | ||
| expect(response.status).toBe(101); | ||
| const socket = response.webSocket; | ||
| if (!socket) throw new TypeError("Expected a WebSocket response."); | ||
| socket.accept(); | ||
| return newWebSocketRpcSession<PublicApi>(socket); | ||
| } | ||
|
|
||
| async function createAccount( | ||
| publicApi: RpcStub<PublicApi>, prefix: string, displayName: string, | ||
| ): Promise<{ username: string; token: string }> { | ||
| const name = prefix + crypto.randomUUID().replaceAll("-", ""); | ||
| const token = await publicApi.createAccount(name, displayName, PASSWORD_HASH); | ||
| if (token === null) throw new Error(`Failed to create ${name}.`); | ||
| return { username: name, token }; | ||
| } | ||
|
|
||
| // User search is admin policy. The AdminSettings DO is the config's only writer, so go through it | ||
| // (rather than the KV mirror) like AdminApiImpl does; each test sets the state it relies on. | ||
| function setUserSearchEnabled(enabled: boolean): Promise<void> { | ||
| return exports.AdminSettings.getByName("").updateAdminConfig({ userSearchEnabled: enabled }); | ||
| } | ||
|
|
||
| describe("authenticated user directory RPC", () => { | ||
| it("indexes a user when it authenticates and re-indexes on rename", async () => { | ||
| await setUserSearchEnabled(true); | ||
| using publicApi = await connect(); | ||
| const viewer = await createAccount(publicApi, "directoryviewer", "Directory Viewer"); | ||
| const target = await createAccount(publicApi, "directorytarget", "Directory Target Before"); | ||
| using viewerApi = await publicApi.authenticate(viewer.token); | ||
|
|
||
| // createAccount alone does not index: the directory is written where a session is minted. | ||
| await expect(viewerApi.searchUsers("target bef", [])).resolves.toEqual([]); | ||
| using targetApi = await publicApi.authenticate(target.token); | ||
| // The sync is fire-and-forget from the user DO, so the record lands shortly after the call. | ||
| await expect.poll(() => viewerApi.searchUsers("target bef", [])).toEqual([ | ||
| { id: target.username, name: "Directory Target Before" }, | ||
| ]); | ||
| // The authenticated caller is always excluded, and callers can exclude more users. | ||
| await expect(viewerApi.searchUsers("directory viewer", [])).resolves.toEqual([]); | ||
| await expect(viewerApi.searchUsers("target bef", [target.username])).resolves.toEqual([]); | ||
|
|
||
| await targetApi.setOwnDisplayName("Directory Target After"); | ||
| await expect.poll(() => viewerApi.searchUsers("target aft", [])).toEqual([ | ||
| { id: target.username, name: "Directory Target After" }, | ||
| ]); | ||
| await expect(viewerApi.searchUsers("target bef", [])).resolves.toEqual([]); | ||
| }); | ||
|
|
||
| it("hides the directory from users while search is off, without dropping the index", async () => { | ||
| await setUserSearchEnabled(true); | ||
| using publicApi = await connect(); | ||
| const viewer = await createAccount(publicApi, "policyviewer", "Policy Viewer"); | ||
| const target = await createAccount(publicApi, "policytarget", "Policy Target"); | ||
| using viewerApi = await publicApi.authenticate(viewer.token); | ||
| using _targetApi = await publicApi.authenticate(target.token); | ||
| const record = { id: target.username, name: "Policy Target" }; | ||
| await expect.poll(() => viewerApi.searchUsers("policy target", [])).toEqual([record]); | ||
|
|
||
| await setUserSearchEnabled(false); | ||
| await expect(viewerApi.searchUsers("policy target", [])).resolves.toEqual([]); | ||
| await expect(viewerApi.searchUsers(target.username, [])).resolves.toEqual([]); | ||
|
|
||
| // Indexing continued while search was off: the record is there the moment it's turned back on. | ||
| await setUserSearchEnabled(true); | ||
| await expect(viewerApi.searchUsers("policy target", [])).resolves.toEqual([record]); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
147 changes: 147 additions & 0 deletions
147
packages/workshop-backend/__tests__/user-directory.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,147 @@ | ||
| import { env } from "cloudflare:workers"; | ||
| import { describe, expect, it } from "vitest"; | ||
| import type { UserDirectoryDurableObject } from "../src/user-directory.js"; | ||
|
|
||
| declare module "cloudflare:workers" { | ||
| interface ProvidedEnv { | ||
| TEST_USER_DIRECTORY: DurableObjectNamespace<UserDirectoryDurableObject>; | ||
| } | ||
| } | ||
|
|
||
| function directory(name: string) { | ||
| return env.TEST_USER_DIRECTORY.getByName(`${name}-${crypto.randomUUID()}`); | ||
| } | ||
|
|
||
| function user(id: string, name: string) { | ||
| return { id, name }; | ||
| } | ||
|
|
||
| // Await a stub call's rejection with a single handler: expect(...).rejects forks the underlying | ||
| // JsRpcPromise (each .then mints a fresh RPC continuation), and the leftover copy is reported as | ||
| // an unhandled rejection (see overseer-hooks.test.ts). | ||
| async function expectRejection(call: Promise<unknown>, message: string): Promise<void> { | ||
| let caught: unknown; | ||
| let rejected = false; | ||
| try { await call; } catch (err) { rejected = true; caught = err; } | ||
| expect(rejected).toBe(true); | ||
| expect(String(caught)).toContain(message); | ||
| } | ||
|
|
||
| // The first RPC into the DO pays for instantiating the whole backend bundle in its isolate (~5s | ||
| // on a dev machine when the pool is contended, as vitest.integration.config.ts also notes); the | ||
| // remaining calls take milliseconds. | ||
| describe("UserDirectoryDurableObject", { timeout: 30_000 }, () => { | ||
| it("upserts profiles, matches name or id case-insensitively, and excludes requested users", async () => { | ||
| const stub = directory("upsert"); | ||
| await stub.syncUser(user("ada@example.com", "Ada Lovelace"), 0); | ||
| await stub.syncUser(user("grace@example.com", "Grace Hopper"), 0); | ||
|
|
||
| await expect(stub.searchUsers("LOVE", [])).resolves.toEqual([ | ||
| user("ada@example.com", "Ada Lovelace"), | ||
| ]); | ||
| await expect(stub.searchUsers("love", ["ada@example.com"])).resolves.toEqual([]); | ||
| await expect(stub.searchUsers("grace@", ["ada@example.com"])).resolves.toEqual([ | ||
| user("grace@example.com", "Grace Hopper"), | ||
| ]); | ||
|
|
||
| await stub.syncUser(user("ada@example.com", "Augusta Ada King"), 1); | ||
| await expect(stub.searchUsers("lovelace", [])).resolves.toEqual([]); | ||
| await expect(stub.searchUsers("augusta", [])).resolves.toEqual([ | ||
| user("ada@example.com", "Augusta Ada King"), | ||
| ]); | ||
| }); | ||
|
|
||
| it("keeps the highest revision when syncs arrive out of order", async () => { | ||
| const stub = directory("revision"); | ||
| await stub.syncUser(user("ada@example.com", "Newest"), 2); | ||
| // A stale sync (an older snapshot that lost the race) and a replay of the same revision are | ||
| // both ignored; only a higher revision replaces the record. | ||
| await stub.syncUser(user("ada@example.com", "Stale"), 1); | ||
| await stub.syncUser(user("ada@example.com", "Replay"), 2); | ||
| await expect(stub.searchUsers("ada@", [])).resolves.toEqual([ | ||
| user("ada@example.com", "Newest"), | ||
| ]); | ||
|
|
||
| await stub.syncUser(user("ada@example.com", "Newer Still"), 3); | ||
| await expect(stub.searchUsers("ada@", [])).resolves.toEqual([ | ||
| user("ada@example.com", "Newer Still"), | ||
| ]); | ||
| }); | ||
|
|
||
| it("ranks the earliest match first and treats pattern characters literally", async () => { | ||
| const stub = directory("rank"); | ||
| await stub.syncUser(user("al@example.com", "Al Li"), 0); | ||
| await stub.syncUser(user("sally@example.com", "Sally"), 0); | ||
| await stub.syncUser(user("%percent", "Percent"), 0); | ||
| await stub.syncUser(user("q@example.com", "A \"Quoted\" AND Person"), 0); | ||
|
|
||
| await expect(stub.searchUsers("al", [])).resolves.toEqual([ | ||
| user("al@example.com", "Al Li"), | ||
| user("sally@example.com", "Sally"), | ||
| ]); | ||
| await expect(stub.searchUsers("%", [])).resolves.toEqual([ | ||
| user("%percent", "Percent"), | ||
| ]); | ||
| await expect(stub.searchUsers("\"Quoted\" AND", [])).resolves.toEqual([ | ||
| user("q@example.com", "A \"Quoted\" AND Person"), | ||
| ]); | ||
| await expect(stub.searchUsers(" ", [])).resolves.toEqual([]); | ||
| }); | ||
|
|
||
| it("ranks an exact canonical id ahead of an identical display name", async () => { | ||
| const stub = directory("exact-id-rank"); | ||
| await stub.syncUser(user("attacker@example.com", "victim@example.com"), 0); | ||
| await stub.syncUser(user("victim@example.com", "Real Victim"), 0); | ||
|
|
||
| await expect(stub.searchUsers("victim@example.com", [])).resolves.toEqual([ | ||
| user("victim@example.com", "Real Victim"), | ||
| user("attacker@example.com", "victim@example.com"), | ||
| ]); | ||
| }); | ||
|
|
||
| it("does not match across the name/id boundary", async () => { | ||
| const stub = directory("boundary"); | ||
| await stub.syncUser(user("ada@example.com", "Grace"), 0); | ||
|
|
||
| await expect(stub.searchUsers("ceada", [])).resolves.toEqual([]); | ||
| await expect(stub.searchUsers("grace", [])).resolves.toEqual([ | ||
| user("ada@example.com", "Grace"), | ||
| ]); | ||
| // The stored id and name are separated by a newline, so a query may not contain one. | ||
| await expectRejection(stub.searchUsers("com\ngra", []), "no line breaks"); | ||
| await expectRejection(stub.searchUsers("com\rgra", []), "no line breaks"); | ||
| }); | ||
|
|
||
| it("bounds the query length and the distinct exclusions", async () => { | ||
| const stub = directory("bounds"); | ||
| await stub.syncUser(user("ada@example.com", "Ada"), 0); | ||
|
|
||
| await expect(stub.searchUsers("a".repeat(1000), [])).resolves.toEqual([]); | ||
| await expectRejection(stub.searchUsers("a".repeat(1001), []), "at most 1000 characters"); | ||
|
|
||
| const distinct = Array.from({ length: 1000 }, (_, index) => `user${index}`); | ||
| await expect(stub.searchUsers("ada", distinct)).resolves.toEqual([user("ada@example.com", "Ada")]); | ||
| // Duplicates collapse before the limit applies; one more distinct id is over it. | ||
| await expect(stub.searchUsers("ada", [...distinct, ...distinct])).resolves.toEqual([ | ||
| user("ada@example.com", "Ada"), | ||
| ]); | ||
| await expectRejection(stub.searchUsers("ada", [...distinct, "user1000"]), "At most 1000 users"); | ||
| }); | ||
|
|
||
| it("applies exclusions before capping broad matches at ten results", async () => { | ||
| const stub = directory("limit"); | ||
| await Promise.all(Array.from({ length: 12 }, (_, index) => stub.syncUser(user( | ||
| `user${index.toString().padStart(2, "0")}@example.com`, | ||
| `Common Person ${index.toString().padStart(2, "0")}`, | ||
| ), 0))); | ||
|
|
||
| const results = await stub.searchUsers("common", [ | ||
| "user00@example.com", | ||
| "user01@example.com", | ||
| ]); | ||
| expect(results).toHaveLength(10); | ||
| expect(results.map(result => result.id)).toEqual( | ||
| Array.from({ length: 10 }, (_, index) => `user${(index + 2).toString().padStart(2, "0")}@example.com`), | ||
| ); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.