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
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]);
});
});
16 changes: 15 additions & 1 deletion packages/workshop-backend/__tests__/admin-config.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
import { DEFAULT_ADMIN_CONFIG, defaultOutputFormatId, parseAdminConfig, reorderFormats, resolveFormatOutput, sanitizeOutputOverrides, serializeAdminConfig } from "../src/admin-config.js";
import { DEFAULT_ADMIN_CONFIG, defaultOutputFormatId, normalizeAdminConfig, parseAdminConfig, reorderFormats, resolveFormatOutput, sanitizeOutputOverrides, serializeAdminConfig } from "../src/admin-config.js";

describe("parseAdminConfig", () => {
it("backfills fields missing from a config persisted before they existed", () => {
Expand All @@ -11,11 +11,25 @@ describe("parseAdminConfig", () => {
expect(config.signupsEnabled).toBe(false);
expect(config.siteName).toBe("acme");
expect(config.formats).toEqual([]);
expect(config.userSearchEnabled).toBe(true);
for (let key of Object.keys(DEFAULT_ADMIN_CONFIG)) {
expect(config[key as keyof typeof config], key).toBeDefined();
}
});

it("defaults user search opposite signups while preserving an explicit setting", () => {
expect(DEFAULT_ADMIN_CONFIG.userSearchEnabled).toBe(!DEFAULT_ADMIN_CONFIG.signupsEnabled);
expect(parseAdminConfig(JSON.stringify({ signupsEnabled: true })).userSearchEnabled).toBe(false);
expect(parseAdminConfig(JSON.stringify({
signupsEnabled: true,
userSearchEnabled: true,
})).userSearchEnabled).toBe(true);
});

it("applies the dependent default to legacy AdminSettings records", () => {
expect(normalizeAdminConfig({ signupsEnabled: false }).userSearchEnabled).toBe(true);
});

it("drops malformed format entries rather than the whole list", () => {
let config = parseAdminConfig(JSON.stringify({
formats: [
Expand Down
147 changes: 147 additions & 0 deletions packages/workshop-backend/__tests__/user-directory.test.ts
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`),
);
});
});
80 changes: 50 additions & 30 deletions packages/workshop-backend/src/admin-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,12 @@ export type AdminConfig = {
* env-driven (see auth/config.ts).
*/
signupsEnabled: boolean;
/**
* Whether users may search the deployment-wide user directory to find collaborators. When not
* explicitly configured, this defaults to the opposite of `signupsEnabled`. The directory itself
* is maintained either way, and this switch just controls user access.
*/
userSearchEnabled: boolean;
/**
* Site name shown next to the top-bar logo, or "" to use DEFAULT_SITE_NAME. Resolve it for
* display with `resolveSiteName()`.
Expand Down Expand Up @@ -81,6 +87,7 @@ export type FormatCuration = {

export const DEFAULT_ADMIN_CONFIG: AdminConfig = {
signupsEnabled: true,
userSearchEnabled: false,
Comment thread
devin-ai-integration[bot] marked this conversation as resolved.
siteName: "",
siteLogoConfigured: false,
instanceInstructions: "",
Expand Down Expand Up @@ -281,39 +288,52 @@ function strings(value: unknown): string[] {
return Array.isArray(value) ? value.filter((v): v is string => typeof v === "string") : [];
}

/**
* Apply defaults to a partial admin config loaded from either authoritative DO
* storage or its KV mirror.
*/
export function normalizeAdminConfig(p: Partial<AdminConfig>): AdminConfig {
let disabledResources: Record<string, string[]> = {};
if (p.disabledResources && typeof p.disabledResources === "object") {
for (let [vendorId, patterns] of Object.entries(p.disabledResources)) {
let list = strings(patterns);
if (list.length > 0) disabledResources[vendorId] = list;
}
}
let ambientGatekeeperModes: Record<string, AmbientGatekeeperMode> = {};
if (p.ambientGatekeeperModes && typeof p.ambientGatekeeperModes === "object") {
for (let [vendorId, mode] of Object.entries(p.ambientGatekeeperModes)) {
if (isAmbientGatekeeperMode(mode)) ambientGatekeeperModes[vendorId.toLowerCase()] = mode;
}
}
let signupsEnabled = typeof p.signupsEnabled === "boolean"
? p.signupsEnabled
: DEFAULT_ADMIN_CONFIG.signupsEnabled;
return {
signupsEnabled,
userSearchEnabled: typeof p.userSearchEnabled === "boolean"
? p.userSearchEnabled
: !signupsEnabled,
siteName: typeof p.siteName === "string" ? p.siteName : "",
siteLogoConfigured: typeof p.siteLogoConfigured === "boolean" ? p.siteLogoConfigured : false,
instanceInstructions: typeof p.instanceInstructions === "string" ? p.instanceInstructions : "",
announcement: typeof p.announcement === "string" ? p.announcement : "",
banner: {
text: typeof p.banner?.text === "string" ? p.banner.text : "",
color: isBannerColor(p.banner?.color) ? p.banner!.color : DEFAULT_BANNER_COLOR,
},
accentColor: typeof p.accentColor === "string" ? p.accentColor : "",
disabledResources,
disabledGatekeepers: strings(p.disabledGatekeepers).map(v => v.toLowerCase()),
ambientGatekeeperModes,
formats: parseFormats(p.formats),
};
}

export function parseAdminConfig(raw: string | null): AdminConfig {
if (!raw) return { ...DEFAULT_ADMIN_CONFIG };
try {
let p = JSON.parse(raw) as Partial<AdminConfig>;
let disabledResources: Record<string, string[]> = {};
if (p.disabledResources && typeof p.disabledResources === "object") {
for (let [vendorId, patterns] of Object.entries(p.disabledResources)) {
let list = strings(patterns);
if (list.length > 0) disabledResources[vendorId] = list;
}
}
let ambientGatekeeperModes: Record<string, AmbientGatekeeperMode> = {};
if (p.ambientGatekeeperModes && typeof p.ambientGatekeeperModes === "object") {
for (let [vendorId, mode] of Object.entries(p.ambientGatekeeperModes)) {
if (isAmbientGatekeeperMode(mode)) ambientGatekeeperModes[vendorId.toLowerCase()] = mode;
}
}
return {
signupsEnabled: typeof p.signupsEnabled === "boolean" ? p.signupsEnabled : true,
siteName: typeof p.siteName === "string" ? p.siteName : "",
siteLogoConfigured: typeof p.siteLogoConfigured === "boolean" ? p.siteLogoConfigured : false,
instanceInstructions: typeof p.instanceInstructions === "string" ? p.instanceInstructions : "",
announcement: typeof p.announcement === "string" ? p.announcement : "",
banner: {
text: typeof p.banner?.text === "string" ? p.banner.text : "",
color: isBannerColor(p.banner?.color) ? p.banner!.color : DEFAULT_BANNER_COLOR,
},
accentColor: typeof p.accentColor === "string" ? p.accentColor : "",
disabledResources,
disabledGatekeepers: strings(p.disabledGatekeepers).map(v => v.toLowerCase()),
ambientGatekeeperModes,
formats: parseFormats(p.formats),
};
return normalizeAdminConfig(JSON.parse(raw) as Partial<AdminConfig>);
} catch {
return { ...DEFAULT_ADMIN_CONFIG };
}
Expand Down
Loading
Loading