Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 17 additions & 6 deletions apps/sim/connectors/gitlab/permissions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -405,15 +405,25 @@ async function listAll<T>(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 {
Expand Down Expand Up @@ -452,7 +462,7 @@ export function gitLabFeatureAudience(
: null
const emails = new Set<string>()
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
Expand Down Expand Up @@ -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] : []
})
)
Expand All @@ -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)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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: [
Expand Down Expand Up @@ -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 = (
Expand Down Expand Up @@ -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]!
Expand Down
5 changes: 5 additions & 0 deletions apps/sim/lib/knowledge/access/tokens.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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. */
Expand Down
26 changes: 25 additions & 1 deletion apps/sim/lib/sim-search/live/gitlab-admin.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<typeof import('@/connectors/gitlab/permissions')>()),
openGitLabDirectory: mocks.directory,
getGitLabDocumentAcls: mocks.acl,
validateGitLabCsvToken: mocks.csv,
Expand Down Expand Up @@ -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(
Expand Down
91 changes: 67 additions & 24 deletions apps/sim/lib/sim-search/live/gitlab-admin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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 {
Expand Down Expand Up @@ -174,13 +178,37 @@ export async function resolveAdminGitLabAccount(owner: ResourceOwner, account: L
type Reference = Pick<NativeDocument, 'id' | 'container' | 'kind' | 'revision'>
type AdminSource = { id: string; config: Record<string, unknown> }

/** 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<NativeSearchInput, 'native' | 'involving'>
): 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<GitLabPerson | undefined> {
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',
Expand Down Expand Up @@ -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,
Expand All @@ -426,7 +456,7 @@ async function createProjectSession(
kind,
},
},
{ ref: string(config.ref) || undefined }
{ ref: string(config.ref) || undefined, person }
)
const page =
selected.length === 1
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -564,6 +595,7 @@ async function createGroupSession(input: GitLabSessionInput, own: string) {
kinds: GitLabSearchKind[],
raw?: string
): Promise<NativePage> => {
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(
Expand Down Expand Up @@ -605,7 +637,6 @@ async function createGroupSession(input: GitLabSessionInput, own: string) {
positions: kinds.map((kind) => ({
mode: fallback(kind) ? 'project' : 'group',
projectIndex: 0,
page: 1,
})),
}
}
Expand All @@ -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(
Expand Down Expand Up @@ -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()
Expand All @@ -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 (
Expand All @@ -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 {
Expand Down Expand Up @@ -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[] = []
Expand All @@ -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
Expand All @@ -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
Expand Down
Loading
Loading