Skip to content

Commit 2019eb6

Browse files
authored
feat(gitlab): filter GitLab search by person through their verified email (#10547)
* feat(gitlab): filter GitLab search by person through their verified email * fix(gitlab): keep accepting group cursors that carry a page number
1 parent 398ffa6 commit 2019eb6

8 files changed

Lines changed: 590 additions & 57 deletions

File tree

‎apps/sim/connectors/gitlab/permissions.ts‎

Lines changed: 17 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -405,15 +405,25 @@ async function listAll<T>(url: string, token: string, signal?: AbortSignal): Pro
405405
return items
406406
}
407407

408-
function verifiedEmail(person: GitLabPermissionUser): string | null {
408+
/**
409+
* A GitLab user's primary email when it identifies them: an active, unlocked user who confirmed
410+
* it. An administrator token sees this email; a public profile email proves nothing.
411+
*/
412+
export function verifiedGitLabEmail(person: {
413+
state?: unknown
414+
locked?: unknown
415+
confirmed_at?: unknown
416+
email?: unknown
417+
}): string | null {
409418
if (
410419
person.state !== 'active' ||
411420
person.locked === true ||
412421
typeof person.confirmed_at !== 'string' ||
413-
!Number.isFinite(Date.parse(person.confirmed_at))
422+
!Number.isFinite(Date.parse(person.confirmed_at)) ||
423+
typeof person.email !== 'string'
414424
)
415425
return null
416-
return userToken(person.email) ? normalizeEmail(person.email as string) : null
426+
return userToken(person.email) ? normalizeEmail(person.email) : null
417427
}
418428

419429
function activeRole(member: GitLabPermissionMember | undefined, now: Date): number {
@@ -452,7 +462,7 @@ export function gitLabFeatureAudience(
452462
: null
453463
const emails = new Set<string>()
454464
for (const person of users) {
455-
const email = verifiedEmail(person)
465+
const email = verifiedGitLabEmail(person)
456466
if (!email) continue
457467
if (repositoryAudience && !repositoryAudience.has(email)) continue
458468
const role = roles.get(person.id) ?? 0
@@ -673,7 +683,8 @@ export async function getGitLabDocumentAcls(
673683
result[doc.externalId] = state.policy.implicitAdmin
674684
? sortAccessTokens(
675685
state.users.flatMap((person) => {
676-
const grant = person.is_admin === true ? userToken(verifiedEmail(person)) : null
686+
const grant =
687+
person.is_admin === true ? userToken(verifiedGitLabEmail(person)) : null
677688
return grant ? [grant] : []
678689
})
679690
)
@@ -699,7 +710,7 @@ export async function getGitLabDocumentAcls(
699710
if (typeof authorId === 'number') ids.add(authorId)
700711
for (const id of ids) {
701712
const person = users.get(id)
702-
const email = person ? verifiedEmail(person) : null
713+
const email = person ? verifiedGitLabEmail(person) : null
703714
const grant = userToken(email)
704715
if (grant && email && issueAudience.has(email)) acl.push(grant)
705716
}

‎apps/sim/lib/knowledge/__integration__/gitlab-federated.integration.ts‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -103,13 +103,15 @@ describe.skipIf(!fixtureFile)('federated self-hosted GitLab Search', () => {
103103

104104
function search(
105105
person: FixturePerson,
106-
kind: 'issues' | 'code' | 'wiki' | 'merge_requests' | 'commits'
106+
kind: 'issues' | 'code' | 'wiki' | 'merge_requests' | 'commits',
107+
involving?: string
107108
) {
108109
return searchLiveKnowledge.execute({
109110
principal: principal(person),
110111
input: {
111112
organizationId: ids.organizationId,
112113
query: QUERY,
114+
...(involving ? { involving } : {}),
113115
topK: 20,
114116
filters: { source: 'gitlab' },
115117
nativeQueries: [
@@ -237,10 +239,13 @@ describe.skipIf(!fixtureFile)('federated self-hosted GitLab Search', () => {
237239
content: `${QUERY} wiki content.`,
238240
format: 'markdown',
239241
})
242+
const assignee = people.reporter
243+
if (!assignee) throw new Error('Expected the reporter fixture')
240244
issueIid = (
241245
await api<{ iid: number }>(`/projects/${projectId}/issues`, 'POST', {
242246
title: `${QUERY} normal issue`,
243247
description: `${QUERY} normal issue body.`,
248+
assignee_ids: [assignee.id],
244249
})
245250
).iid
246251
confidentialIid = (
@@ -353,6 +358,17 @@ describe.skipIf(!fixtureFile)('federated self-hosted GitLab Search', () => {
353358
expect(content).not.toContain('security review')
354359
}, 120_000)
355360

361+
it('filters issues to the person by their verified email', async () => {
362+
const reporter = people.reporter
363+
const guest = people.guest
364+
if (!reporter || !guest) throw new Error('Expected the person fixtures')
365+
const assigned = await search(reporter, 'issues', reporter.email)
366+
expect(assigned.results.map((row) => decodeLiveReference(row.documentId).id)).toEqual([
367+
String(issueIid),
368+
])
369+
expect((await search(reporter, 'issues', guest.email)).results).toEqual([])
370+
}, 120_000)
371+
356372
it('keeps references reader-bound and rechecks confidentiality before reads', async () => {
357373
const reporter = await search(people.reporter!, 'code')
358374
const file = reporter.results[0]!

‎apps/sim/lib/knowledge/access/tokens.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -159,6 +159,11 @@ export function userToken(email: string | null | undefined): string | null {
159159
return isAccessToken(token) ? token : null
160160
}
161161

162+
/** The email a {@link userToken} names, or null for any other token. */
163+
export function userTokenEmail(token: string): string | null {
164+
return token.startsWith('u:') && isAccessToken(token) ? token.slice('u:'.length) : null
165+
}
166+
162167
export interface GroupIdentity {
163168
providerId: string
164169
/** The provider's tenant, or {@link NO_TENANT_SEGMENT} where it reports none. */

‎apps/sim/lib/sim-search/live/gitlab-admin.test.ts‎

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,8 @@ vi.mock('@/lib/knowledge/connectors/permission-store', () => ({
3434
hasConnectorPermissionGrant: mocks.grant,
3535
readConnectorPermissionMetadata: mocks.metadata,
3636
}))
37-
vi.mock('@/connectors/gitlab/permissions', () => ({
37+
vi.mock('@/connectors/gitlab/permissions', async (importOriginal) => ({
38+
...(await importOriginal<typeof import('@/connectors/gitlab/permissions')>()),
3839
openGitLabDirectory: mocks.directory,
3940
getGitLabDocumentAcls: mocks.acl,
4041
validateGitLabCsvToken: mocks.csv,
@@ -266,6 +267,29 @@ describe('administrator-managed live GitLab authorization', () => {
266267
'wiki',
267268
])
268269
})
270+
it('filters by the viewer’s own verified email for involving me, never the source’s account', async () => {
271+
const current = await session()
272+
const paths: string[] = []
273+
client.json.mockImplementation(
274+
async (path: string, options?: { query?: { search?: string } }) => {
275+
paths.push(path)
276+
if (path === '/api/v4/users')
277+
return options?.query?.search === 'reader@example.com'
278+
? [{ id: 5, email: 'reader@example.com', state: 'active', confirmed_at: '2026-01-01' }]
279+
: []
280+
if (path === '/api/v4/users/5/emails') return []
281+
return project
282+
}
283+
)
284+
await current.search({ query: 'fix', limit: 10, scopes: [], involving: 'me' })
285+
expect(paths).not.toContain('/api/v4/user')
286+
expect(
287+
mocks.search.mock.calls.map(([, input, scope]) => [input.native.kind, scope.person])
288+
).toEqual([
289+
['issues', { id: 5, emails: ['reader@example.com'] }],
290+
['merge_requests', { id: 5, emails: ['reader@example.com'] }],
291+
])
292+
})
269293
it('propagates the caller deadline into the canonical permission directory', async () => {
270294
await session()
271295
expect(mocks.directory).toHaveBeenCalledWith(

‎apps/sim/lib/sim-search/live/gitlab-admin.ts‎

Lines changed: 74 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ import { decryptApiKey } from '@/lib/api-key/crypto'
99
import { type ResourceOwner, resourceScopeFromOwner } from '@/lib/core/resource-scope'
1010
import { resourceScopeCondition } from '@/lib/core/resource-scope.server'
1111
import { createUserKnowledgeAccessProvider } from '@/lib/knowledge/access/scope'
12-
import { groupToken } from '@/lib/knowledge/access/tokens'
12+
import { groupToken, userTokenEmail } from '@/lib/knowledge/access/tokens'
1313
import {
1414
connectorsGrantingSubject,
1515
hasConnectorPermissionGrant,
@@ -19,11 +19,15 @@ import {
1919
import { searchIntegrationAccessCondition } from '@/lib/knowledge/search/integration-policy'
2020
import { dateSortDirection, hasDateBounds } from '@/lib/sim-search/live/dates'
2121
import {
22+
GITLAB_AUTHORED_KINDS,
2223
GITLAB_OPT_IN_KINDS,
2324
type GitLabCodeScope,
25+
type GitLabPerson,
2426
gitLabDocumentUrl,
2527
gitLabProjectPath,
28+
isGitLabMergedCursor,
2629
readGitLab,
30+
resolveGitLabPerson,
2731
searchGitLab,
2832
} from '@/lib/sim-search/live/gitlab'
2933
import {
@@ -174,13 +178,37 @@ export async function resolveAdminGitLabAccount(owner: ResourceOwner, account: L
174178
type Reference = Pick<NativeDocument, 'id' | 'container' | 'kind' | 'revision'>
175179
type AdminSource = { id: string; config: Record<string, unknown> }
176180

177-
/** The source's kinds a search covers: the one it names, or all but the opt-in kinds. */
178-
function defaultKinds(kinds: GitLabSearchKind[], requested?: string): GitLabSearchKind[] {
179-
return kinds.filter((kind) =>
180-
requested ? kind === requested : !GITLAB_OPT_IN_KINDS.includes(kind)
181+
/**
182+
* The source's kinds a search covers: the one it names, or all but the opt-in kinds, and for a
183+
* person filter only the kinds whose items have an author.
184+
*/
185+
function defaultKinds(
186+
kinds: GitLabSearchKind[],
187+
search: Pick<NativeSearchInput, 'native' | 'involving'>
188+
): GitLabSearchKind[] {
189+
const requested = search.native?.kind
190+
if (requested) return kinds.filter((kind) => kind === requested)
191+
return kinds.filter(
192+
(kind) =>
193+
!GITLAB_OPT_IN_KINDS.includes(kind) && (!search.involving || GITLAB_AUTHORED_KINDS.has(kind))
181194
)
182195
}
183196

197+
/**
198+
* The GitLab user a person filter names: for `me`, the viewer's own verified organization email,
199+
* never the source's service account; otherwise the email given.
200+
*/
201+
async function gitLabPerson(
202+
client: NativeClient,
203+
own: string,
204+
involving: string | undefined
205+
): Promise<GitLabPerson | undefined> {
206+
if (!involving) return undefined
207+
const email = involving === 'me' ? userTokenEmail(own) : involving
208+
if (!email) throw new NativeSearchError('unavailable', 'GitLab search requires a verified email.')
209+
return resolveGitLabPerson(client, email)
210+
}
211+
184212
/** The connector document ID prefix each kind's permissions are evaluated under. */
185213
const GITLAB_DOCUMENT_PREFIXES = {
186214
code: 'file',
@@ -412,7 +440,9 @@ async function createProjectSession(
412440
async search(search: NativeSearchInput) {
413441
if (search.native?.project && ![project, projectPath].includes(search.native.project))
414442
return { documents: [] }
415-
const selected = defaultKinds(kinds, search.native?.kind)
443+
const selected = defaultKinds(kinds, search)
444+
if (!selected.length) return { documents: [] }
445+
const person = await gitLabPerson(client, own, search.involving)
416446
const request = (kind: GitLabSearchKind) =>
417447
searchGitLab(
418448
client,
@@ -426,7 +456,7 @@ async function createProjectSession(
426456
kind,
427457
},
428458
},
429-
{ ref: string(config.ref) || undefined }
459+
{ ref: string(config.ref) || undefined, person }
430460
)
431461
const page =
432462
selected.length === 1
@@ -474,9 +504,16 @@ const groupCursorSchema = z
474504
.object({
475505
mode: z.enum(['group', 'project']),
476506
projectIndex: z.number().int().min(0).max(GITLAB_GROUP_MAX_PROJECTS),
477-
page: z.number().int().min(1).max(10_000),
507+
/** The collection's own cursor; absent on its first page. */
508+
cursor: z.string().max(512).optional(),
509+
/** A page number, as cursors issued before collection cursors carried it. */
510+
page: z.number().int().min(1).max(10_000).optional(),
478511
})
479512
.strict()
513+
.transform(({ page, ...position }) => ({
514+
...position,
515+
cursor: position.cursor ?? (page && page > 1 ? String(page) : undefined),
516+
}))
480517
.nullable()
481518
)
482519
.min(1)
@@ -564,6 +601,7 @@ async function createGroupSession(input: GitLabSessionInput, own: string) {
564601
kinds: GitLabSearchKind[],
565602
raw?: string
566603
): Promise<NativePage> => {
604+
const person = await gitLabPerson(client, own, search.involving)
567605
/** Group search takes no branch, so a source limited to one searches its projects instead. */
568606
const fallback = (kind: string) =>
569607
Boolean(
@@ -605,7 +643,7 @@ async function createGroupSession(input: GitLabSessionInput, own: string) {
605643
positions: kinds.map((kind) => ({
606644
mode: fallback(kind) ? 'project' : 'group',
607645
projectIndex: 0,
608-
page: 1,
646+
cursor: undefined,
609647
})),
610648
}
611649
}
@@ -629,14 +667,17 @@ async function createGroupSession(input: GitLabSessionInput, own: string) {
629667
query: search.query,
630668
...search.native,
631669
kind,
632-
cursor: String(position.page),
670+
cursor: position.cursor,
633671
},
634672
}
635673
attempts += 1
636674
try {
637675
let result: NativePage
638676
if (position.mode === 'group') {
639-
result = await searchGitLab(client, query, { groupId: metadata.group.id })
677+
result = await searchGitLab(client, query, {
678+
groupId: metadata.group.id,
679+
person,
680+
})
640681
const byId = new Set(result.documents.map((document) => document.container))
641682
const candidates = projects.filter((project) => byId.has(String(project.id)))
642683
const allowed = new Map(
@@ -676,10 +717,10 @@ async function createGroupSession(input: GitLabSessionInput, own: string) {
676717
documents.push(...result.documents)
677718
partial ||= Boolean(result.partial)
678719
cursor.capped ||= Boolean(result.hasMore && !result.nextCursor)
679-
if (result.nextCursor) position.page = Number(result.nextCursor)
720+
if (result.nextCursor) position.cursor = result.nextCursor
680721
else if (position.mode === 'project') {
681722
position.projectIndex += 1
682-
position.page = 1
723+
position.cursor = undefined
683724
} else cursor.positions[index] = null
684725
} catch (error) {
685726
input.signal.throwIfAborted()
@@ -689,7 +730,7 @@ async function createGroupSession(input: GitLabSessionInput, own: string) {
689730
(error.httpStatus === 400 || error.httpStatus === 422)
690731
) {
691732
position.mode = 'project'
692-
position.page = 1
733+
position.cursor = undefined
693734
continue
694735
}
695736
if (
@@ -705,7 +746,7 @@ async function createGroupSession(input: GitLabSessionInput, own: string) {
705746
: 'One GitLab collection could not be searched.'
706747
)
707748
position.projectIndex += 1
708-
position.page = 1
749+
position.cursor = undefined
709750
}
710751
}
711752
return {
@@ -752,23 +793,32 @@ async function createGroupSession(input: GitLabSessionInput, own: string) {
752793
const project = await referencedProject(search.native.project)
753794
return project ? (await session(project)).search(search) : { documents: [] }
754795
}
755-
const kinds = defaultKinds(gitLabSourceKinds(source.config), search.native?.kind)
796+
const kinds = defaultKinds(gitLabSourceKinds(source.config), search)
756797
if (!kinds.length) return { documents: [] }
757798
const raw = search.native?.cursor
758799
if (metadata.mode === 'csv' && (!raw || raw.startsWith('g1.')))
759800
return searchGroup(search, kinds, raw)
760801
const projects = await fallbackProjects()
761802
const legacyCursor = raw ?? `${stored.revision}:${search.limit}:0:0:1`
762-
if (!/^\d{1,10}:\d{1,3}:\d{1,5}:\d:\d{1,4}$/.test(legacyCursor))
803+
const parts = legacyCursor.split(':')
804+
// The last part is the collection's own cursor: a page, or a person search's continuation.
805+
const collectionCursor = parts[4] ?? ''
806+
if (
807+
!/^\d{1,10}:\d{1,3}:\d{1,5}:\d:/.test(legacyCursor) ||
808+
parts.length !== 5 ||
809+
!(/^[1-9]\d{0,3}$/.test(collectionCursor) || isGitLabMergedCursor(collectionCursor))
810+
)
763811
throw new NativeSearchError('unavailable', 'Invalid GitLab group page.')
764-
const [revision, pageSize, ...position] = legacyCursor.split(':').map(Number)
812+
const [revision, pageSize, startProject = 0, startKind = 0] = parts.slice(0, 4).map(Number)
765813
if (revision !== stored.revision || pageSize !== search.limit)
766814
throw new NativeSearchError(
767815
'unavailable',
768816
'GitLab permissions or page size changed. Restart the search.'
769817
)
770-
let [projectIndex = 0, kindIndex = 0, page = 1] = position
771-
if (page < 1 || projectIndex > projects.length || (kinds.length && kindIndex >= kinds.length))
818+
let projectIndex = startProject
819+
let kindIndex = startKind
820+
let page = collectionCursor
821+
if (projectIndex > projects.length || (kinds.length && kindIndex >= kinds.length))
772822
throw new NativeSearchError('unavailable', 'Invalid GitLab group page.')
773823
const documents: NativeDocument[] = []
774824
const failures: string[] = []
@@ -794,14 +844,14 @@ async function createGroupSession(input: GitLabSessionInput, own: string) {
794844
...search.native,
795845
project: String(project.id),
796846
kind,
797-
cursor: String(page),
847+
cursor: page === '1' ? undefined : page,
798848
},
799849
})
800850
documents.push(...current.documents)
801851
partial ||= Boolean(current.partial)
802-
if (current.nextCursor) page = Number(current.nextCursor)
852+
if (current.nextCursor) page = current.nextCursor
803853
else {
804-
page = 1
854+
page = '1'
805855
kindIndex += 1
806856
if (kindIndex >= kinds.length) {
807857
kindIndex = 0
@@ -821,7 +871,7 @@ async function createGroupSession(input: GitLabSessionInput, own: string) {
821871
? error.message
822872
: 'One GitLab collection could not be searched.'
823873
)
824-
page = 1
874+
page = '1'
825875
kindIndex += 1
826876
if (kindIndex >= kinds.length) {
827877
kindIndex = 0

0 commit comments

Comments
 (0)