diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts index 5afb800c19..1fc9255322 100644 --- a/packages/cli/src/index.ts +++ b/packages/cli/src/index.ts @@ -10502,7 +10502,8 @@ program .filter(Boolean).join(" "); for (const r of rows) { const change = r.detail?.after ? ` ${c.dim}${JSON.stringify(r.detail.after)}${c.reset}` : ""; - console.log(`${c.dim}${formatRelativeTime(r.created_at)}${c.reset} ${c.cyan}${r.kind}${c.reset} by ${String(r.actor_user_id).slice(0, 8)} ${subject(r)}${change}`); + const actor = r.actor_key_id ? `key ${String(r.actor_key_id).slice(0, 8)}` : String(r.actor_user_id).slice(0, 8); + console.log(`${c.dim}${formatRelativeTime(r.created_at)}${c.reset} ${c.cyan}${r.kind}${c.reset} by ${actor} ${subject(r)}${change}`); } }); diff --git a/packages/convex/convex/lib/authorityEvents.ts b/packages/convex/convex/lib/authorityEvents.ts index e58c2d8d8f..648e41ddb0 100644 --- a/packages/convex/convex/lib/authorityEvents.ts +++ b/packages/convex/convex/lib/authorityEvents.ts @@ -9,7 +9,7 @@ // A leaf like accessKeys.ts: conversationVisibility.ts (patchConversationVisibility) imports // it at load, so nothing here may reach a module that defines functions. import { Id } from "../_generated/dataModel"; -import { computeWorkspaceKey } from "./accessKeys"; +import { computeWorkspaceKey, workspaceKey } from "./accessKeys"; import { sha256Hex } from "./hash"; export const AUTHORITY_EVENT_KINDS = [ @@ -35,9 +35,14 @@ export const AUTHORITY_EVENT_KINDS = [ ] as const; export type AuthorityEventKind = (typeof AUTHORITY_EVENT_KINDS)[number]; -export type AuthorityEventInput = { +/** Who acted: a person, or a team read key using itself. A key belongs to its + * team, not to the admin who minted it, so its events are the team's. */ +type AuthorityActor = + | { actor_user_id: Id<"users">; actor_key_id?: never } + | { actor_key_id: Id<"team_read_keys">; actor_user_id?: never; team_id: Id<"teams"> }; + +export type AuthorityEventInput = AuthorityActor & { kind: AuthorityEventKind; - actor_user_id: Id<"users">; actor_conversation_id?: Id<"conversations">; /** The conversation the event is about; its POST-change row decides the * access key (a team-visible session's events are the team's, a private @@ -63,7 +68,7 @@ export async function recordAuthorityEvent(ctx: { db: any }, ev: AuthorityEventI const team_id = ev.team_id ?? conv?.team_id; return ctx.db.insert("authority_events", { kind: ev.kind, - actor_user_id: ev.actor_user_id, + ...(ev.actor_user_id === undefined ? { actor_key_id: ev.actor_key_id } : { actor_user_id: ev.actor_user_id }), ...(ev.actor_conversation_id ? { actor_conversation_id: ev.actor_conversation_id } : {}), ...(conv ? { conversation_id: conv._id } : {}), ...(team_id ? { team_id } : {}), @@ -72,7 +77,9 @@ export async function recordAuthorityEvent(ctx: { db: any }, ev: AuthorityEventI ...(ev.share_table ? { share_table: ev.share_table } : {}), ...(ev.share_token ? { share_token_hash: await sha256Hex(ev.share_token) } : {}), detail: ev.detail ?? {}, - workspace: computeWorkspaceKey({ user_id: ev.actor_user_id, team_id }, conv), + workspace: ev.actor_user_id === undefined + ? workspaceKey({ type: "team", teamId: ev.team_id }) + : computeWorkspaceKey({ user_id: ev.actor_user_id, team_id }, conv), created_at: Date.now(), }); } diff --git a/packages/convex/convex/schema.ts b/packages/convex/convex/schema.ts index e7a46d0f10..8468be7b06 100644 --- a/packages/convex/convex/schema.ts +++ b/packages/convex/convex/schema.ts @@ -5745,7 +5745,9 @@ export default defineSchema({ v.literal("team_read_key_revoked"), v.literal("team_read_key_used"), ), - actor_user_id: v.id("users"), + // One of the two: the person who acted, or the team read key that was used. + actor_user_id: v.optional(v.id("users")), + actor_key_id: v.optional(v.id("team_read_keys")), actor_conversation_id: v.optional(v.id("conversations")), conversation_id: v.optional(v.id("conversations")), team_id: v.optional(v.id("teams")), diff --git a/packages/convex/convex/teamReadKeys.test.ts b/packages/convex/convex/teamReadKeys.test.ts index d7e33c6fa0..fe57fe76b1 100644 --- a/packages/convex/convex/teamReadKeys.test.ts +++ b/packages/convex/convex/teamReadKeys.test.ts @@ -250,6 +250,26 @@ describe("team read keys", () => { await expect(as(mo).mutation(api.teamReadKeys.revoke, { team_id: team, key_id: minted.key_id })).rejects.toThrow(); }); + test("the list flags a key whose minter was demoted or left the team", async () => { + const { ada, mo, vi, team, as } = await setup(); + const setRole = (by: Id<"users">, member: Id<"users">, role: "admin" | "member") => + as(by).mutation(api.teams.setMemberRole, { team_id: team, member_user_id: member, role }); + await setRole(ada, vi, "admin"); + await setRole(ada, mo, "admin"); + await mint(as(ada), team, "by ada"); + const byVi = await mint(as(vi), team, "by vi"); + const flags = async () => + Object.fromEntries((await as(mo).query(api.teamReadKeys.list, { team_id: team }))!.map((k) => [k.name, k.created_by_still_admin])); + expect(await flags()).toEqual({ "by ada": true, "by vi": true }); + await setRole(vi, ada, "member"); + expect(await flags()).toEqual({ "by ada": false, "by vi": true }); + await as(vi).mutation(api.teams.removeFromTeam, { team_id: team, user_id: vi }); + expect(await flags()).toEqual({ "by ada": false, "by vi": false }); + // An ended key's minter is not looked up. + await as(mo).mutation(api.teamReadKeys.revoke, { team_id: team, key_id: byVi.key_id }); + expect(await flags()).toEqual({ "by ada": false, "by vi": null }); + }); + test(`a team holds at most ${MAX_LIVE_TEAM_READ_KEYS} live keys; a revoked one frees a place`, async () => { const { ada, team, as } = await setup(); const first = await mint(as(ada), team, "key 0"); @@ -275,8 +295,10 @@ describe("team read keys", () => { "team_read_key_used", "team_read_key_revoked", ]); + // A person mints and revokes; the key itself is the actor of its use. + expect(events.map((e: any) => e.actor_user_id)).toEqual([ada, undefined, undefined, ada]); + expect(events.map((e: any) => e.actor_key_id)).toEqual([undefined, key_id, key_id, undefined]); for (const e of events) { - expect(e.actor_user_id).toBe(ada); expect(e.detail.after).toMatchObject({ key_id, name: "eng site" }); expect(JSON.stringify(e)).not.toContain(key); } diff --git a/packages/convex/convex/teamReadKeys.ts b/packages/convex/convex/teamReadKeys.ts index 5d0b94b041..3981fe3b12 100644 --- a/packages/convex/convex/teamReadKeys.ts +++ b/packages/convex/convex/teamReadKeys.ts @@ -54,6 +54,14 @@ async function requireAdmin(ctx: any, teamId: Id<"teams">): Promise> return userId; } +async function isAdmin(ctx: any, userId: Id<"users">, teamId: Id<"teams">): Promise { + const membership = await ctx.db + .query("team_memberships") + .withIndex("by_user_team", (q: any) => q.eq("user_id", userId).eq("team_id", teamId)) + .first(); + return membership?.role === "admin"; +} + function keysOf(ctx: any, teamId: Id<"teams">): Promise[]> { return ctx.db.query("team_read_keys").withIndex("by_team", (q: any) => q.eq("team_id", teamId)).collect(); } @@ -64,16 +72,19 @@ export const list = query({ handler: async (ctx, args) => { const userId = await getAuthUserId(ctx); if (!userId) return null; - const membership = await ctx.db - .query("team_memberships") - .withIndex("by_user_team", (q) => q.eq("user_id", userId).eq("team_id", args.team_id)) - .first(); - if (membership?.role !== "admin") return null; + if (!(await isAdmin(ctx, userId, args.team_id))) return null; const keys = await keysOf(ctx, args.team_id); const creators = new Map(); for (const id of new Set(keys.map((k) => String(k.created_by)))) { creators.set(id, (await ctx.db.get(id as Id<"users">))?.name ?? null); } + // A key outlives its minter's admin role, so the list says which live keys' + // minters are no longer team admins. The live-key cap bounds these reads. + const now = Date.now(); + const stillAdmin = new Map(); + for (const id of new Set(keys.filter((k) => isLive(k, now)).map((k) => k.created_by))) { + stillAdmin.set(String(id), await isAdmin(ctx, id, args.team_id)); + } return keys .sort((a, b) => b.created_at - a.created_at) .map((k) => ({ @@ -82,6 +93,8 @@ export const list = query({ prefix: k.prefix, created_at: k.created_at, created_by_name: creators.get(String(k.created_by)) ?? null, + /** Null for an ended key, whose minter is not looked up. */ + created_by_still_admin: stillAdmin.get(String(k.created_by)) ?? null, expires_at: k.expires_at, revoked_at: k.revoked_at ?? null, last_used_at: k.last_used_at ?? null, @@ -166,8 +179,8 @@ export const keyForHash = internalQuery({ /** * A key's use, recorded before the read it opens: last_used_at moves and a - * team_read_key_used event names the key, with the admin who minted it as the - * actor. Requests inside the same window record nothing. + * team_read_key_used event names the key as its actor. Requests inside the + * same window record nothing. */ export const recordUse = internalMutation({ args: { key_id: v.id("team_read_keys") }, @@ -178,7 +191,7 @@ export const recordUse = internalMutation({ await ctx.db.patch(key._id, { last_used_at: now }); await recordAuthorityEvent(ctx, { kind: "team_read_key_used", - actor_user_id: key.created_by, + actor_key_id: key._id, team_id: key.team_id, detail: { after: { key_id: key._id, name: key.name, prefix: key.prefix } }, }); diff --git a/packages/web/components/settings/TeamReadKeys.tsx b/packages/web/components/settings/TeamReadKeys.tsx index dabfc7f68f..3396174835 100644 --- a/packages/web/components/settings/TeamReadKeys.tsx +++ b/packages/web/components/settings/TeamReadKeys.tsx @@ -217,12 +217,19 @@ function MintedKey({ minted, onDone }: { minted: Minted; onDone: (fromKeyboard: ); } +const ORPHANED = "no longer a team admin"; + function KeyLine({ teamId, row, now }: { teamId: Id<"teams">; row: KeyRow; now: number }) { const ended = row.revoked_at ? "Revoked" : row.expires_at <= now ? "Expired" : null; const daysLeft = Math.ceil((row.expires_at - now) / DAY_MS); + // A live key whose minter left the team or lost the admin role: the remaining + // admins decide whether to revoke it. A row cached before the server sent the + // field has no value, which is not a flag. + const orphaned = !ended && row.created_by_still_admin === false; const details = [ `${row.prefix}…`, - row.created_by_name && `by ${row.created_by_name}`, + orphaned ? `by ${row.created_by_name ?? "someone"}` : row.created_by_name && `by ${row.created_by_name}`, + orphaned && ORPHANED, row.last_used_at ? `Used ${relativeTime(row.last_used_at)}` : ended ? "Never used" : "Not used yet", ended ? null : daysLeft === 1 ? "1 day left" : `${daysLeft} days left`, ].filter((d): d is string => !!d); @@ -236,7 +243,7 @@ function KeyLine({ teamId, row, now }: { teamId: Id<"teams">; row: KeyRow; now:
{details.map((d, i) => ( - {d} + {d} ))}