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
3 changes: 2 additions & 1 deletion packages/cli/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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}`);
}
});

Expand Down
17 changes: 12 additions & 5 deletions packages/convex/convex/lib/authorityEvents.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 = [
Expand All @@ -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
Expand All @@ -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 } : {}),
Expand All @@ -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(),
});
}
4 changes: 3 additions & 1 deletion packages/convex/convex/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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")),
Expand Down
24 changes: 23 additions & 1 deletion packages/convex/convex/teamReadKeys.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand All @@ -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);
}
Expand Down
29 changes: 21 additions & 8 deletions packages/convex/convex/teamReadKeys.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,14 @@ async function requireAdmin(ctx: any, teamId: Id<"teams">): Promise<Id<"users">>
return userId;
}

async function isAdmin(ctx: any, userId: Id<"users">, teamId: Id<"teams">): Promise<boolean> {
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<Doc<"team_read_keys">[]> {
return ctx.db.query("team_read_keys").withIndex("by_team", (q: any) => q.eq("team_id", teamId)).collect();
}
Expand All @@ -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<string, string | null>();
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<string, boolean>();
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) => ({
Expand All @@ -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,
Expand Down Expand Up @@ -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") },
Expand All @@ -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 } },
});
Expand Down
11 changes: 9 additions & 2 deletions packages/web/components/settings/TeamReadKeys.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -236,7 +243,7 @@ function KeyLine({ teamId, row, now }: { teamId: Id<"teams">; row: KeyRow; now:
<div className="overflow-hidden text-xs text-sol-text-dim">
<div className="-ml-3 flex flex-wrap">
{details.map((d, i) => (
<span key={i} className={`relative whitespace-nowrap pl-3 before:absolute before:left-0 before:w-3 before:text-center before:content-['·'] ${i === 0 ? "font-mono" : ""}`}>{d}</span>
<span key={i} className={`relative whitespace-nowrap pl-3 before:absolute before:left-0 before:w-3 before:text-center before:content-['·'] ${i === 0 ? "font-mono" : ""} ${d === ORPHANED ? "text-sol-orange before:text-sol-text-dim" : ""}`}>{d}</span>
))}
</div>
</div>
Expand Down
Loading