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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions apps/sim/lib/sim-search/live/gitlab-admin.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,49 @@ describe('administrator-managed live GitLab authorization', () => {
expect.any(Object)
)
})
it('trusts a ref-scoped search for a commit’s ref and checks any other commit once', async () => {
const sha = '4109c2d872d5fdb1ed057400d103766aaea97f98'
const current = await session({ ...source.config, ref: 'main' })
client.json.mockResolvedValue({ id: sha })
expect(
await current.verify({ id: sha, container: '42', kind: 'commits' }, { ref: 'main' })
).toBe(true)
expect(client.json).toHaveBeenCalledTimes(1)
expect(await current.verify({ id: sha.slice(0, 8), container: '42', kind: 'commits' })).toBe(
true
)
expect(await current.verify({ id: sha, container: '42', kind: 'commits' })).toBe(true)
expect(
client.json.mock.calls.filter(([path]) => String(path).endsWith('/merge_base'))
).toHaveLength(1)
})
it('reads with no repository content from a source that does not serve code', async () => {
const actual = await vi.importActual<typeof import('@/lib/sim-search/live/gitlab')>(
'@/lib/sim-search/live/gitlab'
)
mocks.read.mockImplementation(actual.readGitLab)
const current = await session({ ...source.config, contentTypes: 'merge_requests' })
const mergeRequest = {
project_id: 42,
iid: 9,
title: 'Add cache',
description: 'Adds the cache layer',
target_branch: 'main',
author: { id: 8 },
assignees: [],
}
client.json.mockImplementation(async (path: string) => {
if (path.endsWith('/merge_requests/9')) return mergeRequest
if (path.endsWith('/merge_requests/9/discussions')) return []
if (path.endsWith('/merge_requests/9/diffs'))
return [{ new_path: 'src/secret.ts', old_path: 'src/secret.ts', diff: '+const key = 1' }]
return project
})
const document = await current.read({ id: '9', container: '42', kind: 'merge_requests' })
expect(document.content).toContain('Adds the cache layer')
expect(document.content).not.toContain('const key')
expect(document.content).toContain('Changes are not shown')
})
it('leaves commits out of a source that limits code to a path, whose commits span other files', async () => {
const current = await session({ ...source.config, pathPrefix: 'docs' })
expect(await current.verify({ id: '4109c2d8', container: '42', kind: 'commits' })).toBe(false)
Expand Down
58 changes: 33 additions & 25 deletions apps/sim/lib/sim-search/live/gitlab-admin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import { searchIntegrationAccessCondition } from '@/lib/knowledge/search/integra
import { dateSortDirection, hasDateBounds } from '@/lib/sim-search/live/dates'
import {
GITLAB_OPT_IN_KINDS,
type GitLabCodeScope,
gitLabDocumentUrl,
gitLabProjectPath,
readGitLab,
Expand Down Expand Up @@ -291,7 +292,7 @@ async function createProjectSession(
if (grant) tokens.add(grant)
}
}
const current = object(await client.json(`/api/v4/projects/${segment(string(config.project))}`))
const current = object(await client.json(gitLabProjectPath(string(config.project))))
project = string(current.id)
projectPath = string(current.path_with_namespace)
}
Expand All @@ -308,15 +309,9 @@ async function createProjectSession(
throw new NativeSearchError('unavailable', 'GitLab project identity could not be verified.')
signal.throwIfAborted()
const kinds = gitLabSourceKinds(config)
const permittedReference = (reference: Reference) => {
if (
![project, projectPath].includes(reference.container ?? '') ||
!kinds.some((kind) => kind === reference.kind)
)
return false
if (reference.kind === 'commits') return isCommitSha(reference.id)
if (reference.kind !== 'code') return true
const path = reference.id
const ref = string(config.ref)
/** The repository paths the source's code scope covers: its path prefix and file types. */
const permittedPath = (path: string) => {
if (
path.startsWith('/') ||
path.includes('\\') ||
Expand All @@ -329,22 +324,33 @@ async function createProjectSession(
.split(',')
.map((part) => part.trim().toLowerCase())
.filter(Boolean)
if (
extensions.length &&
!extensions.some((extension) =>
return (
!extensions.length ||
extensions.some((extension) =>
path.toLowerCase().endsWith(extension.startsWith('.') ? extension : `.${extension}`)
)
)
return false
const branch = string(config.ref)
return !branch || reference.revision === branch
}
/** What of the repository a read may show: none unless the source serves code. */
const codeScope: GitLabCodeScope | null = kinds.includes('code')
? { allows: permittedPath, ...(ref ? { ref } : {}) }
: null
/** Commits a ref-scoped search returned, or a merge-base check placed, in the source's ref. */
const onRef = new Set<string>()
const permittedReference = (reference: Reference) => {
if (![project, projectPath].includes(reference.container ?? '')) return false
if (reference.kind === 'commits') return isCommitSha(reference.id)
if (reference.kind !== 'code') return true
if (!permittedPath(reference.id)) return false
return !ref || reference.revision === ref
}
const verify = async (
reference: Reference,
evidence?: Record<string, unknown>
): Promise<boolean> => {
signal.throwIfAborted()
if (!permittedReference(reference)) return false
const kind = kinds.find((candidate) => candidate === reference.kind)
if (!kind || !permittedReference(reference)) return false
let metadata: Record<string, unknown> = {}
if (reference.kind === 'issues' || reference.kind === 'merge_requests') {
if (!/^[1-9]\d*$/.test(reference.id)) return false
Expand All @@ -371,12 +377,14 @@ async function createProjectSession(
return false
}
}
if (reference.kind === 'commits' && string(config.ref)) {
const sha = reference.id.toLowerCase()
if (reference.kind === 'commits' && ref && evidence?.ref !== ref && !onRef.has(sha)) {
// A source limited to one ref (branch, tag or commit) serves only the commits in its history:
// a commit's merge base with that ref is the commit itself.
// a commit's merge base with that ref is the commit itself. Commits a ref-scoped search
// returned are on the ref already.
const base = await client
.json(`${gitLabProjectPath(project)}/repository/merge_base`, {
query: { 'refs[]': [reference.id, string(config.ref)] },
query: { 'refs[]': [reference.id, ref] },
memo: true,
})
.catch((error: unknown) => {
Expand All @@ -385,11 +393,10 @@ async function createProjectSession(
return undefined
throw error
})
if (!string(object(base).id).toLowerCase().startsWith(reference.id.toLowerCase()))
return false
const full = string(object(base).id).toLowerCase()
if (!full.startsWith(sha)) return false
onRef.add(sha).add(full)
}
const kind = kinds.find((candidate) => candidate === reference.kind)
if (!kind) return false
const externalId = `${GITLAB_DOCUMENT_PREFIXES[kind]}:${reference.id}`
const acl = await getGitLabDocumentAcls(
token,
Expand Down Expand Up @@ -441,7 +448,8 @@ async function createProjectSession(
reference.id,
project,
reference.kind,
string(config.ref) || reference.revision
ref || reference.revision,
codeScope
)
if (!(await verify(document, document.accessMetadata)))
throw new NativeSearchError(
Expand Down
146 changes: 134 additions & 12 deletions apps/sim/lib/sim-search/live/gitlab.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,19 +45,34 @@ const commitSearch = (
})

describe('GitLab commit search', () => {
it('lists and matches recent commits when the instance has no advanced search', async () => {
it('searches a project’s commits under basic search, whatever the instance’s advanced search', async () => {
const { client, requests } = gitlab({
'/api/v4/application/settings': () => ({ elasticsearch_search: false }),
'/api/v4/projects/42/repository/commits': () => [
commit('Fix the cache eviction race'),
commit('Bump version', 'aaaaaaa1'),
],
'/api/v4/projects/42': () => PROJECT,
'/api/v4/projects/42/search': (query) =>
query?.scope === 'commits' ? [commit('Fix the cache eviction race')] : [],
})
const page = await searchGitLab(client, commitSearch('cache race'))
expect(page.documents.map((document) => document.id)).toEqual([SHA])
expect(page.documents[0]?.kind).toBe('commits')
expect(page.message).toContain('advanced search')
expect(requests).not.toContain('/api/v4/projects/42/search')
expect(page.documents[0]?.url).toBe(`${PROJECT.web_url}/-/commit/${SHA}`)
expect(requests).not.toContain('/api/v4/application/settings')
expect(requests).not.toContain('/api/v4/projects/42/repository/commits')
})

it('lists a project’s commits for a dated search and dates them where they were committed', async () => {
const windows: unknown[] = []
const { client } = gitlab({
'/api/v4/projects/42/repository/commits': (query) => {
windows.push([query?.since, query?.until])
return [{ ...commit('Fix cache'), committed_date: '2026-11-20T09:00:00Z' }]
},
})
const page = await searchGitLab(
client,
commitSearch('cache', { filters: { startDate: '2026-11-15T00:00:00Z' } })
)
expect(windows).toEqual([['2026-11-15T00:00:00.000Z', undefined]])
expect(page.documents[0]?.modifiedAt).toBe('2026-11-20T09:00:00.000Z')
})

it('continues a commit listing without skipping matches beyond one result page', async () => {
Expand All @@ -75,7 +90,10 @@ describe('GitLab commit search', () => {
const seen: string[] = []
let cursor: string | undefined
do {
const input = commitSearch('cache', { limit: 4 })
const input = commitSearch('cache', {
limit: 4,
filters: { startDate: '2026-01-01T00:00:00Z' },
})
const page = await searchGitLab(client, {
...input,
native: { provider: 'gitlab', query: 'cache', project: '42', kind: 'commits', cursor },
Expand All @@ -95,7 +113,10 @@ describe('GitLab commit search', () => {
'/api/v4/projects/42/repository/commits': () =>
Array.from({ length: 4 }, () => commit('Bump version')),
})
const input = commitSearch('cache', { limit: 4 })
const input = commitSearch('cache', {
limit: 4,
filters: { startDate: '2026-01-01T00:00:00Z' },
})
const page = await searchGitLab(client, {
...input,
native: {
Expand All @@ -120,7 +141,7 @@ describe('GitLab commit search', () => {
native: { provider: 'gitlab', query: 'cache', project: '..', kind: 'commits' },
})
).rejects.toThrow('Invalid GitLab project reference')
expect(requests).toEqual(['/api/v4/application/settings'])
expect(requests).toEqual([])
})

it('falls back to the listing when GitLab rejects the commit search scope', async () => {
Expand All @@ -146,8 +167,9 @@ describe('GitLab commit search', () => {
return [commit('Fix the cache eviction race')]
},
})
await searchGitLab(client, commitSearch('cache'), { ref: 'release' })
const page = await searchGitLab(client, commitSearch('cache'), { ref: 'release' })
expect(branches).toEqual(['release', 'release'])
expect(page.documents[0]?.accessMetadata).toEqual({ ref: 'release' })
})

it('refuses commit search across a group without advanced search, so the group searches its projects', async () => {
Expand Down Expand Up @@ -210,6 +232,106 @@ describe('GitLab merge request reads', () => {
]
const base = `/api/v4/projects/42/merge_requests/9`

it('shows a merge request’s diff and diff threads only within the source’s code scope', async () => {
const routes = {
[base]: () => MR,
[`${base}/discussions`]: () => [
...discussions,
{
id: 'd3',
notes: [
{
id: 4,
type: 'DiffNote',
body: 'Rotate this key',
author: { username: 'eve' },
position: { new_path: 'secrets/keys.ts', new_line: 3 },
},
],
},
{
id: 'd4',
notes: [
{
id: 5,
type: 'DiffNote',
body: 'Old secret moved here',
author: { username: 'eve' },
position: { new_path: 'src/moved.ts', old_path: 'secrets/old.ts', new_line: 1 },
},
],
},
{ id: 'd5', notes: [{ id: 6, body: 'Looks good to me', author: { username: 'ann' } }] },
],
[`${base}/diffs`]: () => [
{ new_path: 'src/cache.ts', old_path: 'src/cache.ts', diff: '+cached' },
{ new_path: 'secrets/keys.ts', old_path: 'secrets/keys.ts', diff: '+key' },
{ new_path: 'src/moved.ts', old_path: 'secrets/old.ts', diff: '+moved' },
],
}
const scoped = gitlab(routes)
const inSrc = await readGitLab(scoped.client, '9', '42', 'merge_requests', undefined, {
allows: (path) => path.startsWith('src/'),
})
expect(inSrc.content).toContain('+cached')
expect(inSrc.content).toContain('Use an LRU here')
expect(inSrc.content).toContain('2 changed files fall outside this source')
for (const hidden of ['+key', '+moved', 'Rotate this key', 'Old secret', 'secrets/'])
expect(inSrc.content).not.toContain(hidden)

const noCode = gitlab(routes)
const withoutCode = await readGitLab(
noCode.client,
'9',
'42',
'merge_requests',
undefined,
null
)
expect(withoutCode.content).not.toContain('+cached')
expect(withoutCode.content).not.toContain('Use an LRU here')
expect(noCode.requests).not.toContain(`${base}/diffs`)

const otherRef = gitlab(routes)
const release = await readGitLab(otherRef.client, '9', '42', 'merge_requests', undefined, {
allows: () => true,
ref: 'release',
})
expect(release.content).not.toContain('+cached')
expect(release.content).not.toContain('Use an LRU here')
expect(release.content).toContain('Looks good to me')
expect(otherRef.requests).not.toContain(`${base}/diffs`)
})

it('reads a commit without its diff for a source that does not serve code', async () => {
const commitPath = `/api/v4/projects/42/repository/commits/${SHA}`
const { client, requests } = gitlab({
[commitPath]: () => commit('Fix the cache race'),
[`${commitPath}/diff`]: () => [{ new_path: 'src/cache.ts', diff: '+fixed' }],
})
const document = await readGitLab(client, SHA, '42', 'commits', undefined, null)
expect(document.content).toContain('Fix the cache race')
expect(document.content).not.toContain('+fixed')
expect(requests).not.toContain(`${commitPath}/diff`)
})

it('stops reading diffs when an instance repeats a page instead of advancing', async () => {
const files = Array.from({ length: 50 }, (_, index) => ({
new_path: `src/file${index}.ts`,
old_path: `src/file${index}.ts`,
diff: `+line ${index}`,
}))
const { client, requests } = gitlab({
[base]: () => MR,
[`${base}/discussions`]: () => [],
[`${base}/diffs`]: () => files,
})
const document = await readGitLab(client, '9', '42', 'merge_requests')
expect(requests.filter((path) => path === `${base}/diffs`)).toHaveLength(2)
expect(document.content.split('### src/file0.ts')).toHaveLength(2)
expect(document.content).not.toContain('Coverage incomplete')
})

it('returns the discussion and diff, leaving out internal and system notes', async () => {
const { client } = gitlab({
'/api/v4/projects/42': () => PROJECT,
Expand Down
Loading
Loading