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
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
-- migrate:up
--
-- Conversation scope on corpus documents.
--
-- An emailed attachment belongs to a conversation, and conversations are scoped
-- more narrowly than anything else the corpus holds: admins see all, an
-- unassigned one is admin-triage only, otherwise the caller must be the
-- assignee or in the assigned team. That rule is also LIVE — a reassignment
-- changes who may read the mail, and therefore who may read its attachment.
--
-- So the column does not carry the answer, only the question. It records which
-- conversation the row belongs to; the Convex-truth re-check
-- (`filterRetrievableRagFileIds`) then applies `conversationAssignmentAllows`
-- against the conversation's CURRENT assignment. Stamping a team here instead
-- would be wrong the moment somebody reassigned, and every missed rewrite would
-- leave a file hidden from its new owner or visible to the person who handed it
-- off.
--
-- Its other job is to keep these rows OUT of the hub clause. A row with every
-- scope column NULL reads as org-hub, so without this an indexed attachment
-- would be org-wide by default — the outcome being avoided.
--
-- Nullable TEXT with no default: NULL means "not a conversation row", which is
-- every pre-existing row and every document. Metadata-only, idempotent, safe on
-- any vintage.
--
-- Partial index in the same style as `idx_pk_docs_org_project`: conversation
-- rows are the minority, so the index stays small.

ALTER TABLE private_knowledge.documents
ADD COLUMN IF NOT EXISTS conversation_id TEXT;

CREATE INDEX IF NOT EXISTS idx_pk_docs_org_conversation
ON private_knowledge.documents (org_slug, conversation_id)
WHERE conversation_id IS NOT NULL;

-- migrate:down
-- Deliberately empty, like the other private_knowledge migrations: on a
-- database that received this column it immediately holds tenancy scope, and
-- dropping it would silently widen every conversation-scoped attachment back to
-- org-wide hub visibility. Remove it with an explicit, reviewed migration.
28 changes: 28 additions & 0 deletions services/platform/convex/documents/access.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,34 @@ describe('resolveKnowledgeAccessForUser', () => {
]);
});

it('carries the identity, so an emailed attachment can be decided at all', async () => {
// The other fields are SETS — a conversation-scoped row cannot be expressed
// as one, because its reader is whoever the mail is currently assigned to.
// So the scope carries who asked, and the Convex-truth re-check asks the
// conversation. Without the identity that re-check denies every such row,
// which is the fail-closed direction but also means no inbox attachment is
// ever found.
memberWithRole('member');
mockGetUserTeamIds.mockResolvedValue(['team-a']);
const access = await resolveKnowledgeAccessForUser(
createMockCtx(projects),
orgArgs,
);
expect(access.userId).toBe('user1');
expect(access.includeConversationScoped).toBe(true);
});

it('grants a denied caller no identity and no conversation rows', async () => {
memberWithRole('disabled');
mockGetUserTeamIds.mockResolvedValue(['team-a']);
const access = await resolveKnowledgeAccessForUser(
createMockCtx(projects),
orgArgs,
);
expect(access.userId).toBeUndefined();
expect(access.includeConversationScoped).toBeUndefined();
});

