diff --git a/app/editor/components/DocumentMenu.tsx b/app/editor/components/DocumentMenu.tsx index 834fe67541..f20ab193eb 100644 --- a/app/editor/components/DocumentMenu.tsx +++ b/app/editor/components/DocumentMenu.tsx @@ -2,7 +2,6 @@ import { observer } from "mobx-react"; import { useCallback, useEffect, useState } from "react"; import { useTranslation } from "react-i18next"; import { useLocation } from "react-router-dom"; -import { StatusFilter } from "@shared/types"; import parseDocumentSlug from "@shared/utils/parseDocumentSlug"; import useStores from "~/hooks/useStores"; import type { MentionMenuItem } from "~/editor/menus/mention"; @@ -53,7 +52,10 @@ function DocumentMenu({ search = "", isActive, ...rest }: Props) { ? documents.searchTitles({ query, limit: MaxResults, - statusFilter: [StatusFilter.Published], + filters: [ + { field: "archivedAt", operator: "isNull" }, + { field: "publishedAt", operator: "isNotNull" }, + ], }) : documents.fetchRecentlyViewed({ limit: MaxDefaultResults })); } catch { diff --git a/app/scenes/Search/Search.tsx b/app/scenes/Search/Search.tsx index cb6be0dd7c..1af4022dc4 100644 --- a/app/scenes/Search/Search.tsx +++ b/app/scenes/Search/Search.tsx @@ -8,6 +8,7 @@ import { Waypoint } from "react-waypoint"; import styled from "styled-components"; import breakpoint from "styled-components-breakpoint"; import { Pagination } from "@shared/constants"; +import type { Filter } from "@shared/helpers/FilterHelper"; import type { SortFilter as TSortFilter, DirectionFilter as TDirectionFilter, @@ -98,29 +99,84 @@ function Search() { sort: isSearchable, }; - const filters = React.useMemo( + const filters = React.useMemo(() => { + const children: Filter[] = []; + if (collectionId) { + children.push({ + field: "collectionId", + operator: "eq", + value: collectionId, + }); + } + if (userId) { + children.push({ field: "userId", operator: "eq", value: userId }); + } + if (documentId) { + children.push({ + field: "documentId", + operator: "eq", + value: documentId, + }); + } + if (dateFilter) { + const duration = ( + { + day: "-P1D", + week: "-P1W", + month: "-P1M", + year: "-P1Y", + } as const + )[dateFilter]; + if (duration) { + children.push({ field: "updatedAt", operator: "gte", value: duration }); + } + } + if (statusFilter.length > 0) { + const statusShape = (status: TStatusFilter): Filter => { + if (status === TStatusFilter.Archived) { + return { field: "archivedAt", operator: "isNotNull" }; + } + if (status === TStatusFilter.Published) { + return { + operator: "AND", + filters: [ + { field: "archivedAt", operator: "isNull" }, + { field: "publishedAt", operator: "isNotNull" }, + ], + }; + } + return { + operator: "AND", + filters: [ + { field: "archivedAt", operator: "isNull" }, + { field: "publishedAt", operator: "isNull" }, + ], + }; + }; + const statusGroup = + statusFilter.length === 1 + ? statusShape(statusFilter[0]) + : ({ + operator: "OR", + filters: statusFilter.map(statusShape), + } as Filter); + children.push(statusGroup); + } + if (children.length === 0) { + return undefined; + } + return children; + }, [collectionId, userId, documentId, dateFilter, statusFilter]); + + const requestParams = React.useMemo( () => ({ query, - statusFilter, - collectionId, - userId, - dateFilter, titleFilter, - documentId, sort, direction, + filters, }), - [ - query, - statusFilter, - collectionId, - userId, - dateFilter, - titleFilter, - documentId, - sort, - direction, - ] + [query, titleFilter, sort, direction, filters] ); const requestFn = React.useMemo(() => { @@ -141,13 +197,19 @@ function Search() { limit: params?.limit, }; return titleFilter - ? await documents.searchTitles({ ...filters, ...paginationParams }) - : await documents.search({ ...filters, ...paginationParams }); + ? await documents.searchTitles({ + ...requestParams, + ...paginationParams, + }) + : await documents.search({ + ...requestParams, + ...paginationParams, + }); }; } return () => Promise.resolve([] as SearchResult[]); - }, [query, titleFilter, filters, searches, documents, isSearchable]); + }, [query, titleFilter, requestParams, searches, documents, isSearchable]); const { data, next, end, error, loading } = usePaginatedRequest(requestFn, { limit: Pagination.defaultLimit, diff --git a/app/stores/DocumentsStore.ts b/app/stores/DocumentsStore.ts index d13699b82b..1a1779a06f 100644 --- a/app/stores/DocumentsStore.ts +++ b/app/stores/DocumentsStore.ts @@ -6,11 +6,12 @@ import { AttachmentPreset, SubscriptionType, type DateFilter, - type StatusFilter, } from "@shared/types"; +import type { Filter } from "@shared/helpers/FilterHelper"; import { subtractDate } from "@shared/utils/date"; import { bytesToHumanReadable } from "@shared/utils/files"; import naturalSort from "@shared/utils/naturalSort"; +import type { JSONObject } from "@shared/types"; import type RootStore from "~/stores/RootStore"; import Store from "~/stores/base/Store"; import Document from "~/models/Document"; @@ -33,13 +34,10 @@ export type SearchParams = { query?: string; offset?: number; limit?: number; - dateFilter?: DateFilter; - statusFilter?: StatusFilter[]; - collectionId?: string; - userId?: string; shareId?: string; sort?: SortFilter; direction?: DirectionFilter; + filters?: Filter[]; }; type ImportOptions = { @@ -426,7 +424,7 @@ export default class DocumentsStore extends Store { @action searchTitles = async (options?: SearchParams): Promise => { - const compactedOptions = omitBy(options, (o) => !o); + const compactedOptions = omitBy(options, (o) => !o) as JSONObject; const res = await client.post("/documents.search_titles", { ...compactedOptions, }); @@ -457,7 +455,7 @@ export default class DocumentsStore extends Store { @action search = async (options: SearchParams): Promise => { - const compactedOptions = omitBy(options, (o) => !o); + const compactedOptions = omitBy(options, (o) => !o) as JSONObject; const res = await client.post("/documents.search", { ...compactedOptions, }); diff --git a/plugins/search-postgres/server/PostgresSearchProvider.test.ts b/plugins/search-postgres/server/PostgresSearchProvider.test.ts index e500617a9e..5d05f0edcc 100644 --- a/plugins/search-postgres/server/PostgresSearchProvider.test.ts +++ b/plugins/search-postgres/server/PostgresSearchProvider.test.ts @@ -1,9 +1,4 @@ -import { - DirectionFilter, - DocumentPermission, - SortFilter, - StatusFilter, -} from "@shared/types"; +import { DirectionFilter, DocumentPermission, SortFilter } from "@shared/types"; import { buildDocument, buildDraftDocument, @@ -98,7 +93,7 @@ describe("PostgresSearchProvider", () => { }); const { results } = await provider.searchForTeam(team, { query: "test", - collectionId: collection.id, + filter: { field: "collectionId", operator: "eq", value: collection.id }, }); expect(results.length).toBe(1); }); @@ -127,7 +122,7 @@ describe("PostgresSearchProvider", () => { const { results } = await provider.searchForTeam(team, { query: "test", - collectionId: collection.id, + filter: { field: "collectionId", operator: "eq", value: collection.id }, share, }); expect(results.length).toBe(1); @@ -295,7 +290,7 @@ describe("PostgresSearchProvider", () => { }), ]); const { results } = await provider.searchForUser(user, { - collectionId: collection.id, + filter: { field: "collectionId", operator: "eq", value: collection.id }, }); expect(results.length).toBe(2); expect(results.map((r) => r.document.id).sort()).toEqual( @@ -343,7 +338,11 @@ describe("PostgresSearchProvider", () => { }), ]); const { results } = await provider.searchForUser(user, { - collectionId: collection1.id, + filter: { + field: "collectionId", + operator: "eq", + value: collection1.id, + }, }); expect(results.length).toBe(2); expect(results.map((r) => r.document.id).sort()).toEqual( @@ -386,7 +385,13 @@ describe("PostgresSearchProvider", () => { }); const { results } = await provider.searchForUser(user, { query: "test", - statusFilter: [StatusFilter.Draft], + filter: { + operator: "AND", + filters: [ + { field: "archivedAt", operator: "isNull" }, + { field: "publishedAt", operator: "isNull" }, + ], + }, }); expect(results.length).toBe(1); }); @@ -402,7 +407,13 @@ describe("PostgresSearchProvider", () => { }); const { results } = await provider.searchForUser(user, { query: "test", - statusFilter: [StatusFilter.Draft], + filter: { + operator: "AND", + filters: [ + { field: "archivedAt", operator: "isNull" }, + { field: "publishedAt", operator: "isNull" }, + ], + }, }); expect(results.length).toBe(1); expect(results[0].document?.id).toBe(draft.id); @@ -426,7 +437,13 @@ describe("PostgresSearchProvider", () => { }); const { results } = await provider.searchForUser(user, { query: "test", - statusFilter: [StatusFilter.Draft], + filter: { + operator: "AND", + filters: [ + { field: "archivedAt", operator: "isNull" }, + { field: "publishedAt", operator: "isNull" }, + ], + }, }); expect(results.length).toBe(0); }); @@ -451,7 +468,19 @@ describe("PostgresSearchProvider", () => { const { results } = await provider.searchForUser(user, { query: "test", - statusFilter: [StatusFilter.Published, StatusFilter.Archived], + filter: { + operator: "OR", + filters: [ + { + operator: "AND", + filters: [ + { field: "archivedAt", operator: "isNull" }, + { field: "publishedAt", operator: "isNotNull" }, + ], + }, + { field: "archivedAt", operator: "isNotNull" }, + ], + }, }); expect(results.length).toBe(0); }); @@ -482,7 +511,13 @@ describe("PostgresSearchProvider", () => { }); const { results } = await provider.searchForUser(user, { query: "test", - statusFilter: [StatusFilter.Published], + filter: { + operator: "AND", + filters: [ + { field: "archivedAt", operator: "isNull" }, + { field: "publishedAt", operator: "isNotNull" }, + ], + }, }); expect(results.length).toBe(1); }); @@ -519,7 +554,7 @@ describe("PostgresSearchProvider", () => { }); const { results } = await provider.searchForUser(user, { query: "test", - statusFilter: [StatusFilter.Archived], + filter: { field: "archivedAt", operator: "isNotNull" }, }); expect(results.length).toBe(1); }); @@ -547,7 +582,19 @@ describe("PostgresSearchProvider", () => { }); const { results } = await provider.searchForUser(user, { query: "test", - statusFilter: [StatusFilter.Archived, StatusFilter.Published], + filter: { + operator: "OR", + filters: [ + { field: "archivedAt", operator: "isNotNull" }, + { + operator: "AND", + filters: [ + { field: "archivedAt", operator: "isNull" }, + { field: "publishedAt", operator: "isNotNull" }, + ], + }, + ], + }, }); expect(results.length).toBe(2); }); @@ -575,7 +622,25 @@ describe("PostgresSearchProvider", () => { }); const { results } = await provider.searchForUser(user, { query: "draft", - statusFilter: [StatusFilter.Published, StatusFilter.Draft], + filter: { + operator: "OR", + filters: [ + { + operator: "AND", + filters: [ + { field: "archivedAt", operator: "isNull" }, + { field: "publishedAt", operator: "isNotNull" }, + ], + }, + { + operator: "AND", + filters: [ + { field: "archivedAt", operator: "isNull" }, + { field: "publishedAt", operator: "isNull" }, + ], + }, + ], + }, }); expect(results.length).toBe(2); }); @@ -603,7 +668,19 @@ describe("PostgresSearchProvider", () => { }); const { results } = await provider.searchForUser(user, { query: "draft", - statusFilter: [StatusFilter.Draft, StatusFilter.Archived], + filter: { + operator: "OR", + filters: [ + { + operator: "AND", + filters: [ + { field: "archivedAt", operator: "isNull" }, + { field: "publishedAt", operator: "isNull" }, + ], + }, + { field: "archivedAt", operator: "isNotNull" }, + ], + }, }); expect(results.length).toBe(2); }); @@ -817,7 +894,13 @@ describe("PostgresSearchProvider", () => { const { results } = await provider.searchForUser(user, { query: "group draft", - statusFilter: [StatusFilter.Draft], + filter: { + operator: "AND", + filters: [ + { field: "archivedAt", operator: "isNull" }, + { field: "publishedAt", operator: "isNull" }, + ], + }, }); expect(results.length).toBe(1); @@ -876,7 +959,7 @@ describe("PostgresSearchProvider", () => { }); const documents = await provider.searchTitlesForUser(user, { query: "test", - collectionId: collection.id, + filter: { field: "collectionId", operator: "eq", value: collection.id }, }); expect(documents.length).toBe(1); expect(documents[0]?.id).toBe(document.id); @@ -917,7 +1000,13 @@ describe("PostgresSearchProvider", () => { }); const documents = await provider.searchTitlesForUser(user, { query: "test", - statusFilter: [StatusFilter.Draft], + filter: { + operator: "AND", + filters: [ + { field: "archivedAt", operator: "isNull" }, + { field: "publishedAt", operator: "isNull" }, + ], + }, }); expect(documents.length).toBe(1); }); @@ -948,7 +1037,13 @@ describe("PostgresSearchProvider", () => { }); const documents = await provider.searchTitlesForUser(user, { query: "test", - statusFilter: [StatusFilter.Published], + filter: { + operator: "AND", + filters: [ + { field: "archivedAt", operator: "isNull" }, + { field: "publishedAt", operator: "isNotNull" }, + ], + }, }); expect(documents.length).toBe(1); }); @@ -985,7 +1080,7 @@ describe("PostgresSearchProvider", () => { }); const documents = await provider.searchTitlesForUser(user, { query: "test", - statusFilter: [StatusFilter.Archived], + filter: { field: "archivedAt", operator: "isNotNull" }, }); expect(documents.length).toBe(1); }); @@ -1013,7 +1108,19 @@ describe("PostgresSearchProvider", () => { }); const documents = await provider.searchTitlesForUser(user, { query: "test", - statusFilter: [StatusFilter.Archived, StatusFilter.Published], + filter: { + operator: "OR", + filters: [ + { field: "archivedAt", operator: "isNotNull" }, + { + operator: "AND", + filters: [ + { field: "archivedAt", operator: "isNull" }, + { field: "publishedAt", operator: "isNotNull" }, + ], + }, + ], + }, }); expect(documents.length).toBe(2); }); @@ -1041,7 +1148,25 @@ describe("PostgresSearchProvider", () => { }); const documents = await provider.searchTitlesForUser(user, { query: "draft", - statusFilter: [StatusFilter.Published, StatusFilter.Draft], + filter: { + operator: "OR", + filters: [ + { + operator: "AND", + filters: [ + { field: "archivedAt", operator: "isNull" }, + { field: "publishedAt", operator: "isNotNull" }, + ], + }, + { + operator: "AND", + filters: [ + { field: "archivedAt", operator: "isNull" }, + { field: "publishedAt", operator: "isNull" }, + ], + }, + ], + }, }); expect(documents.length).toBe(2); }); @@ -1069,7 +1194,19 @@ describe("PostgresSearchProvider", () => { }); const documents = await provider.searchTitlesForUser(user, { query: "draft", - statusFilter: [StatusFilter.Draft, StatusFilter.Archived], + filter: { + operator: "OR", + filters: [ + { + operator: "AND", + filters: [ + { field: "archivedAt", operator: "isNull" }, + { field: "publishedAt", operator: "isNull" }, + ], + }, + { field: "archivedAt", operator: "isNotNull" }, + ], + }, }); expect(documents.length).toBe(2); }); diff --git a/plugins/search-postgres/server/PostgresSearchProvider.ts b/plugins/search-postgres/server/PostgresSearchProvider.ts index afa6e3980f..754963cc7b 100644 --- a/plugins/search-postgres/server/PostgresSearchProvider.ts +++ b/plugins/search-postgres/server/PostgresSearchProvider.ts @@ -9,8 +9,9 @@ import type { WhereOptions, } from "sequelize"; import { Op, Sequelize } from "sequelize"; +import type { Filter } from "@shared/helpers/FilterHelper"; import type { SearchableModel } from "@shared/types"; -import { DirectionFilter, SortFilter, StatusFilter } from "@shared/types"; +import { DirectionFilter, SortFilter } from "@shared/types"; import { regexIndexOf, regexLastIndexOf } from "@shared/utils/string"; import { getUrls } from "@shared/utils/urls"; import { ValidationError } from "@server/errors"; @@ -20,7 +21,11 @@ import Document from "@server/models/Document"; import Team from "@server/models/Team"; import User from "@server/models/User"; import { DocumentHelper } from "@server/models/helpers/DocumentHelper"; -import { sequelize, sequelizeReadOnly } from "@server/storage/database"; +import { + buildSearchWhere, + collectEqValues, +} from "@server/models/helpers/Filters"; +import { sequelizeReadOnly } from "@server/storage/database"; import { QueryHelper } from "@server/storage/QueryHelper"; import type { SearchOptions, @@ -189,7 +194,9 @@ export default class PostgresSearchProvider extends BaseSearchProvider { const where = await PostgresSearchProvider.buildWhere(team, { ...options, - statusFilter: [...(options.statusFilter || []), StatusFilter.Published], + // Team-context search (used by shares) is always restricted to + // published, non-archived documents. + filter: PostgresSearchProvider.withPublishedConstraint(options.filter), }); if (options.share) { @@ -594,6 +601,26 @@ export default class PostgresSearchProvider extends BaseSearchProvider { return context.slice(startIndex, endIndex); } + /** + * AND a "published, non-archived" constraint into a filter expression. + * + * @param filter the filter to constrain, or undefined. + * @returns a filter that always requires Published status. + */ + private static withPublishedConstraint(filter: Filter | undefined): Filter { + const publishedShape: Filter = { + operator: "AND", + filters: [ + { field: "archivedAt", operator: "isNull" }, + { field: "publishedAt", operator: "isNotNull" }, + ], + }; + if (!filter) { + return publishedShape; + } + return { operator: "AND", filters: [filter, publishedShape] }; + } + private static async buildWhere(model: User | Team, options: SearchOptions) { const teamId = model instanceof Team ? model.id : model.teamId; const where: WhereOptions & { @@ -617,122 +644,64 @@ export default class PostgresSearchProvider extends BaseSearchProvider { ], }; - // Resolve the collections and individual documents accessible to the - // model upfront so the search query needs no membership joins. If - // collectionId is passed as an option it is assumed that the - // authorization has already been done in the router. - const [membershipDocumentIds, collectionIds] = await Promise.all([ - model instanceof User - ? Document.membershipDocumentIds(model.id) - : Promise.resolve([]), - options.collectionId - ? Promise.resolve([options.collectionId]) - : model.collectionIds(), - ]); + const filter = options.filter; + // A document is visible if any of: + // + // - direct or group membership on the document + // - the user is the creator AND the doc has no collection (unplaced + // drafts that no membership/collection check can reach) + // - the doc is published AND lives in a collection the user can access + // (the common case for non-draft visibility) + // - the user is the creator AND the doc lives in a collection they can + // access (covers own drafts in shared collections — collection access + // alone does not grant visibility into other users' drafts) + // + // Membership and collection access are resolved to id lists upfront so the + // search query needs no membership joins. Status/date narrowing is applied + // separately via `filter`. + // + // For Team contexts (share-based search), the caller is privileged and has + // done its own authorization — narrow to the filter's collectionId if + // specified, otherwise to the team's publicly-permissioned set. if (model instanceof User) { + const [membershipDocumentIds, collectionIds] = await Promise.all([ + Document.membershipDocumentIds(model.id), + model.collectionIds(), + ]); if (membershipDocumentIds.length) { where[Op.or].push({ id: membershipDocumentIds }); } - - // Allow users to see their own drafts that have no collection, where no - // membership or collection access applies. Drafts in collections remain - // gated by the collection/membership checks above. - if (options.statusFilter?.includes(StatusFilter.Draft)) { - where[Op.or].push({ - createdById: model.id, - collectionId: { [Op.is]: null }, - publishedAt: { [Op.eq]: null }, - archivedAt: { [Op.eq]: null }, - }); + where[Op.or].push({ + createdById: model.id, + collectionId: { [Op.is]: null }, + }); + if (collectionIds.length) { + where[Op.or].push( + { + collectionId: collectionIds, + publishedAt: { [Op.ne]: null }, + }, + { + createdById: model.id, + collectionId: collectionIds, + } + ); + } + } else { + const explicitCollectionIds = filter + ? collectEqValues(filter, "collectionId") + : []; + const collectionIds = explicitCollectionIds.length + ? explicitCollectionIds + : await model.collectionIds(); + if (collectionIds.length) { + where[Op.or].push({ collectionId: collectionIds }); } } - if (options.collectionId) { - where[Op.and].push({ collectionId: options.collectionId }); - } - if (collectionIds.length) { - where[Op.or].push({ collectionId: collectionIds }); - } - - if (options.dateFilter) { - where[Op.and].push({ - updatedAt: { - [Op.gt]: sequelize.literal( - `now() - interval '1 ${options.dateFilter}'` - ), - }, - }); - } - - if (options.collaboratorIds) { - where[Op.and].push({ - collaboratorIds: { - [Op.contains]: options.collaboratorIds, - }, - }); - } - - if (options.documentIds) { - where[Op.and].push({ - id: options.documentIds, - }); - } - - const statusQuery = []; - if (options.statusFilter?.includes(StatusFilter.Published)) { - statusQuery.push({ - [Op.and]: [ - { - publishedAt: { - [Op.ne]: null, - }, - archivedAt: { - [Op.eq]: null, - }, - }, - ], - }); - } - - if ( - options.statusFilter?.includes(StatusFilter.Draft) && - // Only include draft results for the user's own documents, or those - // explicitly shared with them - model instanceof User - ) { - statusQuery.push({ - [Op.and]: [ - { - publishedAt: { - [Op.eq]: null, - }, - archivedAt: { - [Op.eq]: null, - }, - [Op.or]: [ - { createdById: model.id }, - ...(membershipDocumentIds.length - ? [{ id: membershipDocumentIds }] - : []), - ], - }, - ], - }); - } - - if (options.statusFilter?.includes(StatusFilter.Archived)) { - statusQuery.push({ - archivedAt: { - [Op.ne]: null, - }, - }); - } - - if (statusQuery.length) { - where[Op.and].push({ - [Op.or]: statusQuery, - }); + if (filter) { + where[Op.and].push(buildSearchWhere(filter)); } if (options.query) { diff --git a/server/models/helpers/Filters.test.ts b/server/models/helpers/Filters.test.ts new file mode 100644 index 0000000000..c547163a4c --- /dev/null +++ b/server/models/helpers/Filters.test.ts @@ -0,0 +1,1318 @@ +import { Op } from "sequelize"; +import { CollectionPermission, StatusFilter } from "@shared/types"; +import { buildCollection, buildUser, buildTeam } from "@server/test/factories"; +import { + authorizeFilterFields, + buildSearchWhere, + buildWhere, + collectEqValues, + dateFromDuration, + expandDocumentIdInFilter, + extractTopLevelEqValue, + hasFieldInFilter, + legacyParamsToFilter, + mapFilterFields, +} from "./Filters"; + +describe("Filters", () => { + describe("buildWhere", () => { + it("converts an eq leaf to Op.eq", () => { + expect( + buildWhere({ field: "title", operator: "eq", value: "x" }) + ).toEqual({ title: { [Op.eq]: "x" } }); + }); + + it("converts contains to a wildcarded iLike with escaped pattern chars", () => { + expect( + buildWhere({ field: "title", operator: "contains", value: "50%_a" }) + ).toEqual({ title: { [Op.iLike]: "%50\\%\\_a%" } }); + }); + + it("converts startsWith to a trailing-wildcard iLike", () => { + expect( + buildWhere({ field: "title", operator: "startsWith", value: "Hi" }) + ).toEqual({ title: { [Op.iLike]: "Hi%" } }); + }); + + it("converts endsWith to a leading-wildcard iLike", () => { + expect( + buildWhere({ field: "title", operator: "endsWith", value: "End" }) + ).toEqual({ title: { [Op.iLike]: "%End" } }); + }); + + it("converts in to Op.in", () => { + expect( + buildWhere({ field: "templateId", operator: "in", value: ["a", "b"] }) + ).toEqual({ templateId: { [Op.in]: ["a", "b"] } }); + }); + + it("converts neq to Op.ne", () => { + expect( + buildWhere({ field: "title", operator: "neq", value: "x" }) + ).toEqual({ title: { [Op.ne]: "x" } }); + }); + + it("converts lt/lte/gt/gte", () => { + expect( + buildWhere({ field: "createdAt", operator: "lt", value: 1 }) + ).toEqual({ createdAt: { [Op.lt]: 1 } }); + expect( + buildWhere({ field: "createdAt", operator: "lte", value: 1 }) + ).toEqual({ createdAt: { [Op.lte]: 1 } }); + expect( + buildWhere({ field: "createdAt", operator: "gt", value: 1 }) + ).toEqual({ createdAt: { [Op.gt]: 1 } }); + expect( + buildWhere({ field: "createdAt", operator: "gte", value: 1 }) + ).toEqual({ createdAt: { [Op.gte]: 1 } }); + }); + + it("converts notIn to Op.notIn", () => { + expect( + buildWhere({ field: "templateId", operator: "notIn", value: ["a"] }) + ).toEqual({ templateId: { [Op.notIn]: ["a"] } }); + }); + + it("escapes backslashes in like values", () => { + expect( + buildWhere({ field: "title", operator: "contains", value: "a\\b" }) + ).toEqual({ title: { [Op.iLike]: "%a\\\\b%" } }); + }); + + it("leaves like values without special chars unmodified", () => { + expect( + buildWhere({ field: "title", operator: "endsWith", value: "abc" }) + ).toEqual({ title: { [Op.iLike]: "%abc" } }); + }); + + it("handles empty-string contains", () => { + expect( + buildWhere({ field: "title", operator: "contains", value: "" }) + ).toEqual({ title: { [Op.iLike]: "%%" } }); + }); + + it("converts a positive duration value on gte to a now()+interval literal", () => { + const result = buildWhere({ + field: "dueDate", + operator: "lte", + value: "P7D", + }) as Record>; + expect(result.dueDate[Op.lte].val).toBe("now() + interval 'P7D'"); + }); + + it("converts a negative duration value on gte to a now()-interval literal", () => { + const result = buildWhere({ + field: "updatedAt", + operator: "gte", + value: "-P7D", + }) as Record>; + expect(result.updatedAt[Op.gte].val).toBe("now() - interval 'P7D'"); + }); + + it("converts a duration on lt for the older-than case", () => { + const result = buildWhere({ + field: "updatedAt", + operator: "lt", + value: "-P30D", + }) as Record>; + expect(result.updatedAt[Op.lt].val).toBe("now() - interval 'P30D'"); + }); + + it("converts a duration on gt for the further-than-future case", () => { + const result = buildWhere({ + field: "dueDate", + operator: "gt", + value: "P1M", + }) as Record>; + expect(result.dueDate[Op.gt].val).toBe("now() + interval 'P1M'"); + }); + + it("does not transform a duration-shaped value on eq", () => { + expect( + buildWhere({ field: "title", operator: "eq", value: "P1D" }) + ).toEqual({ title: { [Op.eq]: "P1D" } }); + }); + + it("does not transform a duration-shaped value on neq", () => { + expect( + buildWhere({ field: "title", operator: "neq", value: "P1D" }) + ).toEqual({ title: { [Op.ne]: "P1D" } }); + }); + + it("does not transform duration-shaped values inside an in array", () => { + expect( + buildWhere({ field: "title", operator: "in", value: ["P1D"] }) + ).toEqual({ title: { [Op.in]: ["P1D"] } }); + }); + + it("does not transform duration-shaped values on non-date fields", () => { + // Converting would compare a text column against a timestamp and error + // at the database. + expect( + buildWhere({ field: "title", operator: "gte", value: "P1D" }) + ).toEqual({ title: { [Op.gte]: "P1D" } }); + }); + + it("passes through ISO 8601 datetimes unchanged on gte", () => { + expect( + buildWhere({ + field: "createdAt", + operator: "gte", + value: "2024-01-01", + }) + ).toEqual({ createdAt: { [Op.gte]: "2024-01-01" } }); + }); + + it("passes through numeric values unchanged on gte", () => { + expect( + buildWhere({ + field: "createdAt", + operator: "gte", + value: 1700000000, + }) + ).toEqual({ createdAt: { [Op.gte]: 1700000000 } }); + }); + + it("converts a flat AND group at the root", () => { + expect( + buildWhere({ + operator: "AND", + filters: [ + { field: "title", operator: "eq", value: "x" }, + { field: "templateId", operator: "isNull" }, + ], + }) + ).toEqual({ + [Op.and]: [ + { title: { [Op.eq]: "x" } }, + { templateId: { [Op.is]: null } }, + ], + }); + }); + + it("converts isNull and isNotNull", () => { + expect(buildWhere({ field: "publishedAt", operator: "isNull" })).toEqual({ + publishedAt: { [Op.is]: null }, + }); + expect( + buildWhere({ field: "publishedAt", operator: "isNotNull" }) + ).toEqual({ publishedAt: { [Op.not]: null } }); + }); + + it("converts an OR group recursively", () => { + const result = buildWhere({ + operator: "OR", + filters: [ + { field: "title", operator: "eq", value: "a" }, + { field: "title", operator: "eq", value: "b" }, + ], + }); + expect(result).toEqual({ + [Op.or]: [{ title: { [Op.eq]: "a" } }, { title: { [Op.eq]: "b" } }], + }); + }); + + it("converts nested AND-of-OR", () => { + const result = buildWhere({ + operator: "AND", + filters: [ + { field: "title", operator: "contains", value: "x" }, + { + operator: "OR", + filters: [ + { field: "templateId", operator: "isNull" }, + { field: "templateId", operator: "eq", value: "t1" }, + ], + }, + ], + }); + expect(result).toEqual({ + [Op.and]: [ + { title: { [Op.iLike]: "%x%" } }, + { + [Op.or]: [ + { templateId: { [Op.is]: null } }, + { templateId: { [Op.eq]: "t1" } }, + ], + }, + ], + }); + }); + + it("maps userId eq to collaboratorIds @> ARRAY[value]", () => { + expect( + buildWhere({ field: "userId", operator: "eq", value: "u1" }) + ).toEqual({ collaboratorIds: { [Op.contains]: ["u1"] } }); + }); + + it("maps userId in to collaboratorIds && ARRAY[...values] (any-of)", () => { + expect( + buildWhere({ field: "userId", operator: "in", value: ["a", "b"] }) + ).toEqual({ collaboratorIds: { [Op.overlap]: ["a", "b"] } }); + }); + + it("rejects userId with a non-eq/in operator", () => { + expect(() => + buildWhere({ field: "userId", operator: "neq", value: "u" }) + ).toThrow(); + }); + }); + + describe("dateFromDuration", () => { + it("returns a now()+interval literal for a positive duration", () => { + expect(dateFromDuration("P1D").val).toBe("now() + interval 'P1D'"); + }); + + it("preserves a multi-unit positive duration verbatim", () => { + expect(dateFromDuration("P1Y2M3DT4H5M6S").val).toBe( + "now() + interval 'P1Y2M3DT4H5M6S'" + ); + }); + + it("returns a now()-interval literal for a negative duration", () => { + expect(dateFromDuration("-P7D").val).toBe("now() - interval 'P7D'"); + }); + + it("strips the sign from the magnitude in negative durations", () => { + expect(dateFromDuration("-PT1H").val).toBe("now() - interval 'PT1H'"); + }); + + it.each(["", "P", "P1.5D", "P1D'", "P-1D", "p1d"])( + "throws on invalid input %j", + (value) => { + expect(() => dateFromDuration(value)).toThrow(/Invalid ISO 8601/); + } + ); + }); + + describe("hasFieldInFilter", () => { + it("finds a leaf field at the root", () => { + expect( + hasFieldInFilter( + { field: "archivedAt", operator: "isNotNull" }, + "archivedAt" + ) + ).toBe(true); + }); + + it("returns false for a non-matching leaf at the root", () => { + expect( + hasFieldInFilter( + { field: "title", operator: "eq", value: "x" }, + "archivedAt" + ) + ).toBe(false); + }); + + it("finds a field inside a nested group", () => { + const filter = { + operator: "OR" as const, + filters: [ + { field: "title", operator: "eq" as const, value: "x" }, + { + operator: "AND" as const, + filters: [{ field: "archivedAt", operator: "isNotNull" as const }], + }, + ], + }; + expect(hasFieldInFilter(filter, "archivedAt")).toBe(true); + expect(hasFieldInFilter(filter, "createdAt")).toBe(false); + }); + }); + + describe("collectEqValues", () => { + it("collects eq and in values across the tree", () => { + const values = collectEqValues( + { + operator: "OR", + filters: [ + { field: "collectionId", operator: "eq", value: "a" }, + { field: "collectionId", operator: "in", value: ["b", "c"] }, + { field: "collectionId", operator: "neq", value: "d" }, + ], + }, + "collectionId" + ); + expect(values.sort()).toEqual(["a", "b", "c"]); + }); + + it("collectEqValues returns an empty list when the field is absent", () => { + expect( + collectEqValues( + { field: "title", operator: "eq", value: "x" }, + "collectionId" + ) + ).toEqual([]); + }); + + it("collectEqValues ignores non-eq/in operators", () => { + expect( + collectEqValues( + { + operator: "AND", + filters: [ + { field: "collectionId", operator: "neq", value: "a" }, + { field: "collectionId", operator: "isNull" }, + { field: "collectionId", operator: "notIn", value: ["b"] }, + ], + }, + "collectionId" + ) + ).toEqual([]); + }); + + it("collectEqValues finds matches across deeply nested groups", () => { + const values = collectEqValues( + { + operator: "AND", + filters: [ + { + operator: "OR", + filters: [ + { field: "collectionId", operator: "eq", value: "a" }, + { + operator: "AND", + filters: [ + { field: "collectionId", operator: "in", value: ["b"] }, + ], + }, + ], + }, + ], + }, + "collectionId" + ); + expect(values.sort()).toEqual(["a", "b"]); + }); + }); + + describe("extractTopLevelEqValue", () => { + it("returns the value for a leaf at the root", () => { + expect( + extractTopLevelEqValue( + { field: "parentDocumentId", operator: "eq", value: "p1" }, + "parentDocumentId" + ) + ).toBe("p1"); + }); + + it("returns the value when wrapped in a single AND group", () => { + expect( + extractTopLevelEqValue( + { + operator: "AND", + filters: [ + { field: "title", operator: "eq", value: "x" }, + { field: "parentDocumentId", operator: "eq", value: "p1" }, + ], + }, + "parentDocumentId" + ) + ).toBe("p1"); + }); + + it("returns undefined inside an OR group", () => { + expect( + extractTopLevelEqValue( + { + operator: "OR", + filters: [ + { field: "parentDocumentId", operator: "eq", value: "p1" }, + { field: "parentDocumentId", operator: "eq", value: "p2" }, + ], + }, + "parentDocumentId" + ) + ).toBeUndefined(); + }); + + it("returns undefined when multiple eq leaves exist", () => { + expect( + extractTopLevelEqValue( + { + operator: "AND", + filters: [ + { field: "parentDocumentId", operator: "eq", value: "p1" }, + { field: "parentDocumentId", operator: "eq", value: "p2" }, + ], + }, + "parentDocumentId" + ) + ).toBeUndefined(); + }); + + it("returns undefined for a non-matching leaf at the root", () => { + expect( + extractTopLevelEqValue( + { field: "title", operator: "eq", value: "x" }, + "parentDocumentId" + ) + ).toBeUndefined(); + }); + + it("returns undefined when the matching leaf uses a non-eq operator", () => { + expect( + extractTopLevelEqValue( + { field: "parentDocumentId", operator: "isNull" }, + "parentDocumentId" + ) + ).toBeUndefined(); + }); + + it("returns undefined when the matching AND leaf uses a non-eq operator", () => { + expect( + extractTopLevelEqValue( + { + operator: "AND", + filters: [ + { field: "title", operator: "eq", value: "x" }, + { field: "parentDocumentId", operator: "isNull" }, + ], + }, + "parentDocumentId" + ) + ).toBeUndefined(); + }); + + it("returns undefined when an AND group has no matching leaves", () => { + expect( + extractTopLevelEqValue( + { + operator: "AND", + filters: [{ field: "title", operator: "eq", value: "x" }], + }, + "parentDocumentId" + ) + ).toBeUndefined(); + }); + + it("does not recurse into nested groups within AND", () => { + expect( + extractTopLevelEqValue( + { + operator: "AND", + filters: [ + { + operator: "AND", + filters: [ + { field: "parentDocumentId", operator: "eq", value: "p1" }, + ], + }, + ], + }, + "parentDocumentId" + ) + ).toBeUndefined(); + }); + }); + + describe("mapFilterFields", () => { + it("renames mapped fields and leaves others alone", () => { + const result = mapFilterFields( + { + operator: "AND", + filters: [ + { field: "userId", operator: "eq", value: "u1" }, + { field: "title", operator: "eq", value: "x" }, + ], + }, + { userId: "createdById" } + ); + expect(result).toEqual({ + operator: "AND", + filters: [ + { field: "createdById", operator: "eq", value: "u1" }, + { field: "title", operator: "eq", value: "x" }, + ], + }); + }); + + it("returns the same leaf when its field is not in the mapping", () => { + const leaf = { + field: "title" as const, + operator: "eq" as const, + value: "x", + }; + expect(mapFilterFields(leaf, { userId: "createdById" })).toBe(leaf); + }); + + it("renames a leaf at the root", () => { + expect( + mapFilterFields( + { field: "userId", operator: "eq", value: "u1" }, + { userId: "createdById" } + ) + ).toEqual({ field: "createdById", operator: "eq", value: "u1" }); + }); + + it("is a no-op when the mapping is empty", () => { + const leaf = { + field: "userId" as const, + operator: "eq" as const, + value: "u1", + }; + expect(mapFilterFields(leaf, {})).toBe(leaf); + }); + + it("renames fields inside nested groups", () => { + const result = mapFilterFields( + { + operator: "OR", + filters: [ + { + operator: "AND", + filters: [{ field: "userId", operator: "eq", value: "u1" }], + }, + ], + }, + { userId: "createdById" } + ); + expect(result).toEqual({ + operator: "OR", + filters: [ + { + operator: "AND", + filters: [{ field: "createdById", operator: "eq", value: "u1" }], + }, + ], + }); + }); + }); + + describe("legacyParamsToFilter", () => { + it("returns undefined when no legacy params are set", () => { + expect(legacyParamsToFilter({})).toBeUndefined(); + }); + + it("ignores parentDocumentId when undefined (distinct from null)", () => { + expect( + legacyParamsToFilter({ parentDocumentId: undefined }) + ).toBeUndefined(); + }); + + it("returns a single leaf when only one legacy param is set", () => { + expect(legacyParamsToFilter({ userId: "u1" })).toEqual({ + field: "userId", + operator: "eq", + value: "u1", + }); + }); + + it("converts parentDocumentId === null to isNull", () => { + expect(legacyParamsToFilter({ parentDocumentId: null })).toEqual({ + field: "parentDocumentId", + operator: "isNull", + }); + }); + + it("converts a truthy parentDocumentId to an eq leaf", () => { + expect(legacyParamsToFilter({ parentDocumentId: "p1" })).toEqual({ + field: "parentDocumentId", + operator: "eq", + value: "p1", + }); + }); + + it("ANDs all three legacy leaves when multiple are supplied", () => { + expect( + legacyParamsToFilter({ + userId: "u1", + collectionId: "c1", + parentDocumentId: "p1", + }) + ).toEqual({ + operator: "AND", + filters: [ + { field: "userId", operator: "eq", value: "u1" }, + { field: "collectionId", operator: "eq", value: "c1" }, + { field: "parentDocumentId", operator: "eq", value: "p1" }, + ], + }); + }); + + it("converts userId / documentId params to eq leaves", () => { + expect(legacyParamsToFilter({ userId: "u1", documentId: "d1" })).toEqual({ + operator: "AND", + filters: [ + { field: "userId", operator: "eq", value: "u1" }, + { field: "documentId", operator: "eq", value: "d1" }, + ], + }); + }); + + it("converts dateFilter to an updatedAt gte duration leaf", () => { + expect(legacyParamsToFilter({ dateFilter: "week" })).toEqual({ + field: "updatedAt", + operator: "gte", + value: "-P1W", + }); + }); + + it("converts a single statusFilter entry to its shape", () => { + expect( + legacyParamsToFilter({ statusFilter: [StatusFilter.Archived] }) + ).toEqual({ field: "archivedAt", operator: "isNotNull" }); + }); + + it("converts multiple statusFilter entries to an OR of shapes", () => { + expect( + legacyParamsToFilter({ + statusFilter: [StatusFilter.Published, StatusFilter.Archived], + }) + ).toEqual({ + operator: "OR", + filters: [ + { + operator: "AND", + filters: [ + { field: "archivedAt", operator: "isNull" }, + { field: "publishedAt", operator: "isNotNull" }, + ], + }, + { field: "archivedAt", operator: "isNotNull" }, + ], + }); + }); + + it("ANDs collectionId / dateFilter / statusFilter together", () => { + expect( + legacyParamsToFilter({ + collectionId: "c", + dateFilter: "day", + statusFilter: [StatusFilter.Archived], + }) + ).toEqual({ + operator: "AND", + filters: [ + { field: "collectionId", operator: "eq", value: "c" }, + { field: "updatedAt", operator: "gte", value: "-P1D" }, + { field: "archivedAt", operator: "isNotNull" }, + ], + }); + }); + }); + + describe("authorizeFilterFields", () => { + it("is a no-op when the filter does not reference collectionId", async () => { + const user = await buildUser(); + await expect( + authorizeFilterFields(user, { + field: "title", + operator: "eq", + value: "x", + }) + ).resolves.toBeUndefined(); + }); + + it("is a no-op when collectionId only appears via non-eq operators", async () => { + const user = await buildUser(); + await expect( + authorizeFilterFields(user, { + field: "collectionId", + operator: "isNotNull", + }) + ).resolves.toBeUndefined(); + }); + + it("authorizes an eq collectionId the user can read", async () => { + const team = await buildTeam(); + const user = await buildUser({ teamId: team.id }); + const collection = await buildCollection({ teamId: team.id }); + await expect( + authorizeFilterFields(user, { + field: "collectionId", + operator: "eq", + value: collection.id, + }) + ).resolves.toBeUndefined(); + }); + + it("authorizes every collection in an in-list", async () => { + const team = await buildTeam(); + const user = await buildUser({ teamId: team.id }); + const c1 = await buildCollection({ teamId: team.id }); + const c2 = await buildCollection({ teamId: team.id }); + await expect( + authorizeFilterFields(user, { + field: "collectionId", + operator: "in", + value: [c1.id, c2.id], + }) + ).resolves.toBeUndefined(); + }); + + it("authorizes collection references buried inside nested groups", async () => { + const team = await buildTeam(); + const user = await buildUser({ teamId: team.id }); + const collection = await buildCollection({ teamId: team.id }); + await expect( + authorizeFilterFields(user, { + operator: "OR", + filters: [ + { field: "title", operator: "eq", value: "x" }, + { + operator: "AND", + filters: [ + { + field: "collectionId", + operator: "eq", + value: collection.id, + }, + ], + }, + ], + }) + ).resolves.toBeUndefined(); + }); + + it("throws when the user cannot read the referenced collection", async () => { + const team = await buildTeam(); + const owner = await buildUser({ teamId: team.id }); + const outsider = await buildUser({ teamId: team.id }); + const privateCollection = await buildCollection({ + teamId: team.id, + userId: owner.id, + permission: null, + }); + await expect( + authorizeFilterFields(outsider, { + field: "collectionId", + operator: "eq", + value: privateCollection.id, + }) + ).rejects.toThrow(); + }); + + it("throws when any collection in an in-list is unauthorized", async () => { + const team = await buildTeam(); + const owner = await buildUser({ teamId: team.id }); + const outsider = await buildUser({ teamId: team.id }); + const accessible = await buildCollection({ + teamId: team.id, + permission: CollectionPermission.Read, + }); + const privateCollection = await buildCollection({ + teamId: team.id, + userId: owner.id, + permission: null, + }); + await expect( + authorizeFilterFields(outsider, { + field: "collectionId", + operator: "in", + value: [accessible.id, privateCollection.id], + }) + ).rejects.toThrow(); + }); + }); + + describe("buildSearchWhere", () => { + it("maps userId eq to collaboratorIds @> ARRAY[value]", () => { + expect( + buildSearchWhere({ field: "userId", operator: "eq", value: "u1" }) + ).toEqual({ collaboratorIds: { [Op.contains]: ["u1"] } }); + }); + + it("maps userId in to collaboratorIds && ARRAY[...values] (any-of)", () => { + expect( + buildSearchWhere({ field: "userId", operator: "in", value: ["a", "b"] }) + ).toEqual({ collaboratorIds: { [Op.overlap]: ["a", "b"] } }); + }); + + it("converts collectionId eq via the standard leaf conversion", () => { + expect( + buildSearchWhere({ field: "collectionId", operator: "eq", value: "c" }) + ).toEqual({ collectionId: { [Op.eq]: "c" } }); + }); + + it("converts an id in leaf (post-documentId expansion)", () => { + expect( + buildSearchWhere({ field: "id", operator: "in", value: ["a", "b"] }) + ).toEqual({ id: { [Op.in]: ["a", "b"] } }); + }); + + it("converts archivedAt isNotNull", () => { + expect( + buildSearchWhere({ field: "archivedAt", operator: "isNotNull" }) + ).toEqual({ archivedAt: { [Op.not]: null } }); + }); + + it("converts a published-shape AND group", () => { + expect( + buildSearchWhere({ + operator: "AND", + filters: [ + { field: "archivedAt", operator: "isNull" }, + { field: "publishedAt", operator: "isNotNull" }, + ], + }) + ).toEqual({ + [Op.and]: [ + { archivedAt: { [Op.is]: null } }, + { publishedAt: { [Op.not]: null } }, + ], + }); + }); + + it("converts an OR group of statuses", () => { + expect( + buildSearchWhere({ + operator: "OR", + filters: [ + { field: "archivedAt", operator: "isNotNull" }, + { + operator: "AND", + filters: [ + { field: "archivedAt", operator: "isNull" }, + { field: "publishedAt", operator: "isNotNull" }, + ], + }, + ], + }) + ).toEqual({ + [Op.or]: [ + { archivedAt: { [Op.not]: null } }, + { + [Op.and]: [ + { archivedAt: { [Op.is]: null } }, + { publishedAt: { [Op.not]: null } }, + ], + }, + ], + }); + }); + + it("converts updatedAt gte with an ISO duration to a literal", () => { + const result = buildSearchWhere({ + field: "updatedAt", + operator: "gte", + value: "-P7D", + }) as Record>; + expect(result.updatedAt[Op.gte].val).toBe("now() - interval 'P7D'"); + }); + + it("delegates non-search-specific fields to the standard leaf builder", () => { + // `title`/`createdAt`/etc. have no search-specific semantics — they + // map to the underlying column the same way `buildWhere` would. + expect( + buildSearchWhere({ field: "title", operator: "contains", value: "x" }) + ).toEqual({ title: { [Op.iLike]: "%x%" } }); + }); + + it("rejects userId with a non-eq/in operator", () => { + expect(() => + buildSearchWhere({ field: "userId", operator: "neq", value: "u" }) + ).toThrow(); + }); + + it("rejects documentId leaves (must be expanded by the route)", () => { + expect(() => + buildSearchWhere({ field: "documentId", operator: "eq", value: "d" }) + ).toThrow(); + }); + }); + + describe("expandDocumentIdInFilter", () => { + it("replaces a top-level documentId eq leaf with id in", () => { + expect( + expandDocumentIdInFilter( + { field: "documentId", operator: "eq", value: "p" }, + new Map([["p", ["p", "c1", "c2"]]]) + ) + ).toEqual({ field: "id", operator: "in", value: ["p", "c1", "c2"] }); + }); + + it("replaces a documentId leaf inside an AND group", () => { + expect( + expandDocumentIdInFilter( + { + operator: "AND", + filters: [ + { field: "title", operator: "eq", value: "x" }, + { field: "documentId", operator: "eq", value: "p" }, + ], + }, + new Map([["p", ["p", "c1"]]]) + ) + ).toEqual({ + operator: "AND", + filters: [ + { field: "title", operator: "eq", value: "x" }, + { field: "id", operator: "in", value: ["p", "c1"] }, + ], + }); + }); + + it("replaces a documentId in leaf with the deduped union of expansions", () => { + expect( + expandDocumentIdInFilter( + { field: "documentId", operator: "in", value: ["a", "b"] }, + new Map([ + ["a", ["a", "shared"]], + ["b", ["b", "shared"]], + ]) + ) + ).toEqual({ + field: "id", + operator: "in", + value: ["a", "shared", "b"], + }); + }); + + it("replaces multiple documentId leaves, including inside OR groups", () => { + expect( + expandDocumentIdInFilter( + { + operator: "OR", + filters: [ + { field: "documentId", operator: "eq", value: "a" }, + { field: "documentId", operator: "eq", value: "b" }, + ], + }, + new Map([ + ["a", ["a", "a1"]], + ["b", ["b", "b1"]], + ]) + ) + ).toEqual({ + operator: "OR", + filters: [ + { field: "id", operator: "in", value: ["a", "a1"] }, + { field: "id", operator: "in", value: ["b", "b1"] }, + ], + }); + }); + + it("falls back to the raw id when no expansion is present", () => { + expect( + expandDocumentIdInFilter( + { field: "documentId", operator: "eq", value: "unknown" }, + new Map([["p", ["p"]]]) + ) + ).toEqual({ field: "id", operator: "in", value: ["unknown"] }); + }); + + it("leaves non-documentId leaves untouched", () => { + const filter = { + field: "title" as const, + operator: "eq" as const, + value: "x", + }; + expect(expandDocumentIdInFilter(filter, new Map())).toEqual(filter); + }); + + describe("authorizeFilterFields", () => { + it("must authorize EVERY collectionId referenced anywhere in the tree", async () => { + // If the helper only checked top-level leaves, an attacker could + // smuggle an unauthorized collectionId into a nested OR. + const team = await buildTeam(); + const ownerA = await buildUser({ teamId: team.id }); + const ownerB = await buildUser({ teamId: team.id }); + const reader = await buildUser({ teamId: team.id }); + const accessible = await buildCollection({ + teamId: team.id, + userId: reader.id, + permission: CollectionPermission.Read, + }); + const inaccessible = await buildCollection({ + teamId: team.id, + userId: ownerA.id, + permission: null, + }); + + // Buried in an OR group with sibling fields. + const filter = { + operator: "OR" as const, + filters: [ + { + field: "collectionId", + operator: "eq" as const, + value: accessible.id, + }, + { + field: "collectionId", + operator: "eq" as const, + value: inaccessible.id, + }, + ], + }; + + await expect( + authorizeFilterFields(reader, filter) + ).rejects.toBeDefined(); + // Suppress unused var lint + expect(ownerB.id).toBeDefined(); + }); + + it("must authorize collectionId inside a deeply nested AND-OR chain", async () => { + const team = await buildTeam(); + const ownerA = await buildUser({ teamId: team.id }); + const reader = await buildUser({ teamId: team.id }); + const inaccessible = await buildCollection({ + teamId: team.id, + userId: ownerA.id, + permission: null, + }); + + const filter = { + operator: "AND" as const, + filters: [ + { field: "title", operator: "contains" as const, value: "x" }, + { + operator: "OR" as const, + filters: [ + { + operator: "AND" as const, + filters: [ + { + field: "collectionId", + operator: "eq" as const, + value: inaccessible.id, + }, + ], + }, + ], + }, + ], + }; + await expect( + authorizeFilterFields(reader, filter) + ).rejects.toBeDefined(); + }); + + it("must authorize every entry of an in[] list, even with one entry accessible", async () => { + const team = await buildTeam(); + const ownerA = await buildUser({ teamId: team.id }); + const reader = await buildUser({ teamId: team.id }); + const accessible = await buildCollection({ + teamId: team.id, + userId: reader.id, + permission: CollectionPermission.Read, + }); + const inaccessible = await buildCollection({ + teamId: team.id, + userId: ownerA.id, + permission: null, + }); + const filter = { + field: "collectionId" as const, + operator: "in" as const, + value: [accessible.id, inaccessible.id], + }; + await expect( + authorizeFilterFields(reader, filter) + ).rejects.toBeDefined(); + }); + + it("must NOT authorize values that are smuggled through non-eq/in operators today", () => { + // The current contract only authorizes via collectEqValues which + // ignores neq/contains/etc — so those operators must NOT be + // available as a way to scope queries to specific collections. + // The default visibility predicate in documents.list is the safety + // net that catches anything those operators try to expand into. + for (const op of [ + "neq", + "contains", + "startsWith", + "endsWith", + "notIn", + "isNull", + "isNotNull", + ] as const) { + const leaf = + op === "isNull" || op === "isNotNull" + ? { field: "collectionId", operator: op } + : op === "notIn" + ? { field: "collectionId", operator: op, value: ["x"] } + : { field: "collectionId", operator: op, value: "x" }; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + expect(collectEqValues(leaf as any, "collectionId")).toEqual([]); + } + }); + }); + + describe("extractTopLevelEqValue / parent-doc membership escape", () => { + it("must NOT extract a parentDocumentId nested inside an OR group", () => { + // The membership escape drops collection scoping when this returns + // a value. An OR-nested parentDocumentId must not trigger it. + const filter = { + operator: "OR" as const, + filters: [ + { + field: "parentDocumentId", + operator: "eq" as const, + value: "p1", + }, + { field: "title", operator: "contains" as const, value: "x" }, + ], + }; + expect( + extractTopLevelEqValue(filter, "parentDocumentId") + ).toBeUndefined(); + }); + + it("must NOT extract a parentDocumentId from a nested AND inside the root AND", () => { + // Only true top-level AND children count. Nested groups must not be + // recursed into. + const filter = { + operator: "AND" as const, + filters: [ + { field: "title", operator: "contains" as const, value: "x" }, + { + operator: "AND" as const, + filters: [ + { + field: "parentDocumentId", + operator: "eq" as const, + value: "p1", + }, + ], + }, + ], + }; + expect( + extractTopLevelEqValue(filter, "parentDocumentId") + ).toBeUndefined(); + }); + + it("must extract a parentDocumentId at the root or in a one-leaf top-level AND", () => { + expect( + extractTopLevelEqValue( + { + field: "parentDocumentId", + operator: "eq", + value: "p1", + }, + "parentDocumentId" + ) + ).toBe("p1"); + expect( + extractTopLevelEqValue( + { + operator: "AND", + filters: [ + { field: "title", operator: "contains", value: "x" }, + { field: "parentDocumentId", operator: "eq", value: "p1" }, + ], + }, + "parentDocumentId" + ) + ).toBe("p1"); + }); + + it("must NOT extract a parentDocumentId when more than one leaf references the field", () => { + // Ambiguous: two `eq` leaves on parentDocumentId (caller likely + // meant in[] but used a duplicated leaf instead). The escape must + // not engage with an ambiguous target. + expect( + extractTopLevelEqValue( + { + operator: "AND", + filters: [ + { field: "parentDocumentId", operator: "eq", value: "p1" }, + { field: "parentDocumentId", operator: "eq", value: "p2" }, + ], + }, + "parentDocumentId" + ) + ).toBeUndefined(); + }); + }); + + describe("buildWhere LIKE escaping", () => { + it("must escape backslashes in contains values", () => { + // Without escaping, `\%` would itself be interpreted as a literal + // `%` after PostgreSQL parses the LIKE pattern. + expect( + buildWhere({ + field: "title", + operator: "contains", + value: "a\\b", + }) + ).toEqual({ title: { [Op.iLike]: "%a\\\\b%" } }); + }); + + it("must escape underscores so they cannot match arbitrary chars", () => { + expect( + buildWhere({ + field: "title", + operator: "startsWith", + value: "a_b", + }) + ).toEqual({ title: { [Op.iLike]: "a\\_b%" } }); + }); + }); + + describe("dateFromDuration SQL safety", () => { + it("must throw on inputs containing SQL quote characters", () => { + expect(() => dateFromDuration("P1D' OR 1=1 --")).toThrow(); + }); + + it("must throw on inputs containing whitespace", () => { + expect(() => dateFromDuration("P 1D")).toThrow(); + }); + + it("must throw on inputs with disallowed characters", () => { + for (const value of [ + "P1D;DROP", + "P1D-", + "P1D--", + "P1D/*", + "P1D)", + "1D", + "PT", + "P", + "", + "P1.5D", + ]) { + expect(() => dateFromDuration(value)).toThrow(); + } + }); + }); + + describe("hasFieldInFilter", () => { + it("walks recursively across both AND and OR groups", () => { + const filter = { + operator: "AND" as const, + filters: [ + { + operator: "OR" as const, + filters: [ + { + field: "archivedAt", + operator: "isNotNull" as const, + }, + { field: "title", operator: "contains" as const, value: "x" }, + ], + }, + ], + }; + // The current handler uses this to disable the default + // archivedAt-is-null exclusion. That's defensible (a referenced + // archivedAt clause is the caller's intent), but the test pins the + // contract so future refactors don't silently change it. + expect(hasFieldInFilter(filter, "archivedAt")).toBe(true); + }); + }); + + describe("mapFilterFields", () => { + it("does not mutate the input filter tree", () => { + const original = { + operator: "AND" as const, + filters: [ + { field: "userId", operator: "eq" as const, value: "u1" }, + { + operator: "OR" as const, + filters: [ + { field: "documentId", operator: "eq" as const, value: "d1" }, + ], + }, + ], + }; + const snapshot = JSON.parse(JSON.stringify(original)); + mapFilterFields(original, { userId: "createdById", documentId: "id" }); + expect(original).toEqual(snapshot); + }); + }); + }); +}); diff --git a/server/models/helpers/Filters.ts b/server/models/helpers/Filters.ts new file mode 100644 index 0000000000..cd299661f2 --- /dev/null +++ b/server/models/helpers/Filters.ts @@ -0,0 +1,479 @@ +import { Op, Sequelize, type Utils, type WhereOptions } from "sequelize"; +import type { + ComparisonOperator, + Filter, + FilterCondition, + FilterGroup, +} from "@shared/helpers/FilterHelper"; +import { RANGE_OPERATORS } from "@shared/helpers/FilterHelper"; +import type { DateFilter, StatusFilter } from "@shared/types"; +import { StatusFilter as StatusFilterEnum } from "@shared/types"; +import { Collection } from "@server/models"; +import type User from "@server/models/User"; +import { authorize } from "@server/policies"; +import { isISO8601Duration } from "@server/validation"; + +const operatorMap: Record< + ComparisonOperator, + symbol | { op: symbol; transform?: (value: unknown) => unknown } +> = { + eq: Op.eq, + neq: Op.ne, + lt: Op.lt, + lte: Op.lte, + gt: Op.gt, + gte: Op.gte, + contains: Op.iLike, + startsWith: Op.iLike, + endsWith: Op.iLike, + containsStrict: Op.like, + startsWithStrict: Op.like, + endsWithStrict: Op.like, + in: Op.in, + notIn: Op.notIn, + isNull: Op.is, + isNotNull: Op.not, +}; + +/** Escape a value for safe use inside a SQL LIKE / iLike pattern. */ +function escapeLike(value: string): string { + return value.replace(/[\\%_]/g, (c) => `\\${c}`); +} + +// Only date fields support ISO 8601 duration values — converting durations on +// other fields (e.g. `title gte "P1D"`) would compare a text column against a +// timestamp and error at the database. Follows the codebase-wide naming +// convention for timestamp columns (`*At`, `*Date`). +const DATE_FIELD_RE = /(At|Date)$/; + +/** + * Convert an ISO 8601 duration into a Sequelize literal expressing + * `now() ± interval ''`. A leading `-` flips the sign, allowing + * relative-past durations (`-P7D` → `now() - 7 days`) and relative-future + * durations (`P7D` → `now() + 7 days`). + * + * @param duration an ISO 8601 duration, optionally signed with a leading `-`. + * @returns a Sequelize literal that resolves to `now() ± interval ''`. + * @throws if the input is not a valid ISO 8601 duration. + */ +export function dateFromDuration(duration: string): Utils.Literal { + if (!isISO8601Duration(duration)) { + throw new Error(`Invalid ISO 8601 duration: ${duration}`); + } + const negative = duration.startsWith("-"); + const magnitude = negative ? duration.slice(1) : duration; + const op = negative ? "-" : "+"; + return Sequelize.literal(`now() ${op} interval '${magnitude}'`); +} + +function isGroup( + filter: Filter +): filter is FilterGroup { + return "filters" in filter; +} + +function leafToWhere(condition: FilterCondition): Record { + const { field, operator, value } = condition; + + // `userId` is the public-API name for the denormalized collaboratorIds array + // column on Document. Semantics: "documents this user collaborated on". + if (field === "userId") { + if (operator === "eq" && value !== undefined) { + return { collaboratorIds: { [Op.contains]: [String(value)] } }; + } + if (operator === "in" && Array.isArray(value)) { + // `in` means "any of" — a document matches if it shares any collaborator + // with the list, so use array overlap (&&) rather than contains (@>), + // which would require every listed user to be a collaborator. + return { collaboratorIds: { [Op.overlap]: value.map(String) } }; + } + throw new Error("`userId` only supports `eq` or `in` operators"); + } + + switch (operator) { + case "isNull": + return { [field]: { [Op.is]: null } }; + case "isNotNull": + return { [field]: { [Op.not]: null } }; + case "contains": + return { [field]: { [Op.iLike]: `%${escapeLike(String(value))}%` } }; + case "startsWith": + return { [field]: { [Op.iLike]: `${escapeLike(String(value))}%` } }; + case "endsWith": + return { [field]: { [Op.iLike]: `%${escapeLike(String(value))}` } }; + case "containsStrict": + return { [field]: { [Op.like]: `%${escapeLike(String(value))}%` } }; + case "startsWithStrict": + return { [field]: { [Op.like]: `${escapeLike(String(value))}%` } }; + case "endsWithStrict": + return { [field]: { [Op.like]: `%${escapeLike(String(value))}` } }; + default: { + const op = operatorMap[operator]; + if (typeof op !== "symbol") { + throw new Error(`Unhandled filter operator: ${operator}`); + } + const resolved = + DATE_FIELD_RE.test(field) && + RANGE_OPERATORS.has(operator) && + typeof value === "string" && + isISO8601Duration(value) + ? dateFromDuration(value) + : value; + return { [field]: { [op]: resolved } }; + } + } +} + +/** + * Combine a list of filter expressions into a single tree, ANDing top-level entries. + * + * The wire-level API accepts `filters: Filter[]` with an implicit AND between + * entries; internal helpers operate on a single Filter tree. This bridges the two. + * + * @param filters the list of filter expressions, or undefined. + * @returns the equivalent single filter, or undefined if the list is empty/missing. + */ +export function combineFilters( + filters: Filter[] | undefined +): Filter | undefined { + if (!filters || filters.length === 0) { + return undefined; + } + if (filters.length === 1) { + return filters[0]; + } + return { operator: "AND", filters }; +} + +/** + * Convert a filter DSL expression into a Sequelize WhereOptions clause. + * + * @param filter the filter expression to convert. + * @returns a Sequelize-compatible where clause. + */ +export function buildWhere( + filter: Filter +): WhereOptions { + if (isGroup(filter)) { + const subWheres = filter.filters.map((f) => buildWhere(f)); + const op = filter.operator === "AND" ? Op.and : Op.or; + return { [op]: subWheres } as WhereOptions; + } + return leafToWhere(filter) as WhereOptions; +} + +/** + * Recursively check whether a filter references a particular field anywhere in its tree. + * + * @param filter the filter to inspect. + * @param field the field name to look for. + * @returns true if the field appears in any leaf condition. + */ +export function hasFieldInFilter(filter: Filter, field: string): boolean { + if (isGroup(filter)) { + return filter.filters.some((f) => hasFieldInFilter(f, field)); + } + return filter.field === field; +} + +/** + * Collect all values referenced by `eq` and `in` leaves for a given field. + * + * @param filter the filter to inspect. + * @param field the field name to extract values for. + * @returns the union of values across matching leaves; empty if none. + */ +export function collectEqValues(filter: Filter, field: string): string[] { + const out: string[] = []; + const walk = (f: Filter) => { + if (isGroup(f)) { + f.filters.forEach(walk); + return; + } + if (f.field !== field) { + return; + } + if (f.operator === "eq" && f.value !== undefined) { + out.push(String(f.value)); + } else if (f.operator === "in" && Array.isArray(f.value)) { + out.push(...f.value.map(String)); + } + }; + walk(filter); + return out; +} + +/** + * Extract a single top-level eq value for a given field, if present. + * + * Only matches when the filter root is either a leaf condition or an AND group + * containing exactly one matching leaf — used for handling parameters whose + * semantics only make sense as a single value (e.g. parentDocumentId membership + * escape, sort=index special case). + * + * @param filter the filter to inspect. + * @param field the field name to extract. + * @returns the single eq value, or undefined if not unambiguously present. + */ +export function extractTopLevelEqValue( + filter: Filter, + field: string +): string | undefined { + const leaves: FilterCondition[] = isGroup(filter) + ? filter.operator === "AND" + ? filter.filters.filter( + (f): f is FilterCondition => !isGroup(f) && f.field === field + ) + : [] + : filter.field === field + ? [filter] + : []; + + if (leaves.length !== 1) { + return undefined; + } + const leaf = leaves[0]; + if (leaf.operator !== "eq" || leaf.value === undefined) { + return undefined; + } + return String(leaf.value); +} + +/** + * Rename leaf field names according to a mapping. + * + * Used to bridge the public API field naming (e.g. `userId`) to the underlying + * Sequelize column name (e.g. `createdById`) without exposing the column name + * in the API. + * + * @param filter the filter to transform. + * @param mapping map of source field name to target column name. + * @returns a new filter with mapped field names; structure preserved. + */ +export function mapFilterFields( + filter: Filter, + mapping: Record +): Filter { + if (isGroup(filter)) { + return { + operator: filter.operator, + filters: filter.filters.map((f) => mapFilterFields(f, mapping)), + }; + } + const mapped = mapping[filter.field]; + return mapped ? { ...filter, field: mapped } : filter; +} + +function searchLeafToWhere( + condition: FilterCondition +): Record { + // documentId must be expanded to descendant ids by the route handler + // before reaching here — the expansion is async and authorization- + // sensitive. + if (condition.field === "documentId") { + throw new Error( + "documentId leaves must be expanded to `id` leaves before buildSearchWhere" + ); + } + return leafToWhere(condition); +} + +/** + * Convert a filter expression into a Sequelize WHERE clause for full-text + * search. Mirrors `buildWhere` apart from one field-specific guard: + * + * - `documentId` leaves must be expanded to `id` leaves by the route + * handler before reaching this function — `expandDocumentIdInFilter` + * handles that. + * + * @param filter the filter expression. + * @returns a Sequelize WHERE clause. + * @throws if the filter references documentId (unexpanded). + */ +export function buildSearchWhere( + filter: Filter +): WhereOptions { + if (isGroup(filter)) { + const subWheres = filter.filters.map((f) => buildSearchWhere(f)); + const op = filter.operator === "AND" ? Op.and : Op.or; + return { [op]: subWheres } as WhereOptions; + } + return searchLeafToWhere(filter) as WhereOptions; +} + +interface LegacyParams { + userId?: string; + collectionId?: string; + parentDocumentId?: string | null; + documentId?: string; + dateFilter?: DateFilter; + statusFilter?: StatusFilter[]; +} + +const DURATION_BY_DATE_FILTER: Record = { + day: "-P1D", + week: "-P1W", + month: "-P1M", + year: "-P1Y", +}; + +function statusToFilter(status: StatusFilter): Filter { + if (status === StatusFilterEnum.Archived) { + return { field: "archivedAt", operator: "isNotNull" }; + } + if (status === StatusFilterEnum.Published) { + return { + operator: "AND", + filters: [ + { field: "archivedAt", operator: "isNull" }, + { field: "publishedAt", operator: "isNotNull" }, + ], + }; + } + // Draft + return { + operator: "AND", + filters: [ + { field: "archivedAt", operator: "isNull" }, + { field: "publishedAt", operator: "isNull" }, + ], + }; +} + +/** + * Translate deprecated top-level params into an equivalent filter expression. + * Callers pass only the subset of params their route accepts; each one becomes + * a leaf (or sub-tree, for `statusFilter`), and all entries are ANDed together. + * + * Notable shapes: + * - `parentDocumentId === null` → `isNull` leaf (matches root-level docs). + * - `dateFilter` → `updatedAt gte` with an ISO 8601 duration literal. + * - `statusFilter` with multiple entries → OR of status shapes. + * + * @param legacy the deprecated top-level params. + * @returns the equivalent filter, or undefined if none were set. + */ +export function legacyParamsToFilter(legacy: LegacyParams): Filter | undefined { + const leaves: Filter[] = []; + + if (legacy.userId) { + leaves.push({ field: "userId", operator: "eq", value: legacy.userId }); + } + if (legacy.collectionId) { + leaves.push({ + field: "collectionId", + operator: "eq", + value: legacy.collectionId, + }); + } + if (legacy.parentDocumentId === null) { + leaves.push({ field: "parentDocumentId", operator: "isNull" }); + } else if (legacy.parentDocumentId) { + leaves.push({ + field: "parentDocumentId", + operator: "eq", + value: legacy.parentDocumentId, + }); + } + if (legacy.documentId) { + leaves.push({ + field: "documentId", + operator: "eq", + value: legacy.documentId, + }); + } + if (legacy.dateFilter) { + leaves.push({ + field: "updatedAt", + operator: "gte", + value: DURATION_BY_DATE_FILTER[legacy.dateFilter], + }); + } + if (legacy.statusFilter && legacy.statusFilter.length > 0) { + const statusShapes = legacy.statusFilter.map(statusToFilter); + leaves.push( + statusShapes.length === 1 + ? statusShapes[0] + : { operator: "OR", filters: statusShapes } + ); + } + + return combineFilters(leaves); +} + +/** + * Replace `documentId` leaves in a filter with `id in [...]` leaves using ids + * pre-resolved by the route handler (typically each document plus its + * descendant ids). `eq` leaves map to their document's expansion; `in` leaves + * map to the union of their documents' expansions. A document missing from the + * map falls back to its own id, which matches at most the document itself. + * + * @param filter the filter to transform. + * @param expandedIds map of documentId to its resolved id list. + * @returns a new filter with the substitution applied. + */ +export function expandDocumentIdInFilter( + filter: Filter, + expandedIds: Map +): Filter { + if (isGroup(filter)) { + return { + operator: filter.operator, + filters: filter.filters.map((f) => + expandDocumentIdInFilter(f, expandedIds) + ), + }; + } + if (filter.field !== "documentId") { + return filter; + } + // `eq` is the single-id case of `in`; both map to the deduped union of each + // document's pre-resolved expansion (falling back to the raw id). + let ids: string[] | undefined; + if (filter.operator === "eq" && filter.value !== undefined) { + ids = [String(filter.value)]; + } else if (filter.operator === "in" && Array.isArray(filter.value)) { + ids = filter.value.map(String); + } + if (!ids) { + return filter; + } + return { + field: "id", + operator: "in", + value: Array.from( + new Set(ids.flatMap((id) => expandedIds.get(id) ?? [id])) + ), + }; +} + +/** + * Re-run authorization for any auth-bearing fields referenced inside a filter. + * + * Currently authorizes each `collectionId` value referenced via `eq` or `in`, + * mirroring the authorize() call the legacy top-level `collectionId` param would + * have triggered. Throws if any referenced collection is not readable. + * + * @param user the current user. + * @param filter the filter to authorize. + * @throws if the user lacks read access to any referenced collection. + */ +export async function authorizeFilterFields( + user: User, + filter: Filter +): Promise { + const collectionIds = collectEqValues(filter, "collectionId"); + if (collectionIds.length === 0) { + return; + } + + const collections = await Promise.all( + Array.from(new Set(collectionIds)).map((id) => + Collection.findByPk(id, { userId: user.id }) + ) + ); + + for (const collection of collections) { + authorize(user, "readDocument", collection); + } +} diff --git a/server/routes/api/documents/documents.test.ts b/server/routes/api/documents/documents.test.ts index 396b133f24..34eb532096 100644 --- a/server/routes/api/documents/documents.test.ts +++ b/server/routes/api/documents/documents.test.ts @@ -1293,6 +1293,1354 @@ describe("#documents.list", () => { expect(body.data[0].id).toEqual(anotherDoc.id); }); + describe("filter DSL", () => { + it("should match a simple contains leaf case-insensitively", async () => { + const user = await buildUser(); + await buildDocument({ + title: "First document", + userId: user.id, + teamId: user.teamId, + }); + await buildDocument({ + title: "Second document", + userId: user.id, + teamId: user.teamId, + }); + + const res = await server.post("/api/documents.list", user, { + body: { + filters: [{ field: "title", operator: "contains", value: "first" }], + }, + }); + const body = await res.json(); + expect(res.status).toEqual(200); + expect(body.data).toHaveLength(1); + expect(body.data[0].title).toEqual("First document"); + }); + + it("should match an OR group", async () => { + const user = await buildUser(); + await buildDocument({ + title: "First document", + userId: user.id, + teamId: user.teamId, + }); + await buildDocument({ + title: "Second document", + userId: user.id, + teamId: user.teamId, + }); + + const res = await server.post("/api/documents.list", user, { + body: { + filters: [ + { + operator: "OR", + filters: [ + { field: "title", operator: "eq", value: "First document" }, + { field: "title", operator: "eq", value: "Second document" }, + ], + }, + ], + }, + }); + const body = await res.json(); + expect(res.status).toEqual(200); + expect(body.data).toHaveLength(2); + }); + + it("should reject an unknown field", async () => { + const user = await buildUser(); + const res = await server.post("/api/documents.list", user, { + body: { + filters: [{ field: "nope", operator: "eq", value: "x" }], + }, + }); + expect(res.status).toEqual(400); + }); + + it("should reject a value provided with isNull", async () => { + const user = await buildUser(); + const res = await server.post("/api/documents.list", user, { + body: { + filters: [{ field: "publishedAt", operator: "isNull", value: "x" }], + }, + }); + expect(res.status).toEqual(400); + }); + + it("should reject a scalar value for the in operator", async () => { + const user = await buildUser(); + const res = await server.post("/api/documents.list", user, { + body: { + filters: [{ field: "title", operator: "in", value: "x" }], + }, + }); + expect(res.status).toEqual(400); + }); + + it("should reject filter nesting beyond the depth limit", async () => { + const user = await buildUser(); + const leaf = { field: "title", operator: "eq", value: "x" }; + let nested: Record = leaf; + for (let i = 0; i < 6; i++) { + nested = { operator: "AND", filters: [nested] }; + } + const res = await server.post("/api/documents.list", user, { + body: { filters: [nested] }, + }); + expect(res.status).toEqual(400); + }); + + it("should not leak documents across teams", async () => { + const userA = await buildUser(); + const userB = await buildUser(); + await buildDocument({ + title: "Cross team", + userId: userB.id, + teamId: userB.teamId, + }); + const res = await server.post("/api/documents.list", userA, { + body: { + filters: [{ field: "title", operator: "eq", value: "Cross team" }], + }, + }); + const body = await res.json(); + expect(res.status).toEqual(200); + expect(body.data).toHaveLength(0); + }); + + it("should re-run authorize for collectionId in filter", async () => { + const user = await buildUser(); + const otherUser = await buildUser(); + const privateCollection = await buildCollection({ + teamId: otherUser.teamId, + userId: otherUser.id, + permission: null, + }); + const res = await server.post("/api/documents.list", user, { + body: { + filters: [ + { + field: "collectionId", + operator: "eq", + value: privateCollection.id, + }, + ], + }, + }); + expect(res.status).toEqual(403); + }); + + it("should include archived documents when filter references archivedAt", async () => { + const user = await buildUser(); + const archived = await buildDocument({ + title: "Old doc", + userId: user.id, + teamId: user.teamId, + archivedAt: new Date(), + }); + const res = await server.post("/api/documents.list", user, { + body: { + filters: [{ field: "archivedAt", operator: "isNotNull" }], + }, + }); + const body = await res.json(); + expect(res.status).toEqual(200); + expect(body.data.map((d: { id: string }) => d.id)).toContain(archived.id); + }); + + it("should escape LIKE wildcards in contains values", async () => { + const user = await buildUser(); + await buildDocument({ + title: "5050", + userId: user.id, + teamId: user.teamId, + }); + const literal = await buildDocument({ + title: "50% off", + userId: user.id, + teamId: user.teamId, + }); + + const res = await server.post("/api/documents.list", user, { + body: { + filters: [{ field: "title", operator: "contains", value: "50%" }], + }, + }); + const body = await res.json(); + expect(res.status).toEqual(200); + expect(body.data).toHaveLength(1); + expect(body.data[0].id).toEqual(literal.id); + }); + + it("should produce equivalent results for legacy collectionId and filter", async () => { + const user = await buildUser(); + const document = await buildDocument({ + userId: user.id, + teamId: user.teamId, + }); + const legacyRes = await server.post("/api/documents.list", user, { + body: { + collectionId: document.collectionId, + }, + }); + const filterRes = await server.post("/api/documents.list", user, { + body: { + filters: [ + { + field: "collectionId", + operator: "eq", + value: document.collectionId, + }, + ], + }, + }); + const legacyBody = await legacyRes.json(); + const filterBody = await filterRes.json(); + expect(legacyRes.status).toEqual(200); + expect(filterRes.status).toEqual(200); + expect(filterBody.data.map((d: { id: string }) => d.id).sort()).toEqual( + legacyBody.data.map((d: { id: string }) => d.id).sort() + ); + }); + + it("should reject filters combined with legacy userId", async () => { + const user = await buildUser(); + const res = await server.post("/api/documents.list", user, { + body: { + userId: user.id, + filters: [{ field: "title", operator: "eq", value: "Match" }], + }, + }); + expect(res.status).toEqual(400); + }); + + it("should reject filters combined with legacy collectionId", async () => { + const user = await buildUser(); + const document = await buildDocument({ + userId: user.id, + teamId: user.teamId, + }); + const res = await server.post("/api/documents.list", user, { + body: { + collectionId: document.collectionId, + filters: [{ field: "title", operator: "eq", value: "x" }], + }, + }); + expect(res.status).toEqual(400); + }); + + it("should reject filters combined with statusFilter", async () => { + const user = await buildUser(); + const res = await server.post("/api/documents.list", user, { + body: { + statusFilter: [StatusFilter.Archived], + filters: [{ field: "title", operator: "eq", value: "x" }], + }, + }); + expect(res.status).toEqual(400); + }); + + it("should apply parent-doc membership escape for parentDocumentId in filters", async () => { + const user = await buildUser(); + const otherUser = await buildUser({ teamId: user.teamId }); + const privateCollection = await buildCollection({ + teamId: user.teamId, + userId: otherUser.id, + permission: null, + }); + const parent = await buildDocument({ + teamId: user.teamId, + userId: otherUser.id, + collectionId: privateCollection.id, + }); + const child = await buildDocument({ + teamId: user.teamId, + userId: otherUser.id, + collectionId: privateCollection.id, + parentDocumentId: parent.id, + }); + await UserMembership.create({ + createdById: otherUser.id, + documentId: parent.id, + userId: user.id, + permission: DocumentPermission.Read, + }); + const res = await server.post("/api/documents.list", user, { + body: { + filters: [ + { field: "parentDocumentId", operator: "eq", value: parent.id }, + ], + }, + }); + const body = await res.json(); + expect(res.status).toEqual(200); + expect(body.data.map((d: { id: string }) => d.id)).toEqual([child.id]); + }); + + /** + * Helper: builds a viewing user plus a teammate-owned private collection + * containing one secret document. The viewing user has zero access to the + * collection. Tests below assert that no filter shape can surface the + * secret document to the viewing user. + */ + const setupVictim = async () => { + const viewer = await buildUser(); + const otherUser = await buildUser({ teamId: viewer.teamId }); + const privateCollection = await buildCollection({ + teamId: viewer.teamId, + userId: otherUser.id, + permission: null, + }); + const secretDoc = await buildDocument({ + title: "TOP SECRET PAYROLL", + text: "salaries everywhere", + teamId: viewer.teamId, + userId: otherUser.id, + collectionId: privateCollection.id, + }); + const ownCollection = await buildCollection({ + teamId: viewer.teamId, + userId: viewer.id, + }); + const ownDoc = await buildDocument({ + title: "Mundane", + teamId: viewer.teamId, + userId: viewer.id, + collectionId: ownCollection.id, + }); + return { + viewer, + otherUser, + privateCollection, + secretDoc, + ownCollection, + ownDoc, + }; + }; + + it("must not leak docs across collections via OR with collectionId+title", async () => { + const { viewer, ownCollection, secretDoc } = await setupVictim(); + + const res = await server.post("/api/documents.list", viewer, { + body: { + filters: [ + { + operator: "OR", + filters: [ + { + field: "collectionId", + operator: "eq", + value: ownCollection.id, + }, + { field: "title", operator: "contains", value: "secret" }, + ], + }, + ], + }, + }); + const body = await res.json(); + expect(res.status).toEqual(200); + const ids = body.data.map((d: { id: string }) => d.id); + expect(ids).not.toContain(secretDoc.id); + }); + + it("must not leak docs across collections via OR with collectionId+empty contains", async () => { + const { viewer, ownCollection, secretDoc } = await setupVictim(); + + const res = await server.post("/api/documents.list", viewer, { + body: { + filters: [ + { + operator: "OR", + filters: [ + { + field: "collectionId", + operator: "eq", + value: ownCollection.id, + }, + { field: "title", operator: "contains", value: "" }, + ], + }, + ], + }, + }); + const body = await res.json(); + expect(res.status).toEqual(200); + const ids = body.data.map((d: { id: string }) => d.id); + expect(ids).not.toContain(secretDoc.id); + }); + + it("must not leak docs across collections via OR with collectionId+userId of teammate", async () => { + const { viewer, otherUser, ownCollection, secretDoc } = + await setupVictim(); + + const res = await server.post("/api/documents.list", viewer, { + body: { + filters: [ + { + operator: "OR", + filters: [ + { + field: "collectionId", + operator: "eq", + value: ownCollection.id, + }, + { field: "userId", operator: "eq", value: otherUser.id }, + ], + }, + ], + }, + }); + const body = await res.json(); + expect(res.status).toEqual(200); + const ids = body.data.map((d: { id: string }) => d.id); + expect(ids).not.toContain(secretDoc.id); + }); + + it("must not leak docs across collections via OR using collectionId in[]", async () => { + const { viewer, ownCollection, secretDoc } = await setupVictim(); + + const res = await server.post("/api/documents.list", viewer, { + body: { + filters: [ + { + operator: "OR", + filters: [ + { + field: "collectionId", + operator: "in", + value: [ownCollection.id], + }, + { field: "title", operator: "contains", value: "" }, + ], + }, + ], + }, + }); + const body = await res.json(); + expect(res.status).toEqual(200); + const ids = body.data.map((d: { id: string }) => d.id); + expect(ids).not.toContain(secretDoc.id); + }); + + it("must not leak docs across collections via OR with collectionId nested in AND", async () => { + const { viewer, ownCollection, secretDoc } = await setupVictim(); + + const res = await server.post("/api/documents.list", viewer, { + body: { + filters: [ + { + operator: "OR", + filters: [ + { + operator: "AND", + filters: [ + { + field: "collectionId", + operator: "eq", + value: ownCollection.id, + }, + { field: "title", operator: "contains", value: "x" }, + ], + }, + { field: "title", operator: "contains", value: "" }, + ], + }, + ], + }, + }); + const body = await res.json(); + expect(res.status).toEqual(200); + const ids = body.data.map((d: { id: string }) => d.id); + expect(ids).not.toContain(secretDoc.id); + }); + + it("must not leak docs via OR with collectionId+documentId of secret doc", async () => { + const { viewer, ownCollection, secretDoc } = await setupVictim(); + + const res = await server.post("/api/documents.list", viewer, { + body: { + filters: [ + { + operator: "OR", + filters: [ + { + field: "collectionId", + operator: "eq", + value: ownCollection.id, + }, + { + field: "documentId", + operator: "eq", + value: secretDoc.id, + }, + ], + }, + ], + }, + }); + const body = await res.json(); + expect(res.status).toEqual(200); + const ids = body.data.map((d: { id: string }) => d.id); + expect(ids).not.toContain(secretDoc.id); + }); + + it("must not leak docs via deeply nested AND-of-OR with collectionId", async () => { + const { viewer, ownCollection, secretDoc } = await setupVictim(); + + const res = await server.post("/api/documents.list", viewer, { + body: { + filters: [ + { + operator: "AND", + filters: [ + { + operator: "OR", + filters: [ + { + field: "collectionId", + operator: "eq", + value: ownCollection.id, + }, + { field: "title", operator: "contains", value: "" }, + ], + }, + ], + }, + ], + }, + }); + const body = await res.json(); + expect(res.status).toEqual(200); + const ids = body.data.map((d: { id: string }) => d.id); + expect(ids).not.toContain(secretDoc.id); + }); + + it("must not leak docs via top-level array implicit-AND with sibling OR group", async () => { + const { viewer, ownCollection, secretDoc } = await setupVictim(); + + const res = await server.post("/api/documents.list", viewer, { + body: { + filters: [ + { + field: "collectionId", + operator: "eq", + value: ownCollection.id, + }, + { + operator: "OR", + filters: [ + { field: "title", operator: "contains", value: "" }, + { field: "title", operator: "contains", value: "secret" }, + ], + }, + ], + }, + }); + const body = await res.json(); + expect(res.status).toEqual(200); + // The collectionId leaf is at top level (AND), so semantically results + // must be limited to ownCollection. Secret doc lives in a different + // collection and must not appear. + const ids = body.data.map((d: { id: string }) => d.id); + expect(ids).not.toContain(secretDoc.id); + }); + + it("must reject OR with one authorized collectionId and one unauthorized collectionId", async () => { + const { viewer, ownCollection, privateCollection } = await setupVictim(); + + const res = await server.post("/api/documents.list", viewer, { + body: { + filters: [ + { + operator: "OR", + filters: [ + { + field: "collectionId", + operator: "eq", + value: ownCollection.id, + }, + { + field: "collectionId", + operator: "eq", + value: privateCollection.id, + }, + ], + }, + ], + }, + }); + // Authorize must run for every collectionId eq value referenced + // anywhere in the tree. The unauthorized one must trigger 403. + expect(res.status).toEqual(403); + }); + + it("must reject in[] containing both an authorized and unauthorized collection", async () => { + const { viewer, ownCollection, privateCollection } = await setupVictim(); + + const res = await server.post("/api/documents.list", viewer, { + body: { + filters: [ + { + field: "collectionId", + operator: "in", + value: [ownCollection.id, privateCollection.id], + }, + ], + }, + }); + expect(res.status).toEqual(403); + }); + + it("must not leak docs from a private collection via filtering by teammate userId", async () => { + // No collectionId in filter at all — just createdById of a teammate. + // The default collection scope must still apply, restricting results to + // the viewer's accessible collections. + const { viewer, otherUser, secretDoc } = await setupVictim(); + + const res = await server.post("/api/documents.list", viewer, { + body: { + filters: [{ field: "userId", operator: "eq", value: otherUser.id }], + }, + }); + const body = await res.json(); + expect(res.status).toEqual(200); + const ids = body.data.map((d: { id: string }) => d.id); + expect(ids).not.toContain(secretDoc.id); + }); + + it("must not leak a secret doc by direct documentId lookup", async () => { + const { viewer, secretDoc } = await setupVictim(); + + const res = await server.post("/api/documents.list", viewer, { + body: { + filters: [ + { field: "documentId", operator: "eq", value: secretDoc.id }, + ], + }, + }); + const body = await res.json(); + expect(res.status).toEqual(200); + const ids = body.data.map((d: { id: string }) => d.id); + expect(ids).not.toContain(secretDoc.id); + }); + + it("must not leak secret docs via documentId in[]", async () => { + const { viewer, secretDoc, ownDoc } = await setupVictim(); + + const res = await server.post("/api/documents.list", viewer, { + body: { + filters: [ + { + field: "documentId", + operator: "in", + value: [secretDoc.id, ownDoc.id], + }, + ], + }, + }); + const body = await res.json(); + expect(res.status).toEqual(200); + const ids = body.data.map((d: { id: string }) => d.id); + expect(ids).not.toContain(secretDoc.id); + expect(ids).toContain(ownDoc.id); + }); + + it("must not leak archived docs in private collections via archivedAt filter", async () => { + const viewer = await buildUser(); + const otherUser = await buildUser({ teamId: viewer.teamId }); + const privateCollection = await buildCollection({ + teamId: viewer.teamId, + userId: otherUser.id, + permission: null, + }); + const archivedSecret = await buildDocument({ + title: "Archived secret", + teamId: viewer.teamId, + userId: otherUser.id, + collectionId: privateCollection.id, + archivedAt: new Date(), + }); + + const res = await server.post("/api/documents.list", viewer, { + body: { + filters: [{ field: "archivedAt", operator: "isNotNull" }], + }, + }); + const body = await res.json(); + expect(res.status).toEqual(200); + const ids = body.data.map((d: { id: string }) => d.id); + expect(ids).not.toContain(archivedSecret.id); + }); + + it("must not bypass collection scope via templateId filter", async () => { + const { viewer, otherUser, privateCollection, secretDoc } = + await setupVictim(); + const template = await buildTemplate({ + teamId: viewer.teamId, + userId: otherUser.id, + collectionId: privateCollection.id, + }); + // Make the secret doc reference the template + await secretDoc.update({ templateId: template.id }); + + const res = await server.post("/api/documents.list", viewer, { + body: { + filters: [ + { field: "templateId", operator: "eq", value: template.id }, + ], + }, + }); + const body = await res.json(); + expect(res.status).toEqual(200); + const ids = body.data.map((d: { id: string }) => d.id); + expect(ids).not.toContain(secretDoc.id); + }); + + it("must not leak docs across teams via cross-team collectionId in OR", async () => { + const viewer = await buildUser(); + const otherTeamUser = await buildUser(); + const otherTeamCollection = await buildCollection({ + teamId: otherTeamUser.teamId, + userId: otherTeamUser.id, + }); + const otherTeamDoc = await buildDocument({ + title: "Other team secret", + teamId: otherTeamUser.teamId, + userId: otherTeamUser.id, + collectionId: otherTeamCollection.id, + }); + + const res = await server.post("/api/documents.list", viewer, { + body: { + filters: [ + { + operator: "OR", + filters: [ + { field: "title", operator: "contains", value: "secret" }, + { + field: "collectionId", + operator: "eq", + value: otherTeamCollection.id, + }, + ], + }, + ], + }, + }); + // Either the cross-team collection auth fails (403), or the doc is + // simply not returned because the team filter filters it out. Both + // outcomes are acceptable; what is NOT acceptable is leaking the doc. + if (res.status === 200) { + const body = await res.json(); + const ids = body.data.map((d: { id: string }) => d.id); + expect(ids).not.toContain(otherTeamDoc.id); + } else { + expect(res.status).toEqual(403); + } + }); + + it("must not leak docs via parentDocumentId membership escape combined with sibling collectionId access", async () => { + // Membership escape on parentDocumentId drops the default collection + // scope. If the schema then ANDs the parentDocumentId leaf with the + // rest of the filter, results must still be restricted to actual + // children of the parent doc. + const viewer = await buildUser(); + const otherUser = await buildUser({ teamId: viewer.teamId }); + const privateCollection = await buildCollection({ + teamId: viewer.teamId, + userId: otherUser.id, + permission: null, + }); + const parent = await buildDocument({ + teamId: viewer.teamId, + userId: otherUser.id, + collectionId: privateCollection.id, + }); + const sibling = await buildDocument({ + title: "Sibling not a child", + teamId: viewer.teamId, + userId: otherUser.id, + collectionId: privateCollection.id, + }); + await UserMembership.create({ + createdById: otherUser.id, + documentId: parent.id, + userId: viewer.id, + permission: DocumentPermission.Read, + }); + + const res = await server.post("/api/documents.list", viewer, { + body: { + filters: [ + { field: "parentDocumentId", operator: "eq", value: parent.id }, + { field: "title", operator: "contains", value: "" }, + ], + }, + }); + const body = await res.json(); + expect(res.status).toEqual(200); + const ids = body.data.map((d: { id: string }) => d.id); + // The viewer has membership on `parent`, so its children would be + // returned. But `sibling` is not a child of `parent`, so it must not + // appear despite living in the same private collection. + expect(ids).not.toContain(sibling.id); + }); + + it("must not leak docs via parentDocumentId in OR with collectionId", async () => { + // Even if the filter mentions parentDocumentId in an OR, the membership + // escape must not engage (it requires a single, top-level eq). And the + // OR with collectionId must not drop the default collection scope. + const viewer = await buildUser(); + const otherUser = await buildUser({ teamId: viewer.teamId }); + const privateCollection = await buildCollection({ + teamId: viewer.teamId, + userId: otherUser.id, + permission: null, + }); + const parent = await buildDocument({ + teamId: viewer.teamId, + userId: otherUser.id, + collectionId: privateCollection.id, + }); + const child = await buildDocument({ + teamId: viewer.teamId, + userId: otherUser.id, + collectionId: privateCollection.id, + parentDocumentId: parent.id, + }); + await UserMembership.create({ + createdById: otherUser.id, + documentId: parent.id, + userId: viewer.id, + permission: DocumentPermission.Read, + }); + const ownCollection = await buildCollection({ + teamId: viewer.teamId, + userId: viewer.id, + }); + + const res = await server.post("/api/documents.list", viewer, { + body: { + filters: [ + { + operator: "OR", + filters: [ + { field: "parentDocumentId", operator: "eq", value: parent.id }, + { + field: "collectionId", + operator: "eq", + value: ownCollection.id, + }, + ], + }, + ], + }, + }); + const body = await res.json(); + // Inside an OR group, the membership escape on parentDocumentId is not + // triggered. The default collection scope must therefore still apply, + // and the child of `parent` (which lives in a private collection the + // viewer cannot access) must not appear. + expect(res.status).toEqual(200); + const ids = body.data.map((d: { id: string }) => d.id); + expect(ids).not.toContain(child.id); + }); + + it("must not return drafts of other users via filter", async () => { + // Draft visibility is enforced by statusFilter handling for the + // legacy path; with filters it must still hold. + const viewer = await buildUser(); + const otherUser = await buildUser({ teamId: viewer.teamId }); + const sharedCollection = await buildCollection({ + teamId: viewer.teamId, + userId: viewer.id, + }); + const otherDraft = await buildDraftDocument({ + title: "Other user draft", + teamId: viewer.teamId, + userId: otherUser.id, + collectionId: sharedCollection.id, + }); + + const res = await server.post("/api/documents.list", viewer, { + body: { + filters: [{ field: "publishedAt", operator: "isNull" }], + }, + }); + const body = await res.json(); + expect(res.status).toEqual(200); + const ids = body.data.map((d: { id: string }) => d.id); + expect(ids).not.toContain(otherDraft.id); + }); + + it("should return own drafts via publishedAt isNull filter", async () => { + const viewer = await buildUser(); + const collection = await buildCollection({ + teamId: viewer.teamId, + userId: viewer.id, + }); + const collectionlessDraft = await buildDraftDocument({ + title: "My unplaced draft", + teamId: viewer.teamId, + userId: viewer.id, + }); + const collectionDraft = await buildDraftDocument({ + title: "My collection draft", + teamId: viewer.teamId, + userId: viewer.id, + collectionId: collection.id, + }); + const published = await buildDocument({ + title: "Published", + teamId: viewer.teamId, + userId: viewer.id, + collectionId: collection.id, + }); + + const res = await server.post("/api/documents.list", viewer, { + body: { + filters: [{ field: "publishedAt", operator: "isNull" }], + }, + }); + const body = await res.json(); + expect(res.status).toEqual(200); + const ids = body.data.map((d: { id: string }) => d.id); + expect(ids).toContain(collectionlessDraft.id); + expect(ids).toContain(collectionDraft.id); + expect(ids).not.toContain(published.id); + }); + + it("should return drafts shared via direct membership when filtering publishedAt", async () => { + const viewer = await buildUser(); + const otherUser = await buildUser({ teamId: viewer.teamId }); + const sharedCollection = await buildCollection({ + teamId: viewer.teamId, + userId: viewer.id, + }); + const sharedDraft = await buildDraftDocument({ + title: "Shared draft", + teamId: viewer.teamId, + userId: otherUser.id, + collectionId: sharedCollection.id, + }); + await UserMembership.create({ + userId: viewer.id, + documentId: sharedDraft.id, + permission: DocumentPermission.Read, + createdById: otherUser.id, + }); + + const res = await server.post("/api/documents.list", viewer, { + body: { + filters: [{ field: "publishedAt", operator: "isNull" }], + }, + }); + const body = await res.json(); + expect(res.status).toEqual(200); + const ids = body.data.map((d: { id: string }) => d.id); + expect(ids).toContain(sharedDraft.id); + }); + + it("must not bypass collection scope via collectionId neq", async () => { + // `neq` must not be considered an explicit collection target. The + // default collection scope must still apply. + const { viewer, secretDoc } = await setupVictim(); + + const res = await server.post("/api/documents.list", viewer, { + body: { + filters: [ + { + field: "collectionId", + operator: "neq", + value: "00000000-0000-0000-0000-000000000000", + }, + ], + }, + }); + const body = await res.json(); + expect(res.status).toEqual(200); + const ids = body.data.map((d: { id: string }) => d.id); + expect(ids).not.toContain(secretDoc.id); + }); + + it("must not bypass collection scope via collectionId notIn", async () => { + // `notIn` must not be considered an explicit collection target. + const { viewer, secretDoc } = await setupVictim(); + + const res = await server.post("/api/documents.list", viewer, { + body: { + filters: [ + { + field: "collectionId", + operator: "notIn", + value: ["00000000-0000-0000-0000-000000000000"], + }, + ], + }, + }); + const body = await res.json(); + expect(res.status).toEqual(200); + const ids = body.data.map((d: { id: string }) => d.id); + expect(ids).not.toContain(secretDoc.id); + }); + + it("must not bypass collection scope via collectionId isNotNull", async () => { + const { viewer, secretDoc } = await setupVictim(); + + const res = await server.post("/api/documents.list", viewer, { + body: { + filters: [{ field: "collectionId", operator: "isNotNull" }], + }, + }); + const body = await res.json(); + expect(res.status).toEqual(200); + const ids = body.data.map((d: { id: string }) => d.id); + expect(ids).not.toContain(secretDoc.id); + }); + + it("must not bypass auth via collectionId pattern matching", async () => { + // contains/startsWith/endsWith on collectionId must not be treated as + // an explicit collection target. Postgres may also error out applying + // iLike to a UUID column — that's a separate availability concern, + // but either way no data must leak. + const { viewer, secretDoc, privateCollection } = await setupVictim(); + + const res = await server.post("/api/documents.list", viewer, { + body: { + filters: [ + { + field: "collectionId", + operator: "startsWith", + value: privateCollection.id.substring(0, 8), + }, + ], + }, + }); + // Acceptable: 200 with empty/scoped data, 400 (validation), or 500 + // (SQL type mismatch). Unacceptable: 200 with the secret doc visible. + if (res.status === 200) { + const body = await res.json(); + const ids = body.data.map((d: { id: string }) => d.id); + expect(ids).not.toContain(secretDoc.id); + } else { + expect([400, 500]).toContain(res.status); + } + }); + + it("must not allow contains-injected SQL wildcards to broaden matches", async () => { + // The `%` and `_` characters in user-supplied contains values must be + // escaped so they cannot match unrelated rows. + const user = await buildUser(); + const decoy = await buildDocument({ + title: "abxc", + teamId: user.teamId, + userId: user.id, + }); + const target = await buildDocument({ + title: "ab_c", + teamId: user.teamId, + userId: user.id, + }); + + const res = await server.post("/api/documents.list", user, { + body: { + filters: [{ field: "title", operator: "contains", value: "ab_c" }], + }, + }); + const body = await res.json(); + expect(res.status).toEqual(200); + const ids = body.data.map((d: { id: string }) => d.id); + expect(ids).toContain(target.id); + expect(ids).not.toContain(decoy.id); + }); + + it("must reject NOT-style operators that are not in the comparison allowlist", async () => { + const user = await buildUser(); + const res = await server.post("/api/documents.list", user, { + body: { + filters: [ + { field: "title", operator: "regexp", value: ".*" } as never, + ], + }, + }); + expect(res.status).toEqual(400); + }); + + it("must reject filters when an empty array is passed", async () => { + const user = await buildUser(); + const res = await server.post("/api/documents.list", user, { + body: { filters: [] }, + }); + expect(res.status).toEqual(400); + }); + + it("must reject filters when in[] is empty", async () => { + const user = await buildUser(); + const res = await server.post("/api/documents.list", user, { + body: { + filters: [{ field: "title", operator: "in", value: [] }], + }, + }); + expect(res.status).toEqual(400); + }); + + it("must not allow exceeding the top-level filter count limit", async () => { + const user = await buildUser(); + const filters = Array.from({ length: 51 }).map(() => ({ + field: "title", + operator: "eq", + value: "x", + })); + const res = await server.post("/api/documents.list", user, { + body: { filters }, + }); + expect(res.status).toEqual(400); + }); + + it("must not allow exceeding maxInValues limit on in[]", async () => { + const user = await buildUser(); + const value = Array.from({ length: 101 }).map( + (_, i) => `00000000-0000-0000-0000-${String(i).padStart(12, "0")}` + ); + const res = await server.post("/api/documents.list", user, { + body: { + filters: [{ field: "documentId", operator: "in", value }], + }, + }); + expect(res.status).toEqual(400); + }); + + it("must reject unsupported operators for userId", async () => { + const user = await buildUser(); + const res = await server.post("/api/documents.list", user, { + body: { + filters: [{ field: "userId", operator: "isNotNull" }], + }, + }); + expect(res.status).toEqual(400); + }); + + it("must reject SQL-injection attempts in ISO 8601 duration values", async () => { + // dateFromDuration interpolates the duration into a Sequelize literal. + // The validation regex must reject anything containing quote + // characters or other SQL metacharacters. + const user = await buildUser(); + const res = await server.post("/api/documents.list", user, { + body: { + filters: [ + { + field: "updatedAt", + operator: "gte", + value: "P1D'; DROP TABLE documents; --", + }, + ], + }, + }); + // The value isn't a valid duration so it falls through as a literal + // string compared via Op.gte. That comparison will either return zero + // rows or fail at the type-cast level; what matters is no SQL error + // and no leaked rows. Acceptable: 200 with empty data, or 400. + expect([200, 400]).toContain(res.status); + if (res.status === 200) { + const body = await res.json(); + // No rows should leak. + expect(Array.isArray(body.data)).toBe(true); + } + }); + + it("must compare duration-shaped values on non-date fields as strings", async () => { + // A duration-shaped value must only be converted to a date literal for + // date fields; on a text field it is a plain string comparison. + const user = await buildUser(); + const document = await buildDocument({ + title: "Zebra", + teamId: user.teamId, + userId: user.id, + }); + const res = await server.post("/api/documents.list", user, { + body: { + filters: [{ field: "title", operator: "gte", value: "P1D" }], + }, + }); + const body = await res.json(); + expect(res.status).toEqual(200); + const ids = body.data.map((d: { id: string }) => d.id); + expect(ids).toContain(document.id); + }); + + it("must reject an out-of-range duration rather than fail at the database", async () => { + const user = await buildUser(); + for (const value of [ + "-P999999999Y", + "P999999999Y", + "-PT99999999999999999S", + ]) { + const filters = [{ field: "createdAt", operator: "gte", value }]; + for (const endpoint of [ + "/api/documents.list", + "/api/documents.search", + "/api/documents.search_titles", + ]) { + const res = await server.post(endpoint, user, { + body: { query: "test", filters }, + }); + expect(res.status).toEqual(400); + } + } + }); + + it("must reject an out-of-range duration on an unauthenticated share search", async () => { + const team = await buildTeam(); + const author = await buildUser({ teamId: team.id }); + const document = await buildDocument({ + teamId: team.id, + userId: author.id, + }); + const share = await buildShare({ + teamId: team.id, + userId: author.id, + documentId: document.id, + includeChildDocuments: true, + published: true, + }); + + const res = await server.post("/api/documents.search", { + body: { + shareId: share.id, + query: "test", + filters: [ + { field: "createdAt", operator: "gte", value: "-P999999999Y" }, + ], + }, + }); + expect(res.status).toEqual(400); + }); + + it("must reject a filter expression over the node limit", async () => { + const user = await buildUser(); + const leaf = { field: "title", operator: "eq", value: "x" }; + // Depth 3 with 7 filters per group is inside both shape limits, but + // holds 57 nodes. + const wide = { + operator: "OR", + filters: Array.from({ length: 7 }, () => ({ + operator: "OR", + filters: Array.from({ length: 7 }, () => leaf), + })), + }; + for (const endpoint of [ + "/api/documents.list", + "/api/documents.search", + "/api/documents.search_titles", + ]) { + const res = await server.post(endpoint, user, { + body: { query: "test", filters: [wide] }, + }); + expect(res.status).toEqual(400); + } + }); + + it("must reject a filter list whose entries total over the node limit", async () => { + const user = await buildUser(); + // Each entry is inside the per-expression limit; the sum is not. + const filters = Array.from({ length: 5 }, () => ({ + operator: "OR", + filters: Array.from({ length: 10 }, () => ({ + field: "title", + operator: "eq", + value: "x", + })), + })); + const res = await server.post("/api/documents.list", user, { + body: { filters }, + }); + expect(res.status).toEqual(400); + }); + + it("must accept the widest filter expression the app builds", async () => { + const user = await buildUser(); + const collection = await buildCollection({ + teamId: user.teamId, + userId: user.id, + }); + const res = await server.post("/api/documents.list", user, { + body: { + filters: [ + { field: "collectionId", operator: "eq", value: collection.id }, + { field: "userId", operator: "eq", value: user.id }, + { field: "updatedAt", operator: "gte", value: "-P1Y" }, + { + operator: "OR", + filters: [ + { field: "archivedAt", operator: "isNotNull" }, + { + operator: "AND", + filters: [ + { field: "archivedAt", operator: "isNull" }, + { field: "publishedAt", operator: "isNotNull" }, + ], + }, + { + operator: "AND", + filters: [ + { field: "archivedAt", operator: "isNull" }, + { field: "publishedAt", operator: "isNull" }, + ], + }, + ], + }, + ], + }, + }); + expect(res.status).toEqual(200); + }); + + it("must not leak draft drafts via OR with createdById self + collectionId of teammate's collection", async () => { + // Drafts are restricted to creator + members. Filter DSL must not + // provide a path to bypass that. + const viewer = await buildUser(); + const otherUser = await buildUser({ teamId: viewer.teamId }); + const sharedCollection = await buildCollection({ + teamId: viewer.teamId, + userId: viewer.id, + }); + const otherDraft = await buildDraftDocument({ + title: "Other user secret draft", + teamId: viewer.teamId, + userId: otherUser.id, + collectionId: sharedCollection.id, + }); + + const res = await server.post("/api/documents.list", viewer, { + body: { + filters: [ + { + operator: "OR", + filters: [ + { field: "userId", operator: "eq", value: viewer.id }, + { + field: "collectionId", + operator: "eq", + value: sharedCollection.id, + }, + ], + }, + ], + }, + }); + const body = await res.json(); + expect(res.status).toEqual(200); + const ids = body.data.map((d: { id: string }) => d.id); + // statusFilter is not set in this request, so drafts shouldn't be + // included by default — but verify either way that the other user's + // draft is not exposed. + expect(ids).not.toContain(otherDraft.id); + }); + }); + it("should require authentication", async () => { const res = await server.post("/api/documents.list"); const body = await res.json(); @@ -1598,6 +2946,210 @@ describe("#documents.search_titles", () => { const res = await server.post("/api/documents.search_titles"); expect(res.status).toEqual(401); }); + + describe("filter DSL", () => { + it("should filter by userId via collaboratorIds", async () => { + const user = await buildUser(); + const document = await buildDocument({ + title: "match title", + teamId: user.teamId, + userId: user.id, + }); + await buildDocument({ + title: "match title", + teamId: user.teamId, + }); + const res = await server.post("/api/documents.search_titles", user, { + body: { + query: "match", + filters: [{ field: "userId", operator: "eq", value: user.id }], + }, + }); + const body = await res.json(); + expect(res.status).toEqual(200); + expect(body.data).toHaveLength(1); + expect(body.data[0].id).toEqual(document.id); + }); + + it("should filter by documentId scope", async () => { + const user = await buildUser(); + const parent = await buildDocument({ + title: "parent match", + teamId: user.teamId, + userId: user.id, + }); + const child = await buildDocument({ + title: "child match", + teamId: user.teamId, + userId: user.id, + parentDocumentId: parent.id, + collectionId: parent.collectionId, + }); + await buildDocument({ + title: "unrelated match", + teamId: user.teamId, + userId: user.id, + }); + const res = await server.post("/api/documents.search_titles", user, { + body: { + query: "match", + filters: [{ field: "documentId", operator: "eq", value: parent.id }], + }, + }); + const body = await res.json(); + expect(res.status).toEqual(200); + const returnedIds = body.data.map((d: { id: string }) => d.id).sort(); + expect(returnedIds).toEqual([parent.id, child.id].sort()); + }); + + it("should reject filters combined with legacy userId", async () => { + const user = await buildUser(); + const res = await server.post("/api/documents.search_titles", user, { + body: { + query: "match", + userId: user.id, + filters: [{ field: "userId", operator: "eq", value: user.id }], + }, + }); + expect(res.status).toEqual(400); + }); + + it("must not leak titles via OR with collectionId+title", async () => { + const viewer = await buildUser(); + const otherUser = await buildUser({ teamId: viewer.teamId }); + const privateCollection = await buildCollection({ + teamId: viewer.teamId, + userId: otherUser.id, + permission: null, + }); + const secretDoc = await buildDocument({ + title: "TOP SECRET match", + teamId: viewer.teamId, + userId: otherUser.id, + collectionId: privateCollection.id, + }); + const ownCollection = await buildCollection({ + teamId: viewer.teamId, + userId: viewer.id, + }); + const res = await server.post("/api/documents.search_titles", viewer, { + body: { + query: "match", + filters: [ + { + operator: "OR", + filters: [ + { + field: "collectionId", + operator: "eq", + value: ownCollection.id, + }, + { field: "title", operator: "contains", value: "match" }, + ], + }, + ], + }, + }); + const body = await res.json(); + expect(res.status).toEqual(200); + const ids = body.data.map((d: { id: string }) => d.id); + expect(ids).not.toContain(secretDoc.id); + }); + + it("must not leak titles via collectionId in[] sibling to a permissive leaf", async () => { + const viewer = await buildUser(); + const otherUser = await buildUser({ teamId: viewer.teamId }); + const privateCollection = await buildCollection({ + teamId: viewer.teamId, + userId: otherUser.id, + permission: null, + }); + const secretDoc = await buildDocument({ + title: "TOP SECRET match", + teamId: viewer.teamId, + userId: otherUser.id, + collectionId: privateCollection.id, + }); + const ownCollection = await buildCollection({ + teamId: viewer.teamId, + userId: viewer.id, + }); + const res = await server.post("/api/documents.search_titles", viewer, { + body: { + query: "match", + filters: [ + { + operator: "OR", + filters: [ + { + field: "collectionId", + operator: "in", + value: [ownCollection.id], + }, + { field: "title", operator: "contains", value: "" }, + ], + }, + ], + }, + }); + const body = await res.json(); + expect(res.status).toEqual(200); + const ids = body.data.map((d: { id: string }) => d.id); + expect(ids).not.toContain(secretDoc.id); + }); + + it("must 403 when a private collection is targeted via filter", async () => { + const viewer = await buildUser(); + const otherUser = await buildUser(); + const privateCollection = await buildCollection({ + teamId: otherUser.teamId, + userId: otherUser.id, + permission: null, + }); + const res = await server.post("/api/documents.search_titles", viewer, { + body: { + query: "secret", + filters: [ + { + field: "collectionId", + operator: "eq", + value: privateCollection.id, + }, + ], + }, + }); + expect(res.status).toEqual(403); + }); + + it("must 403 on documentId scope to a doc the user cannot read", async () => { + const viewer = await buildUser(); + const otherUser = await buildUser({ teamId: viewer.teamId }); + const privateCollection = await buildCollection({ + teamId: viewer.teamId, + userId: otherUser.id, + permission: null, + }); + const secretParent = await buildDocument({ + teamId: viewer.teamId, + userId: otherUser.id, + collectionId: privateCollection.id, + }); + + const res = await server.post("/api/documents.search_titles", viewer, { + body: { + query: "x", + filters: [ + { + field: "documentId", + operator: "eq", + value: secretParent.id, + }, + ], + }, + }); + expect(res.status).toEqual(403); + }); + }); }); describe("#documents.search", () => { @@ -2204,6 +3756,614 @@ describe("#documents.search", () => { const expectedIds = docsInCollection1.map((d) => d.id).sort(); expect(returnedIds).toEqual(expectedIds); }); + + describe("filter DSL", () => { + it("should produce equivalent results for legacy collectionId and filter", async () => { + const user = await buildUser(); + const document = await buildDocument({ + title: "search term", + text: "search term", + teamId: user.teamId, + userId: user.id, + }); + const legacyRes = await server.post("/api/documents.search", user, { + body: { + query: "search term", + collectionId: document.collectionId, + }, + }); + const filterRes = await server.post("/api/documents.search", user, { + body: { + query: "search term", + filters: [ + { + field: "collectionId", + operator: "eq", + value: document.collectionId, + }, + ], + }, + }); + const legacyBody = await legacyRes.json(); + const filterBody = await filterRes.json(); + expect(legacyRes.status).toEqual(200); + expect(filterRes.status).toEqual(200); + expect( + filterBody.data + .map((r: { document: { id: string } }) => r.document.id) + .sort() + ).toEqual( + legacyBody.data + .map((r: { document: { id: string } }) => r.document.id) + .sort() + ); + }); + + it("should filter by userId via collaboratorIds", async () => { + const user = await buildUser(); + const document = await buildDocument({ + title: "search term", + text: "search term", + teamId: user.teamId, + userId: user.id, + }); + await buildDocument({ + title: "search term", + text: "search term", + teamId: user.teamId, + }); + const res = await server.post("/api/documents.search", user, { + body: { + query: "search term", + filters: [{ field: "userId", operator: "eq", value: user.id }], + }, + }); + const body = await res.json(); + expect(res.status).toEqual(200); + expect(body.data).toHaveLength(1); + expect(body.data[0].document.id).toEqual(document.id); + }); + + it("should filter by documentId scope", async () => { + const user = await buildUser(); + const parent = await buildDocument({ + title: "parent", + text: "search term", + teamId: user.teamId, + userId: user.id, + }); + const child = await buildDocument({ + title: "child", + text: "search term", + teamId: user.teamId, + userId: user.id, + parentDocumentId: parent.id, + collectionId: parent.collectionId, + }); + await buildDocument({ + title: "unrelated", + text: "search term", + teamId: user.teamId, + userId: user.id, + }); + const res = await server.post("/api/documents.search", user, { + body: { + query: "search term", + filters: [{ field: "documentId", operator: "eq", value: parent.id }], + }, + }); + const body = await res.json(); + expect(res.status).toEqual(200); + const returnedIds = body.data + .map((r: { document: { id: string } }) => r.document.id) + .sort(); + expect(returnedIds).toEqual([parent.id, child.id].sort()); + }); + + it("should filter by documentId in[] scope", async () => { + const user = await buildUser(); + const parentA = await buildDocument({ + title: "parentA", + text: "search term", + teamId: user.teamId, + userId: user.id, + }); + const childA = await buildDocument({ + title: "childA", + text: "search term", + teamId: user.teamId, + userId: user.id, + parentDocumentId: parentA.id, + collectionId: parentA.collectionId, + }); + const parentB = await buildDocument({ + title: "parentB", + text: "search term", + teamId: user.teamId, + userId: user.id, + }); + await buildDocument({ + title: "unrelated", + text: "search term", + teamId: user.teamId, + userId: user.id, + }); + const res = await server.post("/api/documents.search", user, { + body: { + query: "search term", + filters: [ + { + field: "documentId", + operator: "in", + value: [parentA.id, parentB.id], + }, + ], + }, + }); + const body = await res.json(); + expect(res.status).toEqual(200); + const returnedIds = body.data + .map((r: { document: { id: string } }) => r.document.id) + .sort(); + expect(returnedIds).toEqual([parentA.id, childA.id, parentB.id].sort()); + }); + + it("should expand documentId leaves nested inside groups", async () => { + const user = await buildUser(); + const parentA = await buildDocument({ + title: "parentA", + text: "search term", + teamId: user.teamId, + userId: user.id, + }); + const parentB = await buildDocument({ + title: "parentB", + text: "search term", + teamId: user.teamId, + userId: user.id, + }); + await buildDocument({ + title: "unrelated", + text: "search term", + teamId: user.teamId, + userId: user.id, + }); + const res = await server.post("/api/documents.search", user, { + body: { + query: "search term", + filters: [ + { + operator: "OR", + filters: [ + { field: "documentId", operator: "eq", value: parentA.id }, + { field: "documentId", operator: "eq", value: parentB.id }, + ], + }, + ], + }, + }); + const body = await res.json(); + expect(res.status).toEqual(200); + const returnedIds = body.data + .map((r: { document: { id: string } }) => r.document.id) + .sort(); + expect(returnedIds).toEqual([parentA.id, parentB.id].sort()); + }); + + it("should reject unsupported operators for documentId", async () => { + const user = await buildUser(); + const res = await server.post("/api/documents.search", user, { + body: { + query: "search term", + filters: [{ field: "documentId", operator: "isNotNull" }], + }, + }); + expect(res.status).toEqual(400); + }); + + it("should reject unsupported operators for userId", async () => { + const user = await buildUser(); + const res = await server.post("/api/documents.search", user, { + body: { + query: "search term", + filters: [{ field: "userId", operator: "neq", value: user.id }], + }, + }); + expect(res.status).toEqual(400); + }); + + it("should scope results to a documentId filter combined with shareId", async () => { + const subdomain = faker.internet.domainWord(); + const team = await buildTeam({ subdomain }); + const parent = await buildDocument({ + title: "search term", + text: "parent", + teamId: team.id, + }); + const childA = await buildDocument({ + title: "search term", + text: "childA", + teamId: team.id, + userId: parent.createdById, + parentDocumentId: parent.id, + collectionId: parent.collectionId, + }); + await buildDocument({ + title: "search term", + text: "childB", + teamId: team.id, + userId: parent.createdById, + parentDocumentId: parent.id, + collectionId: parent.collectionId, + }); + await buildShare({ + includeChildDocuments: true, + documentId: parent.id, + teamId: team.id, + urlId: "abc456", + }); + + const res = await server.post("/api/documents.search", { + body: { + query: "search term", + shareId: "abc456", + filters: [{ field: "documentId", operator: "eq", value: childA.id }], + }, + headers: { + host: `${subdomain}.outline.dev`, + }, + }); + const body = await res.json(); + expect(res.status).toEqual(200); + expect(body.data.length).toEqual(1); + expect(body.data[0].document.id).toEqual(childA.id); + }); + + it("should scope results to the legacy documentId param combined with shareId", async () => { + const subdomain = faker.internet.domainWord(); + const team = await buildTeam({ subdomain }); + const parent = await buildDocument({ + title: "search term", + text: "parent", + teamId: team.id, + }); + const childA = await buildDocument({ + title: "search term", + text: "childA", + teamId: team.id, + userId: parent.createdById, + parentDocumentId: parent.id, + collectionId: parent.collectionId, + }); + await buildDocument({ + title: "search term", + text: "childB", + teamId: team.id, + userId: parent.createdById, + parentDocumentId: parent.id, + collectionId: parent.collectionId, + }); + await buildShare({ + includeChildDocuments: true, + documentId: parent.id, + teamId: team.id, + urlId: "abc789", + }); + + const res = await server.post("/api/documents.search", { + body: { + query: "search term", + shareId: "abc789", + documentId: childA.id, + }, + headers: { + host: `${subdomain}.outline.dev`, + }, + }); + const body = await res.json(); + expect(res.status).toEqual(200); + expect(body.data.length).toEqual(1); + expect(body.data[0].document.id).toEqual(childA.id); + }); + + it("should re-run authorize for collectionId in filter", async () => { + const user = await buildUser(); + const otherUser = await buildUser(); + const privateCollection = await buildCollection({ + teamId: otherUser.teamId, + userId: otherUser.id, + permission: null, + }); + const res = await server.post("/api/documents.search", user, { + body: { + query: "search term", + filters: [ + { + field: "collectionId", + operator: "eq", + value: privateCollection.id, + }, + ], + }, + }); + expect(res.status).toEqual(403); + }); + + it("should reject filters combined with legacy collectionId", async () => { + const user = await buildUser(); + const document = await buildDocument({ + userId: user.id, + teamId: user.teamId, + }); + const res = await server.post("/api/documents.search", user, { + body: { + collectionId: document.collectionId, + filters: [ + { + field: "collectionId", + operator: "eq", + value: document.collectionId, + }, + ], + }, + }); + expect(res.status).toEqual(400); + }); + + it("supports title contains as an additional filter alongside the FTS query", async () => { + const user = await buildUser(); + const match = await buildDocument({ + title: "match needle", + text: "search term", + teamId: user.teamId, + userId: user.id, + }); + await buildDocument({ + title: "no needle here", + text: "search term", + teamId: user.teamId, + userId: user.id, + }); + const res = await server.post("/api/documents.search", user, { + body: { + query: "search term", + filters: [{ field: "title", operator: "contains", value: "match" }], + }, + }); + const body = await res.json(); + expect(res.status).toEqual(200); + const ids = body.data.map( + (r: { document: { id: string } }) => r.document.id + ); + expect(ids).toContain(match.id); + }); + + it("supports an OR group at top level without bypassing visibility", async () => { + const viewer = await buildUser(); + const otherUser = await buildUser({ teamId: viewer.teamId }); + const ownCollection = await buildCollection({ + teamId: viewer.teamId, + userId: viewer.id, + }); + const ownDoc = await buildDocument({ + title: "search term in own", + text: "search term", + teamId: viewer.teamId, + userId: viewer.id, + collectionId: ownCollection.id, + }); + const res = await server.post("/api/documents.search", viewer, { + body: { + query: "search term", + filters: [ + { + operator: "OR", + filters: [ + { + field: "collectionId", + operator: "eq", + value: ownCollection.id, + }, + { field: "userId", operator: "eq", value: otherUser.id }, + ], + }, + ], + }, + }); + const body = await res.json(); + expect(res.status).toEqual(200); + const ids = body.data.map( + (r: { document: { id: string } }) => r.document.id + ); + expect(ids).toContain(ownDoc.id); + }); + + /** + * Helper: builds a viewer plus a teammate-owned private collection + * containing one secret document. The viewer has zero access to the + * collection. Tests below assert that no search-filter shape can + * surface the secret document to the viewer. + */ + const setupVictim = async () => { + const viewer = await buildUser(); + const otherUser = await buildUser({ teamId: viewer.teamId }); + const privateCollection = await buildCollection({ + teamId: viewer.teamId, + userId: otherUser.id, + permission: null, + }); + const secretDoc = await buildDocument({ + title: "TOP SECRET PAYROLL", + text: "secret material body", + teamId: viewer.teamId, + userId: otherUser.id, + collectionId: privateCollection.id, + }); + const ownCollection = await buildCollection({ + teamId: viewer.teamId, + userId: viewer.id, + }); + return { + viewer, + otherUser, + privateCollection, + secretDoc, + ownCollection, + }; + }; + + it("must not leak docs across collections via OR with collectionId+title", async () => { + const { viewer, ownCollection, secretDoc } = await setupVictim(); + const res = await server.post("/api/documents.search", viewer, { + body: { + query: "secret material", + filters: [ + { + operator: "OR", + filters: [ + { + field: "collectionId", + operator: "eq", + value: ownCollection.id, + }, + { field: "title", operator: "contains", value: "secret" }, + ], + }, + ], + }, + }); + const body = await res.json(); + expect(res.status).toEqual(200); + const ids = body.data.map( + (r: { document: { id: string } }) => r.document.id + ); + expect(ids).not.toContain(secretDoc.id); + }); + + it("must not leak docs via OR with collectionId+userId of teammate", async () => { + const { viewer, otherUser, ownCollection, secretDoc } = + await setupVictim(); + const res = await server.post("/api/documents.search", viewer, { + body: { + query: "secret material", + filters: [ + { + operator: "OR", + filters: [ + { + field: "collectionId", + operator: "eq", + value: ownCollection.id, + }, + { field: "userId", operator: "eq", value: otherUser.id }, + ], + }, + ], + }, + }); + const body = await res.json(); + expect(res.status).toEqual(200); + const ids = body.data.map( + (r: { document: { id: string } }) => r.document.id + ); + expect(ids).not.toContain(secretDoc.id); + }); + + it("must not leak docs via deeply nested AND-of-OR with collectionId", async () => { + const { viewer, ownCollection, secretDoc } = await setupVictim(); + const res = await server.post("/api/documents.search", viewer, { + body: { + query: "secret material", + filters: [ + { + operator: "AND", + filters: [ + { + operator: "OR", + filters: [ + { + field: "collectionId", + operator: "eq", + value: ownCollection.id, + }, + { field: "title", operator: "contains", value: "" }, + ], + }, + ], + }, + ], + }, + }); + const body = await res.json(); + expect(res.status).toEqual(200); + const ids = body.data.map( + (r: { document: { id: string } }) => r.document.id + ); + expect(ids).not.toContain(secretDoc.id); + }); + + it("must 403 when filter targets a private collection", async () => { + const viewer = await buildUser(); + const otherUser = await buildUser(); + const privateCollection = await buildCollection({ + teamId: otherUser.teamId, + userId: otherUser.id, + permission: null, + }); + const res = await server.post("/api/documents.search", viewer, { + body: { + query: "x", + filters: [ + { + field: "collectionId", + operator: "eq", + value: privateCollection.id, + }, + ], + }, + }); + expect(res.status).toEqual(403); + }); + + it("must 403 when filter targets a documentId in a private collection", async () => { + const viewer = await buildUser(); + const otherUser = await buildUser({ teamId: viewer.teamId }); + const privateCollection = await buildCollection({ + teamId: viewer.teamId, + userId: otherUser.id, + permission: null, + }); + const secret = await buildDocument({ + teamId: viewer.teamId, + userId: otherUser.id, + collectionId: privateCollection.id, + }); + const res = await server.post("/api/documents.search", viewer, { + body: { + query: "x", + filters: [{ field: "documentId", operator: "eq", value: secret.id }], + }, + }); + expect(res.status).toEqual(403); + }); + + it("must 403 when in[] contains both an authorized and unauthorized collection", async () => { + const { viewer, ownCollection, privateCollection } = await setupVictim(); + const res = await server.post("/api/documents.search", viewer, { + body: { + query: "x", + filters: [ + { + field: "collectionId", + operator: "in", + value: [ownCollection.id, privateCollection.id], + }, + ], + }, + }); + expect(res.status).toEqual(403); + }); + }); }); describe("#documents.templatize", () => { diff --git a/server/routes/api/documents/documents.ts b/server/routes/api/documents/documents.ts index 57cf43805e..7a2b1954ae 100644 --- a/server/routes/api/documents/documents.ts +++ b/server/routes/api/documents/documents.ts @@ -7,6 +7,7 @@ import Router from "koa-router"; import { escapeRegExp, has, remove, uniq } from "es-toolkit/compat"; import mime from "mime-types"; import type { Order, ScopeOptions, WhereOptions } from "sequelize"; +import type { Filter } from "@shared/helpers/FilterHelper"; import { Op, Sequelize } from "sequelize"; import { randomUUID } from "node:crypto"; import type { DirectionFilter, SortFilter } from "@shared/types"; @@ -65,6 +66,17 @@ import { import { SearchQuerySource } from "@server/models/SearchQuery"; import AttachmentHelper from "@server/models/helpers/AttachmentHelper"; import { DocumentHelper } from "@server/models/helpers/DocumentHelper"; +import { + authorizeFilterFields, + buildWhere, + collectEqValues, + combineFilters, + expandDocumentIdInFilter, + extractTopLevelEqValue, + hasFieldInFilter, + legacyParamsToFilter, + mapFilterFields, +} from "@server/models/helpers/Filters"; import HTMLHelper from "@server/models/helpers/HTMLHelper"; import { ProsemirrorHelper } from "@server/models/helpers/ProsemirrorHelper"; import TextBundleHelper from "@server/models/helpers/TextBundleHelper"; @@ -101,6 +113,92 @@ import { const router = new Router(); +/** + * Resolve every `documentId` leaf in a search filter to an `id in [...]` leaf + * containing the document and all of its descendants. When a user is given, + * each referenced document is authorized for read access. In share contexts + * the expansion is only scoped to the share's team — results are constrained + * to the share's own document subtree by the provider, so no per-document + * authorization is needed. + * + * @param filter the search filter to transform. + * @param context the user performing the search, or the share's team scope. + * @returns the filter with documentId leaves expanded, or the original filter + * if none are present. + */ +async function expandDocumentIdLeaves( + filter: Filter, + context: { user: User } | { teamId: string } +): Promise { + const documentIds = uniq(collectEqValues(filter, "documentId")); + if (documentIds.length === 0) { + return filter; + } + + const expandedIds = new Map(); + await Promise.all( + documentIds.map(async (documentId) => { + if ("user" in context) { + const document = await Document.findByPk(documentId, { + userId: context.user.id, + }); + authorize(context.user, "read", document); + expandedIds.set(documentId, [ + documentId, + ...(await document.findAllChildDocumentIds()), + ]); + } else { + const document = await Document.unscoped().findOne({ + where: { id: documentId, teamId: context.teamId }, + }); + expandedIds.set( + documentId, + document + ? [documentId, ...(await document.findAllChildDocumentIds())] + : [documentId] + ); + } + }) + ); + + return expandDocumentIdInFilter(filter, expandedIds); +} + +/** + * Fetch the ids of documents the user has a direct membership on. Used to + * express draft visibility without referencing the (separately-loaded) + * memberships association, which would otherwise break the COUNT query. + * + * @param user the user to fetch membership document ids for. + * @returns the list of document ids. + */ +async function directMembershipDocumentIds(user: User): Promise { + const memberships = await UserMembership.findAll({ + attributes: ["documentId"], + where: { + userId: user.id, + documentId: { [Op.ne]: null }, + }, + }); + return memberships.map((m) => m.documentId as string); +} + +/** + * Build the visibility clauses for drafts: a draft is only ever visible to its + * creator or to a user with a direct membership on it. Both the filter-derived + * and legacy statusFilter draft paths route through this so the invariant lives + * in one place. + * + * @param user the user the drafts must be visible to. + * @returns an array of OR-able Sequelize conditions. + */ +async function draftVisibilityClauses(user: User): Promise { + return [ + { createdById: user.id }, + { id: await directMembershipDocumentIds(user) }, + ]; +} + router.post( "documents.list", rateLimiter(RateLimiterStrategy.OneHundredPerMinute), @@ -111,12 +209,13 @@ router.post( const { sort, direction, - collectionId, backlinkDocumentId, - parentDocumentId, - userId: createdById, + parentDocumentId: legacyParentDocumentId, + userId: legacyUserId, statusFilter, + filters: rawFilters, } = ctx.input.body; + let { collectionId: legacyCollectionId } = ctx.input.body; const { offset, limit } = ctx.state.pagination; // always filter by the current team @@ -134,51 +233,26 @@ router.post( ], }; - // Exclude archived docs by default - if (!statusFilter) { - where[Op.and].push({ archivedAt: { [Op.eq]: null } }); - } - - // if a specific user is passed then add to filters. If the user doesn't - // exist in the team then nothing will be returned, so no need to check auth - if (createdById) { - where[Op.and].push({ createdById }); - } - - let documentIds: string[] = []; - - // if a specific collection is passed then we need to check auth to view it - if (collectionId) { - where[Op.and].push({ collectionId: [collectionId] }); - const collection = await Collection.findByPk(collectionId, { - userId: user.id, - includeDocumentStructure: sort === "index", - }); - - authorize(user, "readDocument", collection); - - // index sort is special because it uses the order of the documents in the - // collection.documentStructure rather than a database column - if (sort === "index") { - // Extract all document IDs from the collection structure. - documentIds = (collection.documentStructure || []) - .slice(offset, offset + limit) - .map((node) => node.id); - where[Op.and].push({ id: documentIds }); - } // if it's not a backlink request, filter by all collections the user has access to - } else if (!backlinkDocumentId) { - const collectionIds = await user.collectionIds(); - where[Op.and].push({ - collectionId: collectionIds, - }); - } + // Resolve the parent document being targeted from either the legacy + // top-level param or the filters DSL, so the membership escape below + // applies in both cases. `isNull` leaves resolve to undefined here + // (no specific parent to authorize against). + const normalizedFilter = combineFilters(rawFilters); + const parentDocumentId = + legacyParentDocumentId ?? + (normalizedFilter + ? extractTopLevelEqValue(normalizedFilter, "parentDocumentId") + : undefined); + // Membership escape: if the caller is filtering by a parent document they + // are a direct member of (or have group membership to), bypass the default + // collection access check. Mirrors the prior behavior of pushing then + // removing the legacy collectionId predicate. + let collectionScopeDropped = false; if (parentDocumentId) { const [groupMembership, membership] = await Promise.all([ GroupMembership.findOne({ - where: { - documentId: parentDocumentId, - }, + where: { documentId: parentDocumentId }, include: [ { model: Group, @@ -187,36 +261,76 @@ router.post( { model: GroupUser, required: true, - where: { - userId: user.id, - }, + where: { userId: user.id }, }, ], }, ], }), UserMembership.findOne({ - where: { - userId: user.id, - documentId: parentDocumentId, - }, + where: { userId: user.id, documentId: parentDocumentId }, }), ]); if (groupMembership || membership) { - remove(where[Op.and], (cond) => has(cond, "collectionId")); + collectionScopeDropped = true; + legacyCollectionId = undefined; } - - where[Op.and].push({ parentDocumentId }); } - // Explicitly passing 'null' as the parentDocumentId allows listing documents - // that have no parent document (aka they are at the root of the collection) - if (parentDocumentId === null) { + // The schema rejects callers that combine `filters` with the deprecated + // top-level params, so exactly one of these is set. + const filter = + normalizedFilter ?? + legacyParamsToFilter({ + userId: legacyUserId, + collectionId: legacyCollectionId, + parentDocumentId: legacyParentDocumentId, + }); + + // Exclude archived docs by default. Suppressed when the caller targets a + // specific status, or when their filter already references archivedAt. + const filterIncludesArchivedAt = + filter !== undefined && hasFieldInFilter(filter, "archivedAt"); + if (!statusFilter && !filterIncludesArchivedAt) { + where[Op.and].push({ archivedAt: { [Op.eq]: null } }); + } + + // Sort=index needs the collection's documentStructure for ordering and + // pagination. Only meaningful when the filter targets a single collection. + let documentIds: string[] = []; + const explicitCollectionId = + filter !== undefined + ? extractTopLevelEqValue(filter, "collectionId") + : undefined; + if (explicitCollectionId && sort === "index") { + const collection = await Collection.findByPk(explicitCollectionId, { + userId: user.id, + includeDocumentStructure: true, + }); + authorize(user, "readDocument", collection); + documentIds = (collection.documentStructure || []) + .slice(offset, offset + limit) + .map((node) => node.id); + where[Op.and].push({ id: documentIds }); + } + + // Apply filter and re-run authorize() for any auth-bearing fields. The + // public-API `documentId` field is renamed to the underlying `id` column; + // `userId` is handled inside `buildWhere` (maps to `collaboratorIds`). + if (filter) { + await authorizeFilterFields(user, filter); + const mapped = mapFilterFields(filter, { documentId: "id" }); + where[Op.and].push(buildWhere(mapped)); + } + + if (!backlinkDocumentId && !collectionScopeDropped) { + const collectionIds = await user.collectionIds(); where[Op.and].push({ - parentDocumentId: { - [Op.is]: null, - }, + [Op.or]: [ + { collectionId: collectionIds }, + { collectionId: null, createdById: user.id }, + ], }); } @@ -232,6 +346,23 @@ router.post( remove(where[Op.and], (cond) => has(cond, "collectionId")); } + // A filter referencing publishedAt can surface drafts (the replacement + // for the deprecated statusFilter=draft). Drafts are only ever visible to + // their creator or users with a direct membership — enforce that here, + // mirroring the legacy statusFilter path below. + const filterIncludesDrafts = + !statusFilter && + filter !== undefined && + hasFieldInFilter(filter, "publishedAt"); + if (filterIncludesDrafts) { + where[Op.and].push({ + [Op.or]: [ + { publishedAt: { [Op.ne]: null } }, + ...(await draftVisibilityClauses(user)), + ], + }); + } + const statusQuery = []; if (statusFilter?.includes(StatusFilter.Published)) { statusQuery.push({ @@ -249,19 +380,6 @@ router.post( } if (statusFilter?.includes(StatusFilter.Draft)) { - // Pre-fetch document IDs the user has a direct membership on so the - // filter can be expressed without referencing the (separately-loaded) - // memberships association, which would otherwise break the COUNT query. - const membershipDocumentIds = ( - await UserMembership.findAll({ - attributes: ["documentId"], - where: { - userId: user.id, - documentId: { [Op.ne]: null }, - }, - }) - ).map((m) => m.documentId as string); - statusQuery.push({ [Op.and]: [ { @@ -271,11 +389,7 @@ router.post( archivedAt: { [Op.eq]: null, }, - [Op.or]: [ - // Only ever include draft results for the user's own documents - { createdById: user.id }, - { id: membershipDocumentIds }, - ], + [Op.or]: await draftVisibilityClauses(user), }, ], }); @@ -311,7 +425,8 @@ router.post( : undefined : [[sort, direction]]; - const includeDrafts = !!statusFilter?.includes(StatusFilter.Draft); + const includeDrafts = + !!statusFilter?.includes(StatusFilter.Draft) || filterIncludesDrafts; // The withDrafts scope drops the defaultScope filters, so re-apply the // ones we still want — templates and trial-import documents should never @@ -1051,37 +1166,33 @@ router.post( rateLimiter(RateLimiterStrategy.OneHundredPerMinute), validate(T.DocumentsSearchTitlesSchema), async (ctx: APIContext) => { - const { - query, - statusFilter, - dateFilter, - collectionId, - userId, - sort, - direction, - } = ctx.input.body; + const { query, sort, direction, filters: rawFilters } = ctx.input.body; + const { collectionId, userId, documentId, statusFilter, dateFilter } = + ctx.input.body; const { offset, limit } = ctx.state.pagination; const { user } = ctx.state.auth; - let collaboratorIds = undefined; - - if (collectionId) { - const collection = await Collection.findByPk(collectionId, { - userId: user.id, + const filter = + combineFilters(rawFilters) ?? + legacyParamsToFilter({ + collectionId, + userId, + documentId, + statusFilter, + dateFilter, }); - authorize(user, "readDocument", collection); + + if (filter) { + await authorizeFilterFields(user, filter); } - if (userId) { - collaboratorIds = [userId]; - } + const resolvedFilter = filter + ? await expandDocumentIdLeaves(filter, { user }) + : undefined; const documents = await SearchProviderManager.getProvider().searchTitlesForUser(user, { query, - dateFilter, - statusFilter, - collectionId, - collaboratorIds, + filter: resolvedFilter, offset, limit, sort: sort as SortFilter, @@ -1107,17 +1218,24 @@ router.post( async (ctx: APIContext) => { const { query, - collectionId, - documentId, - userId, - dateFilter, - statusFilter = [], shareId, snippetMinWords, snippetMaxWords, sort, direction, + filters: rawFilters, } = ctx.input.body; + const { collectionId, documentId, userId, dateFilter, statusFilter } = + ctx.input.body; + const filter = + combineFilters(rawFilters) ?? + legacyParamsToFilter({ + collectionId, + userId, + documentId, + statusFilter, + dateFilter, + }); const { offset, limit } = ctx.state.pagination; const { user } = ctx.state.auth; @@ -1161,12 +1279,27 @@ router.post( const team = await share.$get("team"); invariant(team, "Share must belong to a team"); + const shareScopeId = collection?.id || document?.collectionId; + const shareFilter = combineFilters([ + ...(filter ? [filter] : []), + ...(shareScopeId + ? [ + { + field: "collectionId", + operator: "eq" as const, + value: shareScopeId, + }, + ] + : []), + ]); + const resolvedShareFilter = shareFilter + ? await expandDocumentIdLeaves(shareFilter, { teamId: share.teamId }) + : undefined; + response = await SearchProviderManager.getProvider().searchForTeam(team, { query, - collectionId: collection?.id || document?.collectionId, + filter: resolvedShareFilter, share, - dateFilter, - statusFilter, offset, limit, snippetMinWords, @@ -1182,38 +1315,17 @@ router.post( teamId = user.teamId; - if (collectionId) { - const collection = await Collection.findByPk(collectionId, { - userId: user.id, - }); - authorize(user, "readDocument", collection); + if (filter) { + await authorizeFilterFields(user, filter); } - let documentIds = undefined; - if (documentId) { - const document = await Document.findByPk(documentId, { - userId: user.id, - }); - authorize(user, "read", document); - documentIds = [ - documentId, - ...(await document.findAllChildDocumentIds()), - ]; - } - - let collaboratorIds = undefined; - - if (userId) { - collaboratorIds = [userId]; - } + const resolvedFilter = filter + ? await expandDocumentIdLeaves(filter, { user }) + : undefined; response = await SearchProviderManager.getProvider().searchForUser(user, { query, - collaboratorIds, - collectionId, - documentIds, - dateFilter, - statusFilter, + filter: resolvedFilter, offset, limit, snippetMinWords, diff --git a/server/routes/api/documents/schema.ts b/server/routes/api/documents/schema.ts index 2df81599bd..34930310d0 100644 --- a/server/routes/api/documents/schema.ts +++ b/server/routes/api/documents/schema.ts @@ -1,6 +1,7 @@ import type formidable from "formidable"; import { isEmpty } from "es-toolkit/compat"; import { z } from "zod"; +import { createFilterSchema } from "@shared/helpers/FilterHelper"; import { DirectionFilter, DocumentPermission, @@ -13,6 +14,30 @@ import { BaseSchema } from "@server/routes/api/schema"; import { zodIconType, zodIdType, zodShareIdType } from "@server/utils/zod"; import { ValidateColor } from "@server/validation"; +const documentFilterFields = { + createdAt: "date", + updatedAt: "date", + publishedAt: "date", + archivedAt: "date", + title: "string", + templateId: "uuid", + collectionId: "uuid", + // `userId` maps to the collaboratorIds array column and only supports + // membership checks. + userId: { kind: "uuid", operators: ["eq", "in"] }, + documentId: "uuid", + parentDocumentId: "uuid", +} as const; + +const documentListFilter = createFilterSchema(documentFilterFields); + +// On search endpoints `documentId` scopes results to a document subtree and is +// resolved by the route handler, which only supports `eq` and `in`. +const documentSearchFilter = createFilterSchema({ + ...documentFilterFields, + documentId: { kind: "uuid", operators: ["eq", "in"] }, +} as const); + const DocumentsSortParamsSchema = z.object({ /** Specifies the attributes by which documents will be sorted in the list */ sort: z @@ -37,7 +62,11 @@ const DocumentsSortParamsSchema = z.object({ }); const DateFilterSchema = z.object({ - /** Date filter */ + /** + * Date filter. + * @deprecated use `filters` with `updatedAt` and an ISO 8601 duration + * (`-P1D`, `-P1W`, `-P1M`, `-P1Y`) instead. + */ dateFilter: z .union([ z.literal("day"), @@ -49,16 +78,28 @@ const DateFilterSchema = z.object({ }); const BaseSearchSchema = DateFilterSchema.extend({ - /** Filter results for team based on the collection */ + /** + * Filter results for team based on the collection. + * @deprecated use `filters` with field `collectionId` instead. + */ collectionId: z.uuid().optional(), - /** Filter results based on user */ + /** + * Filter results based on user. + * @deprecated use `filters` with field `userId` instead. + */ userId: z.uuid().optional(), - /** Filter results based on content within a document and it's children */ + /** + * Filter results based on content within a document and it's children. + * @deprecated use `filters` with field `documentId` instead. + */ documentId: z.uuid().optional(), - /** Document statuses to include in results */ + /** + * Document statuses to include in results. + * @deprecated use `filters` with `archivedAt`/`publishedAt` instead. + */ statusFilter: z.enum(StatusFilter).array().optional(), /** Filter results for the team derived from shareId */ @@ -78,36 +119,75 @@ const BaseIdSchema = z.object({ export const DocumentsListSchema = BaseSchema.extend({ body: DocumentsSortParamsSchema.extend({ - /** Id of the user who created the doc */ + /** + * Id of a user who collaborated on the doc. + * @deprecated use `filters` with field `userId` instead. + */ userId: z.uuid().optional(), - /** Alias for userId - kept for backwards compatibility */ + /** + * Alias for userId - kept for backwards compatibility. + * @deprecated use `filters` with field `userId` instead. + */ user: z.uuid().optional(), - /** Id of the collection to which the document belongs */ + /** + * Id of the collection to which the document belongs. + * @deprecated use `filters` with field `collectionId` instead. + */ collectionId: z.uuid().optional(), - /** Alias for collectionId - kept for backwards compatibility */ + /** + * Alias for collectionId - kept for backwards compatibility. + * @deprecated use `filters` with field `collectionId` instead. + */ collection: z.uuid().optional(), /** Id of the backlinked document */ backlinkDocumentId: z.uuid().optional(), - /** Id of the parent document to which the document belongs */ + /** + * Id of the parent document to which the document belongs. + * @deprecated use `filters` with field `parentDocumentId` instead. + */ parentDocumentId: z.uuid().nullish(), - /** Document statuses to include in results */ + /** + * Document statuses to include in results. + * @deprecated use `filters` with `archivedAt`/`publishedAt` instead. + */ statusFilter: z.enum(StatusFilter).array().optional(), + + /** List of filter expressions. Implicit AND between top-level entries. */ + filters: documentListFilter.FilterListSchema.optional(), }), // Maintains backwards compatibility -}).transform((req) => { - req.body.collectionId = req.body.collectionId || req.body.collection; - req.body.userId = req.body.userId || req.body.user; - delete req.body.collection; - delete req.body.user; +}) + .transform((req) => { + req.body.collectionId = req.body.collectionId || req.body.collection; + req.body.userId = req.body.userId || req.body.user; + delete req.body.collection; + delete req.body.user; - return req; -}); + return req; + }) + .refine( + (req) => { + if (req.body.filters === undefined) { + return true; + } + return ( + req.body.userId === undefined && + req.body.collectionId === undefined && + req.body.parentDocumentId === undefined && + req.body.statusFilter === undefined + ); + }, + { + message: + "filters cannot be combined with deprecated parameters userId, collectionId, parentDocumentId, or statusFilter", + } + ); export type DocumentsListReq = z.infer; @@ -195,6 +275,26 @@ export const DocumentsRestoreSchema = BaseSchema.extend({ export type DocumentsRestoreReq = z.infer; +const filterIncompatibleWithLegacy = (req: { + body: { + filters?: unknown; + collectionId?: unknown; + userId?: unknown; + documentId?: unknown; + dateFilter?: unknown; + statusFilter?: unknown; + }; +}) => + req.body.filters === undefined || + (req.body.collectionId === undefined && + req.body.userId === undefined && + req.body.documentId === undefined && + req.body.dateFilter === undefined && + req.body.statusFilter === undefined); + +const filterIncompatibleWithLegacyMessage = + "filters cannot be combined with deprecated parameters collectionId, userId, documentId, dateFilter, or statusFilter"; + export const DocumentsSearchSchema = BaseSchema.extend({ body: BaseSearchSchema.extend({ /** Query for search */ @@ -207,7 +307,12 @@ export const DocumentsSearchSchema = BaseSchema.extend({ direction: z .enum(Object.values(DirectionFilter) as [string, ...string[]]) .optional(), + + /** List of filter expressions. Implicit AND between top-level entries. */ + filters: documentSearchFilter.FilterListSchema.optional(), }), +}).refine(filterIncompatibleWithLegacy, { + message: filterIncompatibleWithLegacyMessage, }); export type DocumentsSearchReq = z.infer; @@ -224,7 +329,12 @@ export const DocumentsSearchTitlesSchema = BaseSchema.extend({ direction: z .enum(Object.values(DirectionFilter) as [string, ...string[]]) .optional(), + + /** List of filter expressions. Implicit AND between top-level entries. */ + filters: documentSearchFilter.FilterListSchema.optional(), }), +}).refine(filterIncompatibleWithLegacy, { + message: filterIncompatibleWithLegacyMessage, }); export type DocumentsSearchTitlesReq = z.infer< diff --git a/server/routes/api/middlewares/apiErrorHandler.ts b/server/routes/api/middlewares/apiErrorHandler.ts index 0221f80e1c..0086dbaca4 100644 --- a/server/routes/api/middlewares/apiErrorHandler.ts +++ b/server/routes/api/middlewares/apiErrorHandler.ts @@ -2,6 +2,7 @@ import type { Context, Next } from "koa"; import { ValidationError as SequelizeValidationError, EmptyResultError as SequelizeEmptyResultError, + DatabaseError as SequelizeDatabaseError, } from "sequelize"; import { AuthorizationError, @@ -9,6 +10,23 @@ import { ValidationError, } from "@server/errors"; +/** Postgres codes for a requested date the database cannot represent. */ +const DATE_RANGE_ERROR_CODES = new Set(["22008", "22015"]); + +/** + * Reads the SQLSTATE code from the driver error a DatabaseError wraps. + * + * @param err the Sequelize error to inspect. + * @returns the SQLSTATE code, or undefined if the driver did not supply one. + */ +function sqlStateOf(err: SequelizeDatabaseError): string | undefined { + const { parent } = err; + if (parent && "code" in parent && typeof parent.code === "string") { + return parent.code; + } + return undefined; +} + export default function apiErrorHandler() { return async function apiErrorHandlerMiddleware(ctx: Context, next: Next) { try { @@ -34,6 +52,15 @@ export default function apiErrorHandler() { } } + if ( + err instanceof SequelizeDatabaseError && + DATE_RANGE_ERROR_CODES.has(sqlStateOf(err) ?? "") + ) { + transformedErr = ValidationError( + "Date value in request is out of range" + ); + } + if ( (err instanceof Error && "code" in err && err.code === "ENOENT") || err instanceof SequelizeEmptyResultError || diff --git a/server/routes/api/suggestions/suggestions.ts b/server/routes/api/suggestions/suggestions.ts index 36efba563e..d68d598fb5 100644 --- a/server/routes/api/suggestions/suggestions.ts +++ b/server/routes/api/suggestions/suggestions.ts @@ -1,7 +1,6 @@ import Router from "koa-router"; import { Op } from "sequelize"; import { Sequelize } from "sequelize-typescript"; -import { StatusFilter } from "@shared/types"; import auth from "@server/middlewares/authentication"; import validate from "@server/middlewares/validate"; import { Group, User } from "@server/models"; @@ -82,7 +81,13 @@ router.post( query, offset, limit, - statusFilter: [StatusFilter.Published], + filter: { + operator: "AND", + filters: [ + { field: "archivedAt", operator: "isNull" }, + { field: "publishedAt", operator: "isNotNull" }, + ], + }, }), suggestUsers(), can(actor, "listGroups", actor.team) diff --git a/server/tools/documents.ts b/server/tools/documents.ts index 0b69913e4a..626872a3c1 100644 --- a/server/tools/documents.ts +++ b/server/tools/documents.ts @@ -34,7 +34,8 @@ import { withTracing, } from "./util"; import { ValidationError } from "@server/errors"; -import { StatusFilter, TextEditMode } from "@shared/types"; +import { TextEditMode } from "@shared/types"; +import type { Filter } from "@shared/helpers/FilterHelper"; import SearchProviderManager from "@server/utils/SearchProviderManager"; /** @@ -149,7 +150,13 @@ export function documentTools(server: McpServer, scopes: string[]) { user, { query, - collectionId, + filter: collectionId + ? { + field: "collectionId", + operator: "eq", + value: collectionId, + } + : undefined, offset: effectiveOffset, limit: effectiveLimit, } @@ -233,11 +240,21 @@ export function documentTools(server: McpServer, scopes: string[]) { // List recent documents via the search provider (with no query) so // access control matches the search path exactly. const searchProvider = SearchProviderManager.getProvider(); + const filters: Filter[] = [ + { field: "archivedAt", operator: "isNull" }, + { field: "publishedAt", operator: "isNotNull" }, + ]; + if (collectionId) { + filters.push({ + field: "collectionId", + operator: "eq", + value: collectionId, + }); + } const { results } = await searchProvider.searchForUser(user, { - collectionId, + filter: { operator: "AND", filters }, offset: effectiveOffset, limit: effectiveLimit, - statusFilter: [StatusFilter.Published], }); const documents = results.map((result) => result.document); diff --git a/server/utils/BaseSearchProvider.ts b/server/utils/BaseSearchProvider.ts index 8a2ef5365a..e7f6623afd 100644 --- a/server/utils/BaseSearchProvider.ts +++ b/server/utils/BaseSearchProvider.ts @@ -1,6 +1,6 @@ -import type { DateFilter } from "@shared/types"; +import type { Filter } from "@shared/helpers/FilterHelper"; import type { SearchableModel } from "@shared/types"; -import type { DirectionFilter, SortFilter, StatusFilter } from "@shared/types"; +import type { DirectionFilter, SortFilter } from "@shared/types"; import type Collection from "@server/models/Collection"; import type Comment from "@server/models/Comment"; import type Document from "@server/models/Document"; @@ -28,18 +28,14 @@ export interface SearchOptions { offset?: number; /** The text to search for. */ query?: string; - /** Limit results to a collection. Authorization is presumed to have been done before passing to this provider. */ - collectionId?: string | null; + /** + * A filter expression scoping results. Authorization for any auth-bearing + * fields (e.g. collectionId) is presumed to have been done before reaching + * the provider. + */ + filter?: Filter; /** Limit results to a shared document. */ share?: Share; - /** Limit results to a date range. */ - dateFilter?: DateFilter; - /** Status of the documents to return. */ - statusFilter?: StatusFilter[]; - /** Limit results to a list of documents. */ - documentIds?: string[]; - /** Limit results to a list of users that collaborated on the document. */ - collaboratorIds?: string[]; /** The minimum number of words to be returned in the contextual snippet. */ snippetMinWords?: number; /** The maximum number of words to be returned in the contextual snippet. */ diff --git a/server/validation.test.ts b/server/validation.test.ts index f778907d09..73e385819f 100644 --- a/server/validation.test.ts +++ b/server/validation.test.ts @@ -1,6 +1,6 @@ import { randomUUID } from "node:crypto"; import { Buckets } from "./models/helpers/AttachmentHelper"; -import { ValidateKey } from "./validation"; +import { ValidateKey, isISO8601Duration } from "./validation"; describe("#ValidateKey.isValid", () => { it("should return false if number of key components is incorrect", () => { @@ -69,6 +69,106 @@ describe("#ValidateKey.sanitize", () => { }); }); +describe("#isISO8601Duration", () => { + describe("valid cases", () => { + it.each([ + "P1Y", + "P1M", + "P1D", + "P1W", + "P52W", + "P0D", + "P10Y", + "P365D", + "PT1H", + "PT30M", + "PT45S", + "PT1H30M", + "PT1H30M45S", + "PT24H", + "PT1500S", + "PT0S", + "P1Y2M", + "P1Y2M3D", + "P2M3D", + "P1DT12H", + "P1Y2M3DT4H5M6S", + "-P1D", + "-P7D", + "-PT1H", + "-P1Y2M3DT4H5M6S", + "-P1W", + ])("accepts %s", (value) => { + expect(isISO8601Duration(value)).toBe(true); + }); + }); + + describe("invalid cases", () => { + it.each([ + // Missing prefix + "1D", + "T1H", + "Y1", + // Empty / lone prefix + "", + "P", + "PT", + "-P", + "-PT", + // Missing number + "PD", + "PMW", + "PT H", + // Missing unit + "P1", + "PT1", + "P1Y2", + // Unknown unit + "P1Z", + "P1X", + "PT1Q", + // Wrong section (date vs time) + "P1H", + "PT1Y", + "PT1D", + // Trailing T + "P1DT", + "P1YT", + // Weeks combined with other units + "P1W1D", + "P1Y1W", + // Decimals + "P1.5D", + "P0.5W", + "PT1.5H", + // Sign in wrong place + "P-1D", + "PT-1H", + "--P1D", + "+P1D", + // Whitespace + "P 1D", + "P1D ", + " P1D", + "- P1D", + // Lowercase + "p1d", + "P1d", + "pt1h", + // Quotes / SQL metacharacters + "P1D'", + "P1D; DROP TABLE", + "P1D--", + "P1D OR 1=1", + // Order swap + "P1D1Y", + "P1M1Y", + ])("rejects %j", (value) => { + expect(isISO8601Duration(value)).toBe(false); + }); + }); +}); + describe("#ValidateKey.sanitizeSegment", () => { it("should leave an ordinary name untouched", () => { expect(ValidateKey.sanitizeSegment("My Document")).toEqual("My Document"); diff --git a/server/validation.ts b/server/validation.ts index 9d0c8ff978..0e208a0394 100644 --- a/server/validation.ts +++ b/server/validation.ts @@ -13,6 +13,8 @@ import { isUrl } from "@shared/utils/urls"; import { ParamRequiredError, ValidationError } from "./errors"; import { Buckets } from "./models/helpers/AttachmentHelper"; +export { isISO8601Duration } from "@shared/utils/date"; + type IncomingValue = Primitive | string[]; export const assertPresent = (value: IncomingValue, message: string) => { diff --git a/shared/helpers/FilterHelper.test.ts b/shared/helpers/FilterHelper.test.ts new file mode 100644 index 0000000000..242127453b --- /dev/null +++ b/shared/helpers/FilterHelper.test.ts @@ -0,0 +1,290 @@ +import { FilterValidation } from "../validations"; +import type { Filter } from "./FilterHelper"; +import { createFilterSchema } from "./FilterHelper"; + +const { FilterSchema, FilterListSchema } = createFilterSchema({ + createdAt: "date", + title: "string", + collectionId: "uuid", + views: "number", + isDraft: "boolean", +} as const); + +const uuid = "00000000-0000-4000-8000-000000000000"; + +const leaf: Filter = { field: "title", operator: "eq", value: "x" }; + +/** Build a flat OR group that holds `count` leaves, for a total of count + 1 nodes. */ +function groupOf(count: number): Filter { + return { + operator: "OR", + filters: Array.from({ length: count }, () => leaf), + }; +} + +describe("createFilterSchema value validation", () => { + describe("uuid fields", () => { + it("accepts a valid uuid", () => { + expect( + FilterSchema.safeParse({ + field: "collectionId", + operator: "eq", + value: uuid, + }).success + ).toBe(true); + }); + + it("rejects a non-uuid value", () => { + expect( + FilterSchema.safeParse({ + field: "collectionId", + operator: "eq", + value: "garbage", + }).success + ).toBe(false); + }); + + it("validates every entry of an `in` array", () => { + expect( + FilterSchema.safeParse({ + field: "collectionId", + operator: "in", + value: [uuid, "garbage"], + }).success + ).toBe(false); + + expect( + FilterSchema.safeParse({ + field: "collectionId", + operator: "in", + value: [uuid], + }).success + ).toBe(true); + }); + + it("rejects pattern-matching operators on non-text fields", () => { + expect( + FilterSchema.safeParse({ + field: "collectionId", + operator: "contains", + value: uuid, + }).success + ).toBe(false); + }); + }); + + describe("date fields", () => { + it("accepts an ISO date", () => { + expect( + FilterSchema.safeParse({ + field: "createdAt", + operator: "gt", + value: "2024-01-01T00:00:00.000Z", + }).success + ).toBe(true); + }); + + it("accepts a bare ISO date", () => { + expect( + FilterSchema.safeParse({ + field: "createdAt", + operator: "gt", + value: "2024-01-01", + }).success + ).toBe(true); + }); + + it("rejects an unparseable date", () => { + expect( + FilterSchema.safeParse({ + field: "createdAt", + operator: "gt", + value: "notadate", + }).success + ).toBe(false); + }); + + it("accepts an ISO 8601 duration for range operators", () => { + expect( + FilterSchema.safeParse({ + field: "createdAt", + operator: "gte", + value: "-P7D", + }).success + ).toBe(true); + }); + + it("rejects an ISO 8601 duration for equality operators", () => { + expect( + FilterSchema.safeParse({ + field: "createdAt", + operator: "eq", + value: "-P7D", + }).success + ).toBe(false); + }); + }); + + describe("string fields", () => { + it("accepts a string value and pattern operators", () => { + expect( + FilterSchema.safeParse({ + field: "title", + operator: "contains", + value: "hello", + }).success + ).toBe(true); + }); + + it("rejects a non-string value", () => { + expect( + FilterSchema.safeParse({ + field: "title", + operator: "eq", + value: 5, + }).success + ).toBe(false); + }); + }); + + describe("number and boolean fields", () => { + it("validates number values", () => { + expect( + FilterSchema.safeParse({ + field: "views", + operator: "eq", + value: 5, + }).success + ).toBe(true); + expect( + FilterSchema.safeParse({ + field: "views", + operator: "eq", + value: "5", + }).success + ).toBe(false); + }); + + it("validates boolean values", () => { + expect( + FilterSchema.safeParse({ + field: "isDraft", + operator: "eq", + value: true, + }).success + ).toBe(true); + expect( + FilterSchema.safeParse({ + field: "isDraft", + operator: "eq", + value: "true", + }).success + ).toBe(false); + }); + }); + + it("still allows null operators with no value", () => { + expect( + FilterSchema.safeParse({ + field: "createdAt", + operator: "isNull", + }).success + ).toBe(true); + }); +}); + +describe("createFilterSchema operator allowlists", () => { + const { FilterSchema: RestrictedSchema } = createFilterSchema({ + userId: { kind: "uuid", operators: ["eq", "in"] }, + title: "string", + } as const); + + it("accepts an allowed operator", () => { + expect( + RestrictedSchema.safeParse({ + field: "userId", + operator: "eq", + value: uuid, + }).success + ).toBe(true); + expect( + RestrictedSchema.safeParse({ + field: "userId", + operator: "in", + value: [uuid], + }).success + ).toBe(true); + }); + + it("rejects operators outside the allowlist", () => { + for (const operator of ["neq", "notIn", "isNull", "isNotNull", "lt"]) { + const result = RestrictedSchema.safeParse({ + field: "userId", + operator, + ...(operator === "isNull" || operator === "isNotNull" + ? {} + : { value: operator === "notIn" ? [uuid] : uuid }), + }); + expect(result.success).toBe(false); + } + }); + + it("does not restrict fields without an allowlist", () => { + expect( + RestrictedSchema.safeParse({ + field: "title", + operator: "neq", + value: "x", + }).success + ).toBe(true); + }); + + it("rejects a disallowed operator nested inside a group", () => { + expect( + RestrictedSchema.safeParse({ + operator: "OR", + filters: [ + { field: "title", operator: "eq", value: "x" }, + { field: "userId", operator: "neq", value: uuid }, + ], + }).success + ).toBe(false); + }); +}); + +describe("createFilterSchema node limit", () => { + const { maxNodes } = FilterValidation; + + it("accepts an expression at the node limit", () => { + expect(FilterSchema.safeParse(groupOf(maxNodes - 1)).success).toBe(true); + }); + + it("rejects an expression over the node limit", () => { + expect(FilterSchema.safeParse(groupOf(maxNodes)).success).toBe(false); + }); + + it("rejects a wide expression that stays inside the depth limit", () => { + // Depth 3 and 7 filters per group is well inside both shape limits, yet + // holds 57 nodes. + const wide: Filter = { + operator: "OR", + filters: Array.from({ length: 7 }, () => groupOf(7)), + }; + expect(FilterSchema.safeParse(wide).success).toBe(false); + }); + + it("accepts a list at the node limit", () => { + const filters = Array.from({ length: maxNodes }, () => leaf); + expect(FilterListSchema.safeParse(filters).success).toBe(true); + }); + + it("rejects a list whose entries total over the node limit", () => { + // Each entry is inside the per-expression limit; the sum is not. + const filters = Array.from({ length: 5 }, () => groupOf(10)); + expect(FilterListSchema.safeParse(filters).success).toBe(false); + }); + + it("rejects an empty list", () => { + expect(FilterListSchema.safeParse([]).success).toBe(false); + }); +}); diff --git a/shared/helpers/FilterHelper.ts b/shared/helpers/FilterHelper.ts new file mode 100644 index 0000000000..8bda227adc --- /dev/null +++ b/shared/helpers/FilterHelper.ts @@ -0,0 +1,322 @@ +import { z } from "zod"; +import { isISO8601Duration } from "../utils/date"; +import { FilterValidation } from "../validations"; + +export const ComparisonOperator = z.enum([ + "eq", + "neq", + "lt", + "lte", + "gt", + "gte", + "contains", + "startsWith", + "endsWith", + "containsStrict", + "startsWithStrict", + "endsWithStrict", + "in", + "notIn", + "isNull", + "isNotNull", +]); +export type ComparisonOperator = z.infer; + +export const LogicalOperator = z.enum(["AND", "OR"]); +export type LogicalOperator = z.infer; + +export const FilterValue = z.union([ + z.string(), + z.number(), + z.boolean(), + z.date(), + z.array(z.string()), + z.array(z.number()), +]); +export type FilterValue = z.infer; + +export interface FilterCondition { + field: F; + operator: ComparisonOperator; + value?: FilterValue; +} + +export interface FilterGroup { + operator: LogicalOperator; + filters: Array | FilterGroup>; +} + +export type Filter = + | FilterCondition + | FilterGroup; + +/** The column type a filterable field maps to, used to validate values. */ +export type FieldKind = "uuid" | "string" | "number" | "boolean" | "date"; + +/** + * A filterable field definition: either just its column type, or an object + * that additionally restricts which operators the field supports. + */ +export type FieldSpec = + | FieldKind + | { kind: FieldKind; operators: readonly ComparisonOperator[] }; + +const uuidSchema = z.uuid(); + +// Accept a full ISO 8601 datetime (with `Z` or an offset) or a bare ISO date. +const dateSchema = z.union([z.iso.datetime({ offset: true }), z.iso.date()]); + +/** Operators for which range comparisons (and relative durations) apply. */ +export const RANGE_OPERATORS = new Set([ + "gt", + "gte", + "lt", + "lte", +]); + +/** + * Check whether a single scalar value is compatible with a field's column type. + * + * @param kind the field's column type. + * @param value the candidate value. + * @param operator the operator the value is used with. + * @returns true if the value is a valid input for the field. + */ +function scalarMatchesKind( + kind: FieldKind, + value: unknown, + operator: ComparisonOperator +): boolean { + switch (kind) { + case "uuid": + return uuidSchema.safeParse(value).success; + case "string": + return typeof value === "string"; + case "number": + return typeof value === "number"; + case "boolean": + return typeof value === "boolean"; + case "date": + if (typeof value !== "string") { + return false; + } + if (RANGE_OPERATORS.has(operator) && isISO8601Duration(value)) { + return true; + } + return dateSchema.safeParse(value).success; + default: + return false; + } +} + +function isGroup(filter: Filter): filter is FilterGroup { + return "filters" in filter; +} + +function depthOf(filter: Filter): number { + if (isGroup(filter)) { + return 1 + Math.max(...filter.filters.map(depthOf)); + } + return 1; +} + +function countNodes(filter: Filter): number { + if (isGroup(filter)) { + return filter.filters.reduce((total, f) => total + countNodes(f), 1); + } + return 1; +} + +/** + * Build a zod schema for a typed filter DSL constrained to a field allowlist. + * + * Each field maps to a column type ({@link FieldKind}) so that values are + * validated against the field at the input layer, returning a clean 400 rather + * than letting malformed input (e.g. a non-uuid id, an invalid date) reach the + * database. A field may also restrict its supported operators + * ({@link FieldSpec}) so that combinations the query layer cannot execute are + * rejected here as well. + * + * @param fields map of allowed field name to its column type, optionally with a restricted operator set. + * @returns FilterSchema for a single expression, and FilterListSchema for the wire-level `filters` array. + */ +export function createFilterSchema>( + fields: S +) { + const FieldEnum = z.enum( + Object.keys(fields) as [ + Extract, + ...Extract[], + ] + ); + + const FilterConditionSchema = z + .object({ + field: FieldEnum, + operator: ComparisonOperator, + value: FilterValue.optional(), + }) + .superRefine((data, ctx) => { + const { field, operator, value } = data; + const spec: FieldSpec = fields[field]; + const kind = typeof spec === "string" ? spec : spec.kind; + const allowedOperators = + typeof spec === "string" ? undefined : spec.operators; + + if (allowedOperators && !allowedOperators.includes(operator)) { + ctx.addIssue({ + code: "custom", + message: `operator '${operator}' is not supported for field '${field}'`, + path: ["operator"], + }); + return; + } + + const isArrayOp = operator === "in" || operator === "notIn"; + const isNullOp = operator === "isNull" || operator === "isNotNull"; + const isStringOp = + operator === "contains" || + operator === "startsWith" || + operator === "endsWith" || + operator === "containsStrict" || + operator === "startsWithStrict" || + operator === "endsWithStrict"; + + if (isNullOp) { + if (value !== undefined) { + ctx.addIssue({ + code: "custom", + message: `value must not be provided for operator '${operator}'`, + path: ["value"], + }); + } + return; + } + + if (value === undefined) { + ctx.addIssue({ + code: "custom", + message: `value is required for operator '${operator}'`, + path: ["value"], + }); + return; + } + + if (isArrayOp) { + if (!Array.isArray(value) || value.length === 0) { + ctx.addIssue({ + code: "custom", + message: `value must be a non-empty array for operator '${operator}'`, + path: ["value"], + }); + return; + } + if (value.length > FilterValidation.maxInValues) { + ctx.addIssue({ + code: "custom", + message: `value must contain at most ${FilterValidation.maxInValues} entries for operator '${operator}'`, + path: ["value"], + }); + } + if (value.some((entry) => !scalarMatchesKind(kind, entry, operator))) { + ctx.addIssue({ + code: "custom", + message: `value must contain only valid ${kind} entries for field '${field}'`, + path: ["value"], + }); + } + return; + } + + if (Array.isArray(value)) { + ctx.addIssue({ + code: "custom", + message: `value must not be an array for operator '${operator}'`, + path: ["value"], + }); + return; + } + + if (isStringOp) { + if (typeof value !== "string") { + ctx.addIssue({ + code: "custom", + message: `value must be a string for operator '${operator}'`, + path: ["value"], + }); + return; + } + // Pattern matching (iLike/like) only applies to text columns; running + // it against a uuid/date/etc. column would error at the database. + if (kind !== "string") { + ctx.addIssue({ + code: "custom", + message: `operator '${operator}' is only valid for text fields, not field '${field}'`, + path: ["operator"], + }); + } + return; + } + + if (!scalarMatchesKind(kind, value, operator)) { + ctx.addIssue({ + code: "custom", + message: `value must be a valid ${kind} for field '${field}'`, + path: ["value"], + }); + } + }); + + type Condition = z.infer; + type Group = { + operator: LogicalOperator; + filters: Array; + }; + + const FilterGroupSchema: z.ZodType = z.lazy(() => + z.object({ + operator: LogicalOperator, + filters: z + .array(z.union([FilterConditionSchema, FilterGroupSchema])) + .min(1) + .max(FilterValidation.maxNodes), + }) + ); + + const FilterSchema = z + .union([FilterConditionSchema, FilterGroupSchema]) + .superRefine((data, ctx) => { + const filter = data as Filter; + if (depthOf(filter) > FilterValidation.maxDepth) { + ctx.addIssue({ + code: "custom", + message: `filter nesting depth exceeds maximum of ${FilterValidation.maxDepth}`, + }); + } + if (countNodes(filter) > FilterValidation.maxNodes) { + ctx.addIssue({ + code: "custom", + message: `filter contains more than the maximum of ${FilterValidation.maxNodes} conditions`, + }); + } + }); + + const FilterListSchema = z + .array(FilterSchema) + .min(1) + .max(FilterValidation.maxNodes) + .superRefine((filters, ctx) => { + const total = filters.reduce( + (sum, filter) => sum + countNodes(filter as Filter), + 0 + ); + if (total > FilterValidation.maxNodes) { + ctx.addIssue({ + code: "custom", + message: `filters contain more than the maximum of ${FilterValidation.maxNodes} conditions`, + }); + } + }); + + return { FilterSchema, FilterListSchema }; +} diff --git a/shared/utils/date.ts b/shared/utils/date.ts index 30ea543517..79f6fbf993 100644 --- a/shared/utils/date.ts +++ b/shared/utils/date.ts @@ -140,6 +140,38 @@ export function parseDate(dateStr: string): Date | null { return null; } +const ISO8601_DURATION_RE = + /^-?P(?:(\d+W)|((?:\d+Y)?(?:\d+M)?(?:\d+D)?)(T(?:\d+H)?(?:\d+M)?(?:\d+S)?)?)$/; + +/** + * Validate a string against the ISO 8601 duration format. + * + * Supported subset: an optional leading `-`, then `P[nY][nM][nW][nD][T[nH][nM][nS]]`. + * The weeks form (`PnW`) is mutually exclusive with year/month/day units. + * Decimals are not supported. + * + * @param value the candidate string. + * @returns true if the string is a syntactically valid ISO 8601 duration. + */ +export function isISO8601Duration(value: string): boolean { + const m = ISO8601_DURATION_RE.exec(value); + if (!m) { + return false; + } + const [, weeks, date, time] = m; + if (weeks) { + return true; + } + // A bare `T` separator with no following time unit is invalid even if a date + // portion is present (e.g. `P1DT` should be rejected). + if (time === "T") { + return false; + } + const hasDate = !!date && date.length > 0; + const hasTime = !!time && time.length > 1; + return hasDate || hasTime; +} + export function subtractDate(date: Date, period: DateFilter) { switch (period) { case "day": diff --git a/shared/validations.ts b/shared/validations.ts index 1dbe024386..31e99421f8 100644 --- a/shared/validations.ts +++ b/shared/validations.ts @@ -176,6 +176,17 @@ export const WebhookSubscriptionValidation = { maxUrlLength: 1024, }; +export const FilterValidation = { + /** The maximum nesting depth of a filter expression */ + maxDepth: 5, + + /** The maximum number of values in an `in` / `notIn` array */ + maxInValues: 100, + + /** The maximum number of conditions and groups a filter may contain */ + maxNodes: 50, +}; + export const EmojiValidation = { /** The maximum length of the emoji name */ maxNameLength: 25,