From bb998388019867000188e0deac4c43ea11d10088 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Tue, 1 Dec 2026 01:03:28 -0800 Subject: [PATCH] feat(gitlab): filter GitLab search by person through their verified email --- apps/sim/connectors/gitlab/permissions.ts | 23 +- .../gitlab-federated.integration.ts | 18 +- apps/sim/lib/knowledge/access/tokens.ts | 5 + .../lib/sim-search/live/gitlab-admin.test.ts | 26 +- apps/sim/lib/sim-search/live/gitlab-admin.ts | 91 +++-- apps/sim/lib/sim-search/live/gitlab.test.ts | 151 +++++++- apps/sim/lib/sim-search/live/gitlab.ts | 324 ++++++++++++++++-- apps/sim/lib/sim-search/live/providers.ts | 2 + 8 files changed, 583 insertions(+), 57 deletions(-) diff --git a/apps/sim/connectors/gitlab/permissions.ts b/apps/sim/connectors/gitlab/permissions.ts index d9de62c27f8..43112b3dc86 100644 --- a/apps/sim/connectors/gitlab/permissions.ts +++ b/apps/sim/connectors/gitlab/permissions.ts @@ -405,15 +405,25 @@ async function listAll(url: string, token: string, signal?: AbortSignal): Pro return items } -function verifiedEmail(person: GitLabPermissionUser): string | null { +/** + * A GitLab user's primary email when it identifies them: an active, unlocked user who confirmed + * it. An administrator token sees this email; a public profile email proves nothing. + */ +export function verifiedGitLabEmail(person: { + state?: unknown + locked?: unknown + confirmed_at?: unknown + email?: unknown +}): string | null { if ( person.state !== 'active' || person.locked === true || typeof person.confirmed_at !== 'string' || - !Number.isFinite(Date.parse(person.confirmed_at)) + !Number.isFinite(Date.parse(person.confirmed_at)) || + typeof person.email !== 'string' ) return null - return userToken(person.email) ? normalizeEmail(person.email as string) : null + return userToken(person.email) ? normalizeEmail(person.email) : null } function activeRole(member: GitLabPermissionMember | undefined, now: Date): number { @@ -452,7 +462,7 @@ export function gitLabFeatureAudience( : null const emails = new Set() for (const person of users) { - const email = verifiedEmail(person) + const email = verifiedGitLabEmail(person) if (!email) continue if (repositoryAudience && !repositoryAudience.has(email)) continue const role = roles.get(person.id) ?? 0 @@ -673,7 +683,8 @@ export async function getGitLabDocumentAcls( result[doc.externalId] = state.policy.implicitAdmin ? sortAccessTokens( state.users.flatMap((person) => { - const grant = person.is_admin === true ? userToken(verifiedEmail(person)) : null + const grant = + person.is_admin === true ? userToken(verifiedGitLabEmail(person)) : null return grant ? [grant] : [] }) ) @@ -699,7 +710,7 @@ export async function getGitLabDocumentAcls( if (typeof authorId === 'number') ids.add(authorId) for (const id of ids) { const person = users.get(id) - const email = person ? verifiedEmail(person) : null + const email = person ? verifiedGitLabEmail(person) : null const grant = userToken(email) if (grant && email && issueAudience.has(email)) acl.push(grant) } diff --git a/apps/sim/lib/knowledge/__integration__/gitlab-federated.integration.ts b/apps/sim/lib/knowledge/__integration__/gitlab-federated.integration.ts index 35d1dfff5fa..a435de73e21 100644 --- a/apps/sim/lib/knowledge/__integration__/gitlab-federated.integration.ts +++ b/apps/sim/lib/knowledge/__integration__/gitlab-federated.integration.ts @@ -103,13 +103,15 @@ describe.skipIf(!fixtureFile)('federated self-hosted GitLab Search', () => { function search( person: FixturePerson, - kind: 'issues' | 'code' | 'wiki' | 'merge_requests' | 'commits' + kind: 'issues' | 'code' | 'wiki' | 'merge_requests' | 'commits', + involving?: string ) { return searchLiveKnowledge.execute({ principal: principal(person), input: { organizationId: ids.organizationId, query: QUERY, + ...(involving ? { involving } : {}), topK: 20, filters: { source: 'gitlab' }, nativeQueries: [ @@ -237,10 +239,13 @@ describe.skipIf(!fixtureFile)('federated self-hosted GitLab Search', () => { content: `${QUERY} wiki content.`, format: 'markdown', }) + const assignee = people.reporter + if (!assignee) throw new Error('Expected the reporter fixture') issueIid = ( await api<{ iid: number }>(`/projects/${projectId}/issues`, 'POST', { title: `${QUERY} normal issue`, description: `${QUERY} normal issue body.`, + assignee_ids: [assignee.id], }) ).iid confidentialIid = ( @@ -353,6 +358,17 @@ describe.skipIf(!fixtureFile)('federated self-hosted GitLab Search', () => { expect(content).not.toContain('security review') }, 120_000) + it('filters issues to the person by their verified email', async () => { + const reporter = people.reporter + const guest = people.guest + if (!reporter || !guest) throw new Error('Expected the person fixtures') + const assigned = await search(reporter, 'issues', reporter.email) + expect(assigned.results.map((row) => decodeLiveReference(row.documentId).id)).toEqual([ + String(issueIid), + ]) + expect((await search(reporter, 'issues', guest.email)).results).toEqual([]) + }, 120_000) + it('keeps references reader-bound and rechecks confidentiality before reads', async () => { const reporter = await search(people.reporter!, 'code') const file = reporter.results[0]! diff --git a/apps/sim/lib/knowledge/access/tokens.ts b/apps/sim/lib/knowledge/access/tokens.ts index 59fc8e89f4c..915daa4bee5 100644 --- a/apps/sim/lib/knowledge/access/tokens.ts +++ b/apps/sim/lib/knowledge/access/tokens.ts @@ -159,6 +159,11 @@ export function userToken(email: string | null | undefined): string | null { return isAccessToken(token) ? token : null } +/** The email a {@link userToken} names, or null for any other token. */ +export function userTokenEmail(token: string): string | null { + return token.startsWith('u:') && isAccessToken(token) ? token.slice('u:'.length) : null +} + export interface GroupIdentity { providerId: string /** The provider's tenant, or {@link NO_TENANT_SEGMENT} where it reports none. */ diff --git a/apps/sim/lib/sim-search/live/gitlab-admin.test.ts b/apps/sim/lib/sim-search/live/gitlab-admin.test.ts index 73487bc0ccc..3af5e171920 100644 --- a/apps/sim/lib/sim-search/live/gitlab-admin.test.ts +++ b/apps/sim/lib/sim-search/live/gitlab-admin.test.ts @@ -34,7 +34,8 @@ vi.mock('@/lib/knowledge/connectors/permission-store', () => ({ hasConnectorPermissionGrant: mocks.grant, readConnectorPermissionMetadata: mocks.metadata, })) -vi.mock('@/connectors/gitlab/permissions', () => ({ +vi.mock('@/connectors/gitlab/permissions', async (importOriginal) => ({ + ...(await importOriginal()), openGitLabDirectory: mocks.directory, getGitLabDocumentAcls: mocks.acl, validateGitLabCsvToken: mocks.csv, @@ -266,6 +267,29 @@ describe('administrator-managed live GitLab authorization', () => { 'wiki', ]) }) + it('filters by the viewer’s own verified email for involving me, never the source’s account', async () => { + const current = await session() + const paths: string[] = [] + client.json.mockImplementation( + async (path: string, options?: { query?: { search?: string } }) => { + paths.push(path) + if (path === '/api/v4/users') + return options?.query?.search === 'reader@example.com' + ? [{ id: 5, email: 'reader@example.com', state: 'active', confirmed_at: '2026-01-01' }] + : [] + if (path === '/api/v4/users/5/emails') return [] + return project + } + ) + await current.search({ query: 'fix', limit: 10, scopes: [], involving: 'me' }) + expect(paths).not.toContain('/api/v4/user') + expect( + mocks.search.mock.calls.map(([, input, scope]) => [input.native.kind, scope.person]) + ).toEqual([ + ['issues', { id: 5, emails: ['reader@example.com'] }], + ['merge_requests', { id: 5, emails: ['reader@example.com'] }], + ]) + }) it('propagates the caller deadline into the canonical permission directory', async () => { await session() expect(mocks.directory).toHaveBeenCalledWith( diff --git a/apps/sim/lib/sim-search/live/gitlab-admin.ts b/apps/sim/lib/sim-search/live/gitlab-admin.ts index ab3b7239594..cf3ec4ab20c 100644 --- a/apps/sim/lib/sim-search/live/gitlab-admin.ts +++ b/apps/sim/lib/sim-search/live/gitlab-admin.ts @@ -9,7 +9,7 @@ import { decryptApiKey } from '@/lib/api-key/crypto' import { type ResourceOwner, resourceScopeFromOwner } from '@/lib/core/resource-scope' import { resourceScopeCondition } from '@/lib/core/resource-scope.server' import { createUserKnowledgeAccessProvider } from '@/lib/knowledge/access/scope' -import { groupToken } from '@/lib/knowledge/access/tokens' +import { groupToken, userTokenEmail } from '@/lib/knowledge/access/tokens' import { connectorsGrantingSubject, hasConnectorPermissionGrant, @@ -19,11 +19,15 @@ import { import { searchIntegrationAccessCondition } from '@/lib/knowledge/search/integration-policy' import { dateSortDirection, hasDateBounds } from '@/lib/sim-search/live/dates' import { + GITLAB_AUTHORED_KINDS, GITLAB_OPT_IN_KINDS, type GitLabCodeScope, + type GitLabPerson, gitLabDocumentUrl, gitLabProjectPath, + isGitLabMergedCursor, readGitLab, + resolveGitLabPerson, searchGitLab, } from '@/lib/sim-search/live/gitlab' import { @@ -174,13 +178,37 @@ export async function resolveAdminGitLabAccount(owner: ResourceOwner, account: L type Reference = Pick type AdminSource = { id: string; config: Record } -/** The source's kinds a search covers: the one it names, or all but the opt-in kinds. */ -function defaultKinds(kinds: GitLabSearchKind[], requested?: string): GitLabSearchKind[] { - return kinds.filter((kind) => - requested ? kind === requested : !GITLAB_OPT_IN_KINDS.includes(kind) +/** + * The source's kinds a search covers: the one it names, or all but the opt-in kinds, and for a + * person filter only the kinds whose items have an author. + */ +function defaultKinds( + kinds: GitLabSearchKind[], + search: Pick +): GitLabSearchKind[] { + const requested = search.native?.kind + if (requested) return kinds.filter((kind) => kind === requested) + return kinds.filter( + (kind) => + !GITLAB_OPT_IN_KINDS.includes(kind) && (!search.involving || GITLAB_AUTHORED_KINDS.has(kind)) ) } +/** + * The GitLab user a person filter names: for `me`, the viewer's own verified organization email, + * never the source's service account; otherwise the email given. + */ +async function gitLabPerson( + client: NativeClient, + own: string, + involving: string | undefined +): Promise { + if (!involving) return undefined + const email = involving === 'me' ? userTokenEmail(own) : involving + if (!email) throw new NativeSearchError('unavailable', 'GitLab search requires a verified email.') + return resolveGitLabPerson(client, email) +} + /** The connector document ID prefix each kind's permissions are evaluated under. */ const GITLAB_DOCUMENT_PREFIXES = { code: 'file', @@ -412,7 +440,9 @@ async function createProjectSession( async search(search: NativeSearchInput) { if (search.native?.project && ![project, projectPath].includes(search.native.project)) return { documents: [] } - const selected = defaultKinds(kinds, search.native?.kind) + const selected = defaultKinds(kinds, search) + if (!selected.length) return { documents: [] } + const person = await gitLabPerson(client, own, search.involving) const request = (kind: GitLabSearchKind) => searchGitLab( client, @@ -426,7 +456,7 @@ async function createProjectSession( kind, }, }, - { ref: string(config.ref) || undefined } + { ref: string(config.ref) || undefined, person } ) const page = selected.length === 1 @@ -474,7 +504,8 @@ const groupCursorSchema = z .object({ mode: z.enum(['group', 'project']), projectIndex: z.number().int().min(0).max(GITLAB_GROUP_MAX_PROJECTS), - page: z.number().int().min(1).max(10_000), + /** The collection's own cursor; absent on its first page. */ + cursor: z.string().max(512).optional(), }) .strict() .nullable() @@ -564,6 +595,7 @@ async function createGroupSession(input: GitLabSessionInput, own: string) { kinds: GitLabSearchKind[], raw?: string ): Promise => { + const person = await gitLabPerson(client, own, search.involving) /** Group search takes no branch, so a source limited to one searches its projects instead. */ const fallback = (kind: string) => Boolean( @@ -605,7 +637,6 @@ async function createGroupSession(input: GitLabSessionInput, own: string) { positions: kinds.map((kind) => ({ mode: fallback(kind) ? 'project' : 'group', projectIndex: 0, - page: 1, })), } } @@ -629,14 +660,17 @@ async function createGroupSession(input: GitLabSessionInput, own: string) { query: search.query, ...search.native, kind, - cursor: String(position.page), + cursor: position.cursor, }, } attempts += 1 try { let result: NativePage if (position.mode === 'group') { - result = await searchGitLab(client, query, { groupId: metadata.group.id }) + result = await searchGitLab(client, query, { + groupId: metadata.group.id, + person, + }) const byId = new Set(result.documents.map((document) => document.container)) const candidates = projects.filter((project) => byId.has(String(project.id))) const allowed = new Map( @@ -676,10 +710,10 @@ async function createGroupSession(input: GitLabSessionInput, own: string) { documents.push(...result.documents) partial ||= Boolean(result.partial) cursor.capped ||= Boolean(result.hasMore && !result.nextCursor) - if (result.nextCursor) position.page = Number(result.nextCursor) + if (result.nextCursor) position.cursor = result.nextCursor else if (position.mode === 'project') { position.projectIndex += 1 - position.page = 1 + position.cursor = undefined } else cursor.positions[index] = null } catch (error) { input.signal.throwIfAborted() @@ -689,7 +723,7 @@ async function createGroupSession(input: GitLabSessionInput, own: string) { (error.httpStatus === 400 || error.httpStatus === 422) ) { position.mode = 'project' - position.page = 1 + position.cursor = undefined continue } if ( @@ -705,7 +739,7 @@ async function createGroupSession(input: GitLabSessionInput, own: string) { : 'One GitLab collection could not be searched.' ) position.projectIndex += 1 - position.page = 1 + position.cursor = undefined } } return { @@ -752,23 +786,32 @@ async function createGroupSession(input: GitLabSessionInput, own: string) { const project = await referencedProject(search.native.project) return project ? (await session(project)).search(search) : { documents: [] } } - const kinds = defaultKinds(gitLabSourceKinds(source.config), search.native?.kind) + const kinds = defaultKinds(gitLabSourceKinds(source.config), search) if (!kinds.length) return { documents: [] } const raw = search.native?.cursor if (metadata.mode === 'csv' && (!raw || raw.startsWith('g1.'))) return searchGroup(search, kinds, raw) const projects = await fallbackProjects() const legacyCursor = raw ?? `${stored.revision}:${search.limit}:0:0:1` - if (!/^\d{1,10}:\d{1,3}:\d{1,5}:\d:\d{1,4}$/.test(legacyCursor)) + const parts = legacyCursor.split(':') + // The last part is the collection's own cursor: a page, or a person search's continuation. + const collectionCursor = parts[4] ?? '' + if ( + !/^\d{1,10}:\d{1,3}:\d{1,5}:\d:/.test(legacyCursor) || + parts.length !== 5 || + !(/^[1-9]\d{0,3}$/.test(collectionCursor) || isGitLabMergedCursor(collectionCursor)) + ) throw new NativeSearchError('unavailable', 'Invalid GitLab group page.') - const [revision, pageSize, ...position] = legacyCursor.split(':').map(Number) + const [revision, pageSize, startProject = 0, startKind = 0] = parts.slice(0, 4).map(Number) if (revision !== stored.revision || pageSize !== search.limit) throw new NativeSearchError( 'unavailable', 'GitLab permissions or page size changed. Restart the search.' ) - let [projectIndex = 0, kindIndex = 0, page = 1] = position - if (page < 1 || projectIndex > projects.length || (kinds.length && kindIndex >= kinds.length)) + let projectIndex = startProject + let kindIndex = startKind + let page = collectionCursor + if (projectIndex > projects.length || (kinds.length && kindIndex >= kinds.length)) throw new NativeSearchError('unavailable', 'Invalid GitLab group page.') const documents: NativeDocument[] = [] const failures: string[] = [] @@ -794,14 +837,14 @@ async function createGroupSession(input: GitLabSessionInput, own: string) { ...search.native, project: String(project.id), kind, - cursor: String(page), + cursor: page === '1' ? undefined : page, }, }) documents.push(...current.documents) partial ||= Boolean(current.partial) - if (current.nextCursor) page = Number(current.nextCursor) + if (current.nextCursor) page = current.nextCursor else { - page = 1 + page = '1' kindIndex += 1 if (kindIndex >= kinds.length) { kindIndex = 0 @@ -821,7 +864,7 @@ async function createGroupSession(input: GitLabSessionInput, own: string) { ? error.message : 'One GitLab collection could not be searched.' ) - page = 1 + page = '1' kindIndex += 1 if (kindIndex >= kinds.length) { kindIndex = 0 diff --git a/apps/sim/lib/sim-search/live/gitlab.test.ts b/apps/sim/lib/sim-search/live/gitlab.test.ts index 2c9ac04f22f..718e7d038c2 100644 --- a/apps/sim/lib/sim-search/live/gitlab.test.ts +++ b/apps/sim/lib/sim-search/live/gitlab.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest' -import { readGitLab, searchGitLab } from '@/lib/sim-search/live/gitlab' +import { readGitLab, resolveGitLabPerson, searchGitLab } from '@/lib/sim-search/live/gitlab' import { NativeSearchError } from '@/lib/sim-search/live/http' import type { NativeClient, NativeSearchInput } from '@/lib/sim-search/live/types' @@ -390,3 +390,152 @@ describe('GitLab commit reads', () => { expect(requests).toEqual([]) }) }) + +describe('GitLab person filters', () => { + const ADA = { + id: 7, + email: 'ada@example.com', + state: 'active', + confirmed_at: '2026-01-01T00:00:00Z', + } + const person = { id: 7, emails: ['ada@example.com', 'ada@users.example.com'] } + const search = (kind?: 'issues' | 'merge_requests' | 'code' | 'commits'): NativeSearchInput => ({ + query: 'cache', + limit: 2, + scopes: [], + native: { provider: 'gitlab', query: 'cache', project: '42', ...(kind ? { kind } : {}) }, + }) + + it('names a person only by the verified primary email an administrator sees', async () => { + const resolve = (users: unknown[]) => + resolveGitLabPerson( + gitlab({ + '/api/v4/users': () => users, + '/api/v4/users/7/emails': () => [ + { email: 'ada@users.example.com', confirmed_at: '2026-01-02T00:00:00Z' }, + { email: 'unverified@example.com', confirmed_at: null }, + ], + }).client, + 'Ada@Example.com' + ) + await expect(resolve([ADA, { ...ADA, id: 8, email: 'ada.l@example.com' }])).resolves.toEqual( + person + ) + await expect( + resolve([{ id: 7, username: 'ada', public_email: 'ada@example.com' }]) + ).rejects.toThrow('administrator token') + await expect(resolve([{ ...ADA, confirmed_at: null }])).rejects.toThrow('No single active') + await expect(resolve([{ ...ADA, state: 'blocked' }])).rejects.toThrow('No single active') + await expect(resolve([{ ...ADA, locked: true }])).rejects.toThrow('No single active') + await expect(resolve([ADA, { ...ADA, id: 9 }])).rejects.toThrow('No single active') + }) + + it('merges what the person authored, is assigned or reviews, a result page at a time, skipping none', async () => { + const roles = new Set() + const mr = (iid: number) => ({ + iid, + project_id: 42, + title: `MR ${iid}`, + updated_at: `2026-11-${String(10 + iid).padStart(2, '0')}T00:00:00Z`, + author: { id: 1 }, + }) + const byRole: Record = { + author_id: [5, 4, 3, 2, 1], + assignee_id: [6, 2], + reviewer_id: [9, 8, 7, 3], + } + const { client } = gitlab({ + '/api/v4/projects/42/merge_requests': (query) => { + const role = Object.keys(byRole).find((key) => query?.[key] === '7') ?? '' + roles.add(role) + const size = Number(query?.per_page) + const start = (Number(query?.page) - 1) * size + return (byRole[role] ?? []).slice(start, start + size).map(mr) + }, + }) + for (const limit of [1, 3]) { + const seen: string[] = [] + let cursor: string | undefined + do { + const page = await searchGitLab( + client, + { + ...search('merge_requests'), + limit, + native: { + provider: 'gitlab', + query: 'cache', + project: '42', + kind: 'merge_requests', + cursor, + }, + }, + { person } + ) + expect(page.documents.length).toBeLessThanOrEqual(limit) + seen.push(...page.documents.map((document) => document.id)) + cursor = page.nextCursor + } while (cursor) + expect(seen).toEqual(['9', '8', '7', '6', '5', '4', '3', '2', '1']) + } + expect([...roles].sort()).toEqual(['assignee_id', 'author_id', 'reviewer_id']) + }) + + it('searches only collections with an author, and refuses code under a person filter', async () => { + const paths: string[] = [] + const { client } = gitlab({ + '/api/v4/projects/42/issues': () => { + paths.push('issues') + return [] + }, + '/api/v4/projects/42/merge_requests': () => { + paths.push('merge_requests') + return [] + }, + }) + const page = await searchGitLab(client, search(), { person }) + expect([...new Set(paths)].sort()).toEqual(['issues', 'merge_requests']) + expect(page.message).toContain('no author') + await expect(searchGitLab(client, search('code'), { person })).rejects.toThrow('no author') + }) + + it('keeps only commits written under the person’s verified emails', async () => { + const { client } = gitlab({ + '/api/v4/projects/42/repository/commits': () => [ + { ...commit('Fix cache'), author_email: 'ADA@users.example.com' }, + { ...commit('Fix cache too', 'bbbbbbb1'), author_email: 'mallory@example.com' }, + ], + }) + const page = await searchGitLab(client, { ...search('commits'), limit: 4 }, { person }) + expect(page.documents.map((document) => document.id)).toEqual([SHA]) + const capped = await searchGitLab( + client, + { ...search('commits'), limit: 4 }, + { person: { ...person, emailsCapped: true } } + ) + expect(capped).toMatchObject({ partial: true, message: expect.stringContaining('more') }) + const full = gitlab({ + '/api/v4/projects/42/repository/commits': () => [ + { ...commit('Fix cache'), author_email: 'ada@example.com' }, + { ...commit('Fix cache too', 'bbbbbbb1'), author_email: 'ada@example.com' }, + ], + }) + const last = await searchGitLab( + full.client, + { + ...search('commits'), + limit: 4, + native: { + provider: 'gitlab', + query: 'cache', + project: '42', + kind: 'commits', + cursor: 'p.40000.40000', + }, + }, + { person } + ) + expect(last).toMatchObject({ partial: true, hasMore: true }) + expect(last.nextCursor).toBeUndefined() + }) +}) diff --git a/apps/sim/lib/sim-search/live/gitlab.ts b/apps/sim/lib/sim-search/live/gitlab.ts index 89ade10ce94..7cacaf5f96e 100644 --- a/apps/sim/lib/sim-search/live/gitlab.ts +++ b/apps/sim/lib/sim-search/live/gitlab.ts @@ -1,3 +1,4 @@ +import { normalizeEmail } from '@sim/utils/string' import type { GitLabSearchKind } from '@/lib/api/contracts/mothership-assistant-tools' import { dateSortDirection, @@ -22,11 +23,21 @@ import type { NativePage, NativeSearchInput, } from '@/lib/sim-search/live/types' +import { verifiedGitLabEmail } from '@/connectors/gitlab/permissions' import { encodeGitLabResourceId } from '@/tools/gitlab/utils' /** Collections a search without a kind covers; commits must be asked for, as on GitHub. */ const GITLAB_DEFAULT_KINDS = ['issues', 'code', 'merge_requests'] as const +/** Collections whose items have an author, the only ones a person filter can apply to. */ +export const GITLAB_AUTHORED_KINDS: ReadonlySet = new Set([ + 'issues', + 'merge_requests', + 'commits', +]) +const GITLAB_NO_AUTHOR = + 'GitLab code and wiki have no author and are excluded from person-filtered searches; use kind issues, merge_requests or commits.' + /** Collections searched only when a search names them, whatever else a source serves. */ export const GITLAB_OPT_IN_KINDS: readonly GitLabSearchKind[] = ['commits'] @@ -55,6 +66,193 @@ export interface GitLabCodeScope { export interface GitLabSearchScope { groupId?: number ref?: string + /** Limits results to the work of this GitLab user. */ + person?: GitLabPerson +} + +/** The GitLab user a person filter names, and the verified emails their commits may carry. */ +export interface GitLabPerson { + id: number + emails: string[] + /** The person confirmed more emails than a commit search covers. */ + emailsCapped?: true +} + +/** Secondary emails a person's commit filter accepts besides the primary one. */ +const GITLAB_PERSON_MAX_EMAILS = 5 + +/** + * The one active GitLab user whose primary email is `email`, as an administrator token sees it. + * Only an administrator sees private primary emails; a public profile email is something a user + * sets, not proof of who they are, so it never names a person here. + */ +export async function resolveGitLabPerson( + client: NativeClient, + email: string +): Promise { + const target = normalizeEmail(email) + const rows = array( + await client.json('/api/v4/users', { + query: { search: target, per_page: '20' }, + memo: true, + }) + ) + if (rows.length && rows.every((row) => !('email' in row))) + throw new NativeSearchError( + 'unavailable', + 'GitLab person filters need an administrator token for this source.' + ) + const matches = rows.filter((row) => verifiedGitLabEmail(row) === target) + const [match] = matches + const id = Number(match?.id) + if (matches.length !== 1 || !Number.isSafeInteger(id)) + throw new NativeSearchError( + 'unavailable', + 'No single active GitLab user has this verified email. Search without involving.' + ) + const secondary = array(await client.json(`/api/v4/users/${id}/emails`, { memo: true })) + .filter((row) => Number.isFinite(Date.parse(string(row.confirmed_at)))) + .map((row) => normalizeEmail(string(row.email))) + const emails = [...new Set([target, ...secondary])].filter(Boolean) + return { + id, + emails: emails.slice(0, GITLAB_PERSON_MAX_EMAILS), + ...(emails.length > GITLAB_PERSON_MAX_EMAILS ? { emailsCapped: true as const } : {}), + } +} + +/** A person search's continuation: each listing's row offset, or `x` once it is exhausted. */ +const GITLAB_MERGED_CURSOR = /^p(?:\.(?:\d{1,7}|x)){1,5}$/ + +/** Whether a cursor continues a person search rather than naming a page. */ +export const isGitLabMergedCursor = (cursor: string) => GITLAB_MERGED_CURSOR.test(cursor) + +/** + * Up to one result page of rows from several listings of one endpoint (one per role or email), + * merged in date order. Each listing is read from its own offset and only the rows the page takes + * advance it, so no row is skipped and the merged order holds across pages. A row several + * listings share is returned once. + */ +async function mergedListings( + client: NativeClient, + path: string, + variants: Record[], + query: Record, + limit: number, + cursor: string | undefined, + order: { key: (row: Record) => string; date: string; direction: 'asc' | 'desc' } +): Promise<{ + rows: Record[] + page: Pick +}> { + const offsets = cursor + ? cursor + .split('.') + .slice(1) + .map((part) => (part === 'x' ? null : Number(part))) + : variants.map(() => 0) + if (offsets.length !== variants.length) + throw new NativeSearchError('unavailable', 'GitLab search options changed. Restart the search.') + let capped = false + const lists = await Promise.all( + variants.map(async (variant, index) => { + const offset = offsets[index] ?? null + if (offset === null) return { offset, rows: [], exhausted: true } + const page = Math.floor(offset / limit) + 1 + if (page > 10_000) { + capped = true + return { offset: null, rows: [], exhausted: true } + } + const response = await client.json(path, { + query: { ...query, ...variant, per_page: String(limit), page: String(page) }, + }) + if (!Array.isArray(response) || response.length > limit) + throw new NativeSearchError('unavailable', 'GitLab returned an invalid listing.') + return { + offset, + rows: array(response).slice(offset % limit), + exhausted: response.length < limit, + } + }) + ) + const taken = lists.map(() => 0) + const emitted = new Set() + const rows: Record[] = [] + const sign = order.direction === 'asc' ? 1 : -1 + const time = (row: Record) => Date.parse(string(row[order.date])) || 0 + while (rows.length < limit) { + // A listing with more rows beyond what was read cannot be ordered against the others. + if (lists.some((list, index) => !list.exhausted && taken[index] === list.rows.length)) break + let best = -1 + for (const [index, list] of lists.entries()) { + const head = list.rows[taken[index] ?? 0] + const current = lists[best]?.rows[taken[best] ?? 0] + if (head && (!current || sign * (time(head) - time(current)) < 0)) best = index + } + const row = lists[best]?.rows[taken[best] ?? 0] + if (!row) break + const key = order.key(row) + for (const [index, list] of lists.entries()) + if (list.rows[taken[index] ?? 0] && order.key(list.rows[taken[index] ?? 0] ?? {}) === key) + taken[index] = (taken[index] ?? 0) + 1 + if (!emitted.has(key)) rows.push(row) + emitted.add(key) + } + const next = lists.map((list, index) => + list.offset === null || (list.exhausted && taken[index] === list.rows.length) + ? 'x' + : String(list.offset + (taken[index] ?? 0)) + ) + return { + rows, + page: next.some((part) => part !== 'x') + ? { nextCursor: `p.${next.join('.')}` } + : capped + ? { partial: true, hasMore: true } + : {}, + } +} + +/** + * Issues or merge requests the person authored, is assigned to, or (merge requests) reviews: + * one listing per role, merged without duplicates. Each listing is a result page, and the cursor + * continues all of them, so no item of a returned page is ever skipped. + */ +async function listGitLabPersonItems( + client: NativeClient, + input: NativeSearchInput, + path: string, + kind: 'issues' | 'merge_requests', + person: GitLabPerson, + cursor: string | undefined +): Promise { + const roles = + kind === 'merge_requests' + ? ['author_id', 'assignee_id', 'reviewer_id'] + : ['author_id', 'assignee_id'] + const dates = nativeDateBounds(input) + const text = nativeText(input) + const direction = dateSortDirection(input.filters) ?? 'desc' + const { rows, page: continuation } = await mergedListings( + client, + path, + roles.map((role) => ({ [role]: String(person.id) })), + { + ...(text ? { search: text } : {}), + ...(dates.start ? { updated_after: dates.start } : {}), + ...(dates.end ? { updated_before: dates.end } : {}), + order_by: 'updated_at', + sort: direction, + }, + input.limit, + cursor, + { + key: (row) => `${string(row.project_id)}:${string(row.iid)}`, + date: 'updated_at', + direction, + } + ) + return { documents: rows.map((row) => document(row, kind)), ...continuation } } /** Listing pages one commit search scans for a match when it matches messages itself. */ @@ -222,30 +420,80 @@ async function listGitLabCommits( } } +/** + * Commits the person authored under any of their verified emails: one listing per email, which + * GitLab filters by author, merged by SHA newest first. Each listing is a result page and the + * cursor continues all of them, so no commit of a returned page is skipped. + */ +async function listGitLabPersonCommits( + client: NativeClient, + input: NativeSearchInput, + project: string, + cursor: string | undefined, + person: GitLabPerson, + ref?: string +): Promise { + const dates = nativeDateBounds(input) + const terms = significantTerms(nativeText(input)) + const emails = new Set(person.emails) + const { rows, page: continuation } = await mergedListings( + client, + `${gitLabProjectPath(project)}/repository/commits`, + person.emails.map((author) => ({ author })), + { + ...(ref ? { ref_name: ref } : {}), + ...(dates.start ? { since: dates.start } : {}), + ...(dates.end ? { until: dates.end } : {}), + }, + input.limit, + cursor, + // GitLab lists commits newest committed first. + { key: (row) => string(row.id), date: 'committed_date', direction: 'desc' } + ) + return { + documents: rows + .filter( + (row) => + emails.has(normalizeEmail(string(row.author_email))) && + termCoverage(string(row.message), terms) === terms.length + ) + .map((row) => commitDocument(row, project, ref)), + ...continuation, + ...(person.emailsCapped + ? { + partial: true, + message: `Commits were searched under the person's first ${GITLAB_PERSON_MAX_EMAILS} verified emails; they have more.`, + } + : {}), + } +} + /** * The project whose commits a commit search lists instead of searching, if any. A project's - * commits are searchable under basic search, but GitLab's commit search filters neither by date - * nor oldest first, so dated searches list instead. Across a group, commit search needs advanced + * commits are searchable under basic search, but GitLab's commit search filters by neither date + * nor author and never sorts oldest first, so dated and person searches list instead. Across a group, commit search needs advanced * search: a group search that cannot run throws with a 400 status, which moves it on to its * projects. */ async function commitListingProject( client: NativeClient, input: NativeSearchInput, - project: string | undefined + project: string | undefined, + person?: GitLabPerson ): Promise { if (dateSortDirection(input.filters) === 'asc') throw new NativeSearchError( 'unavailable', 'GitLab lists commits newest first; sort by newest or omit the sort.' ) - const dated = hasDateBounds(input.filters) || Boolean(dateSortDirection(input.filters)) - if (project) return dated ? project : undefined - if (!dated && (await gitLabAdvancedSearch(client)) !== false) return undefined + const listed = + hasDateBounds(input.filters) || Boolean(dateSortDirection(input.filters)) || Boolean(person) + if (project) return listed ? project : undefined + if (!listed && (await gitLabAdvancedSearch(client)) !== false) return undefined throw new NativeSearchError( 'unavailable', - dated - ? 'GitLab filters commits by date only within a project. Set project to list its commits in that window.' + listed + ? 'GitLab filters commits by date or author only within a project. Set project to list its commits.' : GITLAB_COMMITS_NEED_ADVANCED_SEARCH, undefined, 400 @@ -255,7 +503,7 @@ async function commitListingProject( export async function searchGitLab( client: NativeClient, input: NativeSearchInput, - { groupId, ref }: GitLabSearchScope = {} + { groupId, ref, person }: GitLabSearchScope = {} ): Promise { if (!input.native?.project && groupId === undefined) { const projects = array( @@ -285,7 +533,7 @@ export async function searchGitLab( project: string(project.id), }, }, - { ref } + { ref, person } ) ) } @@ -304,17 +552,20 @@ export async function searchGitLab( } if (!input.native?.kind) return collectNativePages( - GITLAB_DEFAULT_KINDS.map((kind) => - searchGitLab( - client, - { - ...input, - native: { provider: 'gitlab', query: input.query, ...input.native, kind }, - }, - { groupId, ref } - ) + GITLAB_DEFAULT_KINDS.filter((kind) => !person || GITLAB_AUTHORED_KINDS.has(kind)).map( + (kind) => + searchGitLab( + client, + { + ...input, + native: { provider: 'gitlab', query: input.query, ...input.native, kind }, + }, + { groupId, ref, person } + ) ), - 'Searched GitLab issues, merge requests, and code.' + person + ? `Searched GitLab issues and merge requests involving the person. ${GITLAB_NO_AUTHOR}` + : 'Searched GitLab issues, merge requests, and code.' ) const kind = input.native?.kind ?? 'issues' const scope = Object.hasOwn(GITLAB_SCOPES, kind) @@ -325,17 +576,42 @@ export async function searchGitLab( 'unavailable', `GitLab supports ${Object.keys(GITLAB_SCOPES).join(', ')} search.` ) - const page = input.native?.cursor ?? '1' - if (!/^\d{1,5}$/.test(page) || Number(page) < 1 || Number(page) > 10_000) + const cursor = input.native?.cursor + // A person search continues several listings at once; every other search names one page. + const merged = person ? cursor : undefined + const page = person ? '1' : (cursor ?? '1') + if ( + (merged !== undefined && !isGitLabMergedCursor(merged)) || + !/^\d{1,5}$/.test(page) || + Number(page) < 1 || + Number(page) > 10_000 + ) throw new NativeSearchError('unavailable', 'Invalid GitLab page.') if (['code', 'wiki'].includes(kind) && hasDateBounds(input.filters)) throw new NativeSearchError( 'unavailable', 'GitLab code/wiki search does not provide modification dates. Use issues or merge_requests for date-filtered search.' ) + if (person && !GITLAB_AUTHORED_KINDS.has(kind)) + throw new NativeSearchError('unavailable', GITLAB_NO_AUTHOR) const project = groupId === undefined ? input.native?.project : undefined - const listed = kind === 'commits' ? await commitListingProject(client, input, project) : undefined - if (listed) return listGitLabCommits(client, input, listed, Number(page), ref) + const listed = + kind === 'commits' ? await commitListingProject(client, input, project, person) : undefined + if (listed) + return person + ? listGitLabPersonCommits(client, input, listed, merged, person, ref) + : listGitLabCommits(client, input, listed, Number(page), ref) + if (person && (kind === 'issues' || kind === 'merge_requests')) + return listGitLabPersonItems( + client, + input, + groupId !== undefined + ? `/api/v4/groups/${groupId}/${kind}` + : `${gitLabProjectPath(project ?? '')}/${kind}`, + kind, + person, + merged + ) const groupPageLimit = Math.floor(10_000 / input.limit) if (groupId !== undefined && Number(page) > groupPageLimit) throw new NativeSearchError( diff --git a/apps/sim/lib/sim-search/live/providers.ts b/apps/sim/lib/sim-search/live/providers.ts index 9f7e9000af1..c7185d11033 100644 --- a/apps/sim/lib/sim-search/live/providers.ts +++ b/apps/sim/lib/sim-search/live/providers.ts @@ -290,6 +290,8 @@ export const LIVE_SEARCH_PROVIDERS = { read: (client, reference, options) => readFlow(client, reference, options.origin), }, gitlab: { + involving: + 'issues and merge requests they authored or are assigned to, merge requests they review, and commits they authored within a project; code and wiki are skipped', guide: { syntax: 'Plain search terms with kind issues, merge_requests, code, wiki or commits, on administrator-configured projects only; no kind searches issues, merge requests and code. Under basic or advanced search, code and wiki accept filename:, path: and extension: filters (-filename: or -extension: excludes files); where exact code search handles code, use file: and lang: instead. Advanced search also accepts "exact phrase", | for OR and -word to exclude.',