it('names which readable projects are archived, without dropping them', async () => {
memberWithRole('member');
mockGetUserTeamIds.mockResolvedValue(['team-a']);
Expand Down
40 changes: 38 additions & 2 deletions services/platform/convex/documents/access.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
* or `canReadDocument` (async, resolves project access for single-doc reads).
*/

import { ConvexError } from 'convex/values';
import { ConvexError, v } from 'convex/values';

import type { Doc } from '../_generated/dataModel';
import type { MutationCtx, QueryCtx } from '../_generated/server';
Expand Down Expand Up @@ -231,6 +231,8 @@ export interface ResolvedKnowledgeAccess {
teamIds: string[];
projectIds: string[];
includeHub: boolean;
/** Whether conversation-scoped rows are admitted for the re-check to decide. */
includeConversationScoped?: boolean;
/**
* Which of `projectIds` are archived. NOT a narrowing of what is
* retrievable: an archived project's material stays searchable and citable.
Expand All @@ -240,8 +242,33 @@ export interface ResolvedKnowledgeAccess {
* under-labels rather than over-filters.
*/
archivedProjectIds?: string[];
/** The user the scope was resolved for. Needed to decide a
* conversation-scoped corpus row by its live assignment. */
userId?: string;
}

/**
* The wire shape of {@link ResolvedKnowledgeAccess}, declared ONCE.
*
* It was declared three times — the resolver's returns, the re-check's args,
* and the sandbox bridge's returns — and adding a field to the scope meant
* finding all three. Missing one does not fail politely: a closed returns
* validator THROWS on the unexpected field, and a throwing query reads to the
* caller as "no results", so a widened scope would present as knowledge search
* having gone quiet.
*
* `threadIds` is not here: it belongs to the chat lane's request, not to what
* the resolver derives, and the re-check adds it to its own args.
*/
export const knowledgeAccessScopeValidator = v.object({
teamIds: v.array(v.string()),
projectIds: v.array(v.string()),
includeHub: v.boolean(),
archivedProjectIds: v.optional(v.array(v.string())),
includeConversationScoped: v.optional(v.boolean()),
userId: v.optional(v.string()),
});

/** Fail-closed scope: no hub, no teams, no projects — a search sees nothing. */
export const NO_KNOWLEDGE_ACCESS: ResolvedKnowledgeAccess = {
teamIds: [],
Expand Down Expand Up @@ -299,5 +326,14 @@ export async function resolveKnowledgeAccessForUser(
}
}

return { teamIds, projectIds, includeHub: true, archivedProjectIds };
return {
teamIds,
projectIds,
includeHub: true,
archivedProjectIds,
userId: args.userId,
// Emailed attachments are considered; the Convex-truth re-check decides
// each one by the conversation's current assignment.
includeConversationScoped: true,
};
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,231 @@
// The gate that decides an emailed attachment.
//
// Its own file because it needs the identity modules mocked, and the sibling
// suite deliberately runs against a bare fake ctx. What is mocked here is only
// the Better Auth I/O — `resolveAgentReadAccess`, `authorizeRls` and
// `conversationAssignmentAllows` all run for real, so the rule under test is
// the shipped rule and not a restatement of it.

import { beforeEach, describe, expect, it, vi } from 'vitest';

const getUserTeamIds = vi.fn();
const getUserOrganizations = vi.fn();

vi.mock('../lib/get_user_teams', () => ({
getUserTeamIds: (...args: unknown[]) => getUserTeamIds(...args),
}));
vi.mock('../lib/rls/organization/get_user_organizations', () => ({
getUserOrganizations: (...args: unknown[]) => getUserOrganizations(...args),
}));

const { filterRetrievableRagFileIds } =
await import('./filter_retrievable_rag_file_ids');

const ORG = 'org_mail';
const OTHER_ORG = 'org_other';
const USER = 'user_asking';
const TEAM_MINE = 'team_mine';
const TEAM_THEIRS = 'team_theirs';
const ATTACHMENT = 'blob_cv';
const CONVERSATION = 'conv_inbound';

/** Access that admits conversation rows, as the resolver now always does. */
const ACCESS = {
teamIds: [],
projectIds: [],
includeHub: true,
includeConversationScoped: true,
userId: USER,
} as const;

/**
* A ctx holding one emailed attachment bound to one conversation.
*
* `rows` overrides let a case bend one fact — the conversation's assignment,
* its org, the metadata's status — without restating the rest.
*/
function createCtx(
overrides: {
metadata?: Record<string, unknown>;
conversation?: Record<string, unknown> | null;
} = {},
) {
const metadata = {
organizationId: ORG,
storageId: ATTACHMENT,
conversationId: CONVERSATION,
ragStatus: 'completed',
...overrides.metadata,
};
const conversation =
overrides.conversation === null
? null
: { _id: CONVERSATION, organizationId: ORG, ...overrides.conversation };
return {
db: {
query: () => ({
withIndex: (
_name: string,
bind: (q: { eq: (f: string, v: unknown) => unknown }) => unknown,
) => {
let storageId = '';
const q = {
eq(field: string, value: unknown) {
if (field === 'storageId') storageId = String(value);
return q;
},
};
bind(q);
return {
first: async () => (storageId === ATTACHMENT ? metadata : null),
};
},
}),
get: async (id: string) => (id === CONVERSATION ? conversation : null),
},
} as never;
}

async function retrievableFor(
ctx: unknown,
args: Record<string, unknown> = {},
): Promise<string[]> {
return filterRetrievableRagFileIds(ctx as never, {
organizationId: ORG,
fileIds: [ATTACHMENT as never],
access: ACCESS as never,
userId: USER,
...args,
});
}

describe('filterRetrievableRagFileIds — emailed attachments', () => {
beforeEach(() => {
vi.clearAllMocks();
getUserOrganizations.mockResolvedValue([
{ organizationId: ORG, role: 'member' },
]);
getUserTeamIds.mockResolvedValue([TEAM_MINE]);
});

it('serves the individual assignee', async () => {
expect(
await retrievableFor(
createCtx({ conversation: { assigneeUserId: USER } }),
),
).toEqual([ATTACHMENT]);
});

it('serves a member of the assigned team', async () => {
expect(
await retrievableFor(
createCtx({ conversation: { assigneeTeamId: TEAM_MINE } }),
),
).toEqual([ATTACHMENT]);
});

it('denies another team’s mail, and unassigned mail, to a plain member', async () => {
expect(
await retrievableFor(
createCtx({ conversation: { assigneeTeamId: TEAM_THEIRS } }),
),
).toEqual([]);
// Neither stamp is admin-triage state, not org-readable.
expect(await retrievableFor(createCtx({ conversation: {} }))).toEqual([]);
});

it('serves an admin anything, including unassigned mail', async () => {
getUserOrganizations.mockResolvedValue([
{ organizationId: ORG, role: 'admin' },
]);
expect(await retrievableFor(createCtx({ conversation: {} }))).toEqual([
ATTACHMENT,
]);
expect(
await retrievableFor(
createCtx({ conversation: { assigneeTeamId: TEAM_THEIRS } }),
),
).toEqual([ATTACHMENT]);
});

it('denies a caller who did not say who they are', async () => {
const ctx = createCtx({ conversation: { assigneeUserId: USER } });
expect(await retrievableFor(ctx, { userId: undefined })).toEqual([]);
// …and does not spend a membership lookup finding that out.
expect(getUserOrganizations).not.toHaveBeenCalled();
});

it('denies when the scope excludes conversation rows', async () => {
expect(
await retrievableFor(
createCtx({ conversation: { assigneeUserId: USER } }),
{
access: { ...ACCESS, includeConversationScoped: false },
},
),
).toEqual([]);
});

it('denies a non-member and a role that cannot read conversations', async () => {
const ctx = createCtx({ conversation: { assigneeUserId: USER } });
getUserOrganizations.mockResolvedValue([]);
expect(await retrievableFor(ctx)).toEqual([]);

getUserOrganizations.mockResolvedValue([
{ organizationId: ORG, role: 'disabled' },
]);
expect(await retrievableFor(ctx)).toEqual([]);
});

it('denies a conversation belonging to another organization', async () => {
expect(
await retrievableFor(
createCtx({
conversation: { assigneeUserId: USER, organizationId: OTHER_ORG },
}),
),
).toEqual([]);
// A dangling reference is a miss, not a crash.
expect(await retrievableFor(createCtx({ conversation: null }))).toEqual([]);
});

it('never returns an emailed attachment to a folder-scoped search', async () => {
expect(
await retrievableFor(
createCtx({ conversation: { assigneeUserId: USER } }),
{ folder: 'Contracts' },
),
).toEqual([]);
});

it('still requires the attachment itself to be indexed and untrashed', async () => {
expect(
await retrievableFor(
createCtx({
metadata: { ragStatus: 'running' },
conversation: { assigneeUserId: USER },
}),
),
).toEqual([]);
expect(
await retrievableFor(
createCtx({
metadata: { lifecycleStatus: 'trashed' },
conversation: { assigneeUserId: USER },
}),
),
).toEqual([]);
});

it('resolves teams once per call, and not at all when the assignee decides it', async () => {
await retrievableFor(
createCtx({ conversation: { assigneeUserId: USER } }),
{ fileIds: [ATTACHMENT, ATTACHMENT] as never },
);
// The individual-assignee branch settles it, so the Better Auth team
// round-trip is never paid — the laziness `conversation_assignment.ts`
// documents, preserved through this reader.
expect(getUserTeamIds).toHaveBeenCalledTimes(1);
expect(getUserOrganizations).toHaveBeenCalledTimes(1);
});
});
Loading
Loading