Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

fix(directory): resolve people on deployments without the Slack surface

Josh France3ed9cafaaa8b
diff --git a/src/api/app-messaging.ts b/src/api/app-messaging.ts
index 91b95de7c..f63f99b8d 100644
--- a/src/api/app-messaging.ts
+++ b/src/api/app-messaging.ts
@@ -15,7 +15,7 @@ import {
type ReachResolution,
} from "../reach/reach.ts";
import { isVisible } from "../directory/visibility.ts";
-import type { DirectoryMember } from "../directory/directory-store.ts";
+import { pickMatch, type DirectoryMember } from "../directory/directory-store.ts";
import { externalMemberActive } from "../identity/external-members.ts";
import { answerWebContextRequest } from "./web-context.ts";
import { validateUserSchedule } from "../cron/schedule.ts";
@@ -91,19 +91,32 @@ export function createMessagingMethods(
const contextRequests = deps.contextRequests ?? createMemoryMap<SurfaceContextRequest>();
const contextRequestListeners = new Set<(request: SurfaceContextRequest) => void>();
const contextRequestTokens = new Map<string, string>();
- const emailMembers = async (): Promise<DirectoryMember[]> => {
- const externals = (await deps.identity.listExternalMembers()).filter((member) => externalMemberActive(member));
- return [
+ // Principals identity knows about that the Slack directory never sees: the email
+ // allow-list, invited external users, and anyone who has signed in. On a Slack-less
+ // deployment these are the only members there are.
+ const identityMembers = async (): Promise<DirectoryMember[]> => {
+ const [externals, participants] = await Promise.all([
+ deps.identity.listExternalMembers(),
+ deps.sessions?.listParticipants() ?? [],
+ ]);
+ const candidates: DirectoryMember[] = [
...(deps.emailAuthMembers ?? []),
- ...externals.map((member) => ({
- principalId: member.email,
- displayName: member.email,
- type: "internal" as const,
- })),
+ ...externals
+ .filter((member) => externalMemberActive(member))
+ .map((member) => ({ principalId: member.email, displayName: member.email, type: "internal" as const })),
+ ...participants
+ .filter((w) => deps.identity.classify(w.principalId).type === "internal")
+ .map((w) => ({ principalId: w.principalId, displayName: w.principalId, type: "internal" as const })),
];
+ const byKey = new Map<string, DirectoryMember>();
+ for (const member of candidates) {
+ const key = personKey(member.principalId);
+ if (key && !byKey.has(key)) byKey.set(key, member);
+ }
+ return [...byKey.values()];
};
const mergedDirectoryMembers = async () => {
- const [stored, viaEmail] = await Promise.all([deps.directory.list(), emailMembers()]);
+ const [stored, viaEmail] = await Promise.all([deps.directory.list(), identityMembers()]);
const seen = new Set(stored.map((member) => personKey(member.principalId)));
return [...stored, ...viaEmail.filter((member) => !seen.has(personKey(member.principalId)))];
};
@@ -415,11 +428,15 @@ export function createMessagingMethods(
async resolveRecipient(query) {
const stored = await deps.directory.resolve(query);
if (stored.kind !== "none") return stored;
- const key = personKey(query);
- const member = (await emailMembers()).find(
- (candidate) => personKey(candidate.principalId) === key || personKey(candidate.displayName) === key,
+ const match = pickMatch(
+ await identityMembers(),
+ query,
+ (member) => member.principalId,
+ (member) => member.displayName,
);
- return member ? { kind: "one", member } : { kind: "none" };
+ if (match.kind === "one") return { kind: "one", member: match.item };
+ if (match.kind === "ambiguous") return { kind: "ambiguous", candidates: match.items };
+ return { kind: "none" };
},
resolveChannel(query) {
return deps.directory.resolveChannel(query);
@@ -433,7 +450,7 @@ export function createMessagingMethods(
async directoryMember(principalId) {
return (
(await deps.directory.get(principalId)) ??
- (await emailMembers()).find((member) => personKey(member.principalId) === personKey(principalId)) ??
+ (await identityMembers()).find((member) => personKey(member.principalId) === personKey(principalId)) ??
null
);
},
diff --git a/src/api/routes/directory.ts b/src/api/routes/directory.ts
index aadab8bfd..5a113731e 100644
--- a/src/api/routes/directory.ts
+++ b/src/api/routes/directory.ts
@@ -1,4 +1,4 @@
-import type { PrincipalType } from "../../types.ts";
+import { isPrincipalType, PRINCIPAL_TYPES, type PrincipalType } from "../../types.ts";
import type { DirectoryMember } from "../../directory/directory-store.ts";
import { sendJson } from "../http.ts";
import { audit, isObj, orgScope } from "./shared.ts";
@@ -48,6 +48,12 @@ async function pushDirectory(ctx: ApiCtx): Promise<void> {
message: "members[], channels[], and/or groupMembers[] required",
});
}
+ if (Array.isArray(b.members) && b.members.some((m) => isObj(m) && !isPrincipalType(m.type))) {
+ return sendJson(res, 400, {
+ error: "bad_request",
+ message: `member type must be one of: ${PRINCIPAL_TYPES.join(", ")}`,
+ });
+ }
if (typeof b.workspaceUrl === "string" && /^https:\/\/[^\s/]+$/.test(b.workspaceUrl.replace(/\/+$/, ""))) {
await app.setDirectoryWorkspaceUrl(b.workspaceUrl.replace(/\/+$/, ""));
}
@@ -56,10 +62,7 @@ async function pushDirectory(ctx: ApiCtx): Promise<void> {
const members = b.members
.filter(
(m): m is { principalId: string; displayName: string; type: PrincipalType; slackId?: string } =>
- isObj(m) &&
- typeof m.principalId === "string" &&
- typeof m.displayName === "string" &&
- typeof m.type === "string",
+ isObj(m) && typeof m.principalId === "string" && typeof m.displayName === "string" && isPrincipalType(m.type),
)
.map((m) => ({
principalId: m.principalId,
diff --git a/src/directory/directory-store.ts b/src/directory/directory-store.ts
index 8fe4b9bf2..83443ea57 100644
--- a/src/directory/directory-store.ts
+++ b/src/directory/directory-store.ts
@@ -79,7 +79,7 @@ export interface DirectoryStore {
export const MAX_CANDIDATES = 10;
export const normDirectoryQuery = (s: string): string => s.trim().toLowerCase().replace(/^[@#]/, "");
-function pickMatch<T>(
+export function pickMatch<T>(
items: T[],
query: string,
id: (t: T) => string,
diff --git a/src/types.ts b/src/types.ts
index 971553fce..5fe0d0329 100644
--- a/src/types.ts
+++ b/src/types.ts
@@ -2,6 +2,12 @@ import type { ResolvedSecurityPolicy } from "./security/security-posture.ts";
export type PrincipalType = "internal" | "guest";
+export const PRINCIPAL_TYPES = ["internal", "guest"] as const satisfies readonly PrincipalType[];
+
+export function isPrincipalType(value: unknown): value is PrincipalType {
+ return typeof value === "string" && (PRINCIPAL_TYPES as readonly string[]).includes(value);
+}
+
export interface Principal {
id: string;
type: PrincipalType;
diff --git a/test/directory-resolve.test.ts b/test/directory-resolve.test.ts
index 371d1683f..6b5087815 100644
--- a/test/directory-resolve.test.ts
+++ b/test/directory-resolve.test.ts
@@ -6,6 +6,7 @@ import { mkdtempSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { buildApp, type BuiltApp } from "../src/wiring.ts";
+import { signRequest } from "../src/auth/source-auth.ts";
import { createServer } from "../src/api/server.ts";
import { mintCapabilityToken, CAPABILITY_TTL_MS } from "../src/auth/capability-token.ts";
import { testConfig } from "./support/test-config.ts";
@@ -105,3 +106,81 @@ describe("GET /v1/directory/resolve (agent looks up a teammate's mention id)", a
assert.equal(res.status, 401);
});
});
+
+describe("a deployment without the Slack surface (the directory store is never populated)", async () => {
+ let server: Server;
+ let base: string;
+ let built: BuiltApp;
+
+ const cap = await mintCapabilityToken(
+ { actorId: "[email protected]", scopeId: "personal:[email protected]", exp: Date.now() + CAPABILITY_TTL_MS },
+ SECRET,
+ );
+
+ before(async () => {
+ built = buildApp(
+ testConfig({
+ dataDir: mkdtempSync(join(tmpdir(), "dir-web-only-")),
+ signingSecret: SECRET,
+ emailAuthPrincipals: ["[email protected]"],
+ }),
+ );
+ server = createServer(built.app, { signingSecret: SECRET, scheduler: built.scheduler });
+ await new Promise<void>((resolve) => server.listen(0, resolve));
+ base = `http://localhost:${(server.address() as AddressInfo).port}`;
+ const session = await built.sessions.getOrCreateByThread("web:1", "dm", "personal:[email protected]");
+ await built.sessions.addParticipant(session.id, "[email protected]");
+ });
+
+ after(async () => {
+ await new Promise<void>((resolve) => server.close(() => resolve()));
+ });
+
+ const get = (path: string) => fetch(`${base}${path}`, { headers: { "x-agent-capability": cap } });
+ const matchesOf = async (query: string): Promise<Array<{ principalId: string; type: string }>> => {
+ const res = await get(`/v1/directory/resolve?q=${encodeURIComponent(query)}`);
+ assert.equal(res.status, 200);
+ return ((await res.json()) as { matches: Array<{ principalId: string; type: string }> }).matches;
+ };
+
+ it("finds a principal who has signed in but was never pushed into the directory", async () => {
+ const matches = await matchesOf("[email protected]");
+ assert.deepEqual(
+ matches.map((m) => m.principalId),
+ );
+ assert.equal(matches[0]!.type, "internal", "the web UI only offers internal principals as project members");
+ });
+
+ it("matches on a prefix, the way the stored directory does — the search box types a name, not an address", async () => {
+ assert.deepEqual(
+ (await matchesOf("dan")).map((m) => m.principalId),
+ );
+ assert.deepEqual(
+ (await matchesOf("rex")).map((m) => m.principalId),
+ );
+ });
+
+ it("still returns nothing for someone who has never signed in", async () => {
+ assert.deepEqual(await matchesOf("[email protected]"), []);
+ });
+
+ it("rejects a member pushed with a type outside PrincipalType instead of dropping it silently", async () => {
+ const body = JSON.stringify({ members: [{ principalId: "[email protected]", displayName: "Sam", type: "user" }] });
+ const ts = Math.floor(Date.now() / 1000);
+ const res = await fetch(`${base}/v1/directory`, {
+ method: "POST",
+ headers: {
+ "content-type": "application/json",
+ "x-timestamp": String(ts),
+ "x-signature": signRequest(SECRET, ts, `POST\n/v1/directory\n${body}`),
+ },
+ body,
+ });
+ assert.equal(res.status, 400);
+ assert.match(((await res.json()) as { message: string }).message, /internal, guest/);
+ assert.deepEqual(await matchesOf("[email protected]"), [], "a rejected push must not land");
+ });
+});