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
12 changes: 12 additions & 0 deletions apps/sim/connectors/gitlab/permissions.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -227,6 +227,18 @@ describe('GitLab source permission audiences', () => {
])
})

it('grants a commit to the repository audience only, withdrawn with repository access', async () => {
const commit = document('commit:4109c2d8', {})
const acls = await getGitLabDocumentAcls('test-token', config, [commit])
expect(acls['commit:4109c2d8']).toEqual([
'g:gitlab:gitlab.example.com%3A8443/42:project:42:repository',
])
sourceProject = { ...project, repository_access_level: 'disabled' }
expect(
(await getGitLabDocumentAcls('test-token', config, [commit]))['commit:4109c2d8']
).toEqual([])
})

it('rejects a project path reassigned between directory identity and permission reads', async () => {
const directory = await openGitLabDirectory('test-token', config, {})
sourceProject = { ...project, id: 43 }
Expand Down
30 changes: 20 additions & 10 deletions apps/sim/connectors/gitlab/permissions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -594,6 +594,24 @@ export async function openGitLabDirectory(
}
}

/**
* The project feature that governs each document ID prefix. Commits are live Search references the
* crawl never lists; they belong to the repository like files.
*/
const DOCUMENT_FEATURES: Record<string, Feature> = {
file: 'repository',
commit: 'repository',
merge_request: 'merge_requests',
wiki: 'wiki',
issue: 'issues',
}

function documentFeature(externalId: string): Feature | null {
const separator = externalId.indexOf(':')
const prefix = separator > 0 ? externalId.slice(0, separator) : ''
return Object.hasOwn(DOCUMENT_FEATURES, prefix) ? (DOCUMENT_FEATURES[prefix] ?? null) : null
}

/** Permissions are fetched independently from content hashes, including unchanged confidential issues. */
export async function getGitLabDocumentAcls(
token: string,
Expand All @@ -605,7 +623,7 @@ export async function getGitLabDocumentAcls(
if (csv) {
const result: Record<string, string[]> = {}
for (const doc of documents) {
const known = /^(file|wiki|issue|merge_request):/.test(doc.externalId)
const known = documentFeature(doc.externalId) !== null
const excluded =
doc.skippedReason ||
(doc.externalId.startsWith('issue:') && doc.metadata?.confidential !== false)
Expand All @@ -628,15 +646,7 @@ export async function getGitLabDocumentAcls(
)
const result: Record<string, string[]> = {}
for (const doc of documents) {
const feature = doc.externalId.startsWith('file:')
? 'repository'
: doc.externalId.startsWith('merge_request:')
? 'merge_requests'
: doc.externalId.startsWith('wiki:')
? 'wiki'
: doc.externalId.startsWith('issue:')
? 'issues'
: null
const feature = documentFeature(doc.externalId)
if (
!feature ||
!['enabled', 'private'].includes(accessLevel(state.project, feature) ?? '') ||
Expand Down
5 changes: 4 additions & 1 deletion apps/sim/lib/api/contracts/mothership-assistant-tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,16 @@ export const MAX_NATIVE_QUERIES_PER_ACCOUNT = 4
*/
const PROVIDER_KIND_SCHEMAS = {
github: z.enum(['issues', 'code', 'repositories', 'commits']),
gitlab: z.enum(['issues', 'code', 'merge_requests', 'wiki']),
gitlab: z.enum(['issues', 'code', 'merge_requests', 'wiki', 'commits']),
Comment thread
waleedlatif1 marked this conversation as resolved.
Resolved
hubspot: z.enum(['contacts', 'companies', 'deals', 'tickets']),
lucid: z.enum(['lucidchart', 'lucidspark']),
google_meet: z.enum(['transcript', 'smart_notes']),
zoom: z.enum(['meeting']),
} as const

/** A collection one GitLab search selects. */
export type GitLabSearchKind = z.output<typeof PROVIDER_KIND_SCHEMAS.gitlab>

function hasSearchKinds(
provider: LiveSearchProvider
): provider is keyof typeof PROVIDER_KIND_SCHEMAS {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ describe.skipIf(!fixtureFile)('federated self-hosted GitLab Search', () => {
let connectorId: string
let issueIid: number
let confidentialIid: number
let mergeRequestIid: number
let sourceRevision: number
const people: Record<string, FixturePerson> = {}
const providerUserIds: number[] = []
Expand Down Expand Up @@ -100,7 +101,10 @@ describe.skipIf(!fixtureFile)('federated self-hosted GitLab Search', () => {
throw new Error('Disposable GitLab membership did not converge')
}

function search(person: FixturePerson, kind: 'issues' | 'code' | 'wiki' | 'merge_requests') {
function search(
person: FixturePerson,
kind: 'issues' | 'code' | 'wiki' | 'merge_requests' | 'commits'
) {
return searchLiveKnowledge.execute({
principal: principal(person),
input: {
Expand Down Expand Up @@ -226,7 +230,7 @@ describe.skipIf(!fixtureFile)('federated self-hosted GitLab Search', () => {
await api(`/projects/${projectId}/repository/files/fixture.md`, 'POST', {
branch: 'main',
content: `${QUERY} repository content.`,
commit_message: 'Create disposable federated fixture',
commit_message: `${QUERY} create disposable federated fixture`,
})
await api(`/projects/${projectId}/wikis`, 'POST', {
title: `${QUERY} wiki`,
Expand Down Expand Up @@ -255,11 +259,20 @@ describe.skipIf(!fixtureFile)('federated self-hosted GitLab Search', () => {
content: `${QUERY} proposed content.`,
commit_message: 'Update disposable federated fixture',
})
await api(`/projects/${projectId}/merge_requests`, 'POST', {
source_branch: 'fixture-change',
target_branch: 'main',
title: `${QUERY} merge request`,
description: `${QUERY} proposed content.`,
mergeRequestIid = (
await api<{ iid: number }>(`/projects/${projectId}/merge_requests`, 'POST', {
source_branch: 'fixture-change',
target_branch: 'main',
title: `${QUERY} merge request`,
description: `${QUERY} proposed content.`,
})
).iid
await api(`/projects/${projectId}/merge_requests/${mergeRequestIid}/notes`, 'POST', {
body: 'Reviewed: ship it',
})
await api(`/projects/${projectId}/merge_requests/${mergeRequestIid}/notes`, 'POST', {
body: 'Internal: hold for the security review',
internal: true,
})
await db.insert(organizationSearchIntegration).values({
organizationId: ids.organizationId,
Expand Down Expand Up @@ -300,7 +313,7 @@ describe.skipIf(!fixtureFile)('federated self-hosted GitLab Search', () => {
for (const result of cleanup) if (result.status === 'rejected') throw result.reason
}, 120_000)

it.each(['issues', 'code', 'wiki', 'merge_requests'] as const)(
it.each(['issues', 'code', 'wiki', 'merge_requests', 'commits'] as const)(
'searches and reads %s from the configured HTTPS instance with current permissions',
async (kind) => {
const result = await search(people.reporter!, kind)
Expand All @@ -324,6 +337,22 @@ describe.skipIf(!fixtureFile)('federated self-hosted GitLab Search', () => {
120_000
)

it('reads a merge request with its review discussion and diff, without internal notes', async () => {
const reporter = people.reporter
if (!reporter) throw new Error('Expected the reporter fixture')
const row = (await search(reporter, 'merge_requests')).results.find(
(result) => decodeLiveReference(result.documentId).id === String(mergeRequestIid)
)
if (!row) throw new Error('Expected the fixture merge request')
const content = (await read(reporter, row.documentId)).chunks
.map((chunk) => chunk.content)
.join('\n')
expect(content).toContain('Reviewed: ship it')
expect(content).toContain('### fixture.md (modified)')
expect(content).toContain(`+${QUERY} proposed content.`)
expect(content).not.toContain('security review')
}, 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
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ export const MAX_NATIVE_QUERIES_PER_ACCOUNT = 4
*/
const PROVIDER_KIND_SCHEMAS = {
github: z.enum(['issues', 'code', 'repositories', 'commits']),
gitlab: z.enum(['issues', 'code', 'merge_requests', 'wiki']),
gitlab: z.enum(['issues', 'code', 'merge_requests', 'wiki', 'commits']),
hubspot: z.enum(['contacts', 'companies', 'deals', 'tickets']),
lucid: z.enum(['lucidchart', 'lucidspark']),
google_meet: z.enum(['transcript', 'smart_notes']),
Expand Down
11 changes: 9 additions & 2 deletions apps/sim/lib/sim-search/live/github.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,14 @@ import {
nativeText,
} from '@/lib/sim-search/live/dates'
import { readDiscussionSection } from '@/lib/sim-search/live/discussion'
import { array, NativeSearchError, object, segment, string } from '@/lib/sim-search/live/http'
import {
array,
isCommitSha,
NativeSearchError,
object,
segment,
string,
} from '@/lib/sim-search/live/http'
import { collectNativePages, joinMessages } from '@/lib/sim-search/live/pages'
import type {
NativeClient,
Expand Down Expand Up @@ -460,7 +467,7 @@ export async function readGitHub(
return githubDocument(row, 'repositories')
}
if (kind === 'commits') {
if (!/^[0-9a-f]{7,40}$/i.test(id))
if (!isCommitSha(id))
throw new NativeSearchError('unavailable', 'Invalid GitHub commit reference.')
/** Each changed file carries its patch, so the page bounds the response size. */
const row = object(
Expand Down
56 changes: 54 additions & 2 deletions apps/sim/lib/sim-search/live/gitlab-admin.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
createAdminGitLabSession,
listAdminGitLabAccounts,
} from '@/lib/sim-search/live/gitlab-admin'
import { NativeSearchError } from '@/lib/sim-search/live/http'
import {
gitLabCsvGroupToken,
setGitLabCsvContext,
Expand Down Expand Up @@ -38,7 +39,8 @@ vi.mock('@/connectors/gitlab/permissions', () => ({
getGitLabDocumentAcls: mocks.acl,
validateGitLabCsvToken: mocks.csv,
}))
vi.mock('@/lib/sim-search/live/gitlab', () => ({
vi.mock('@/lib/sim-search/live/gitlab', async (importOriginal) => ({
...(await importOriginal<typeof import('@/lib/sim-search/live/gitlab')>()),
searchGitLab: mocks.search,
readGitLab: mocks.read,
}))
Expand All @@ -55,7 +57,7 @@ const grant = groupToken({
groupId: 'repository',
})!
const client = { json: vi.fn(), text: vi.fn(), bytes: vi.fn() }
const session = (config = source.config) =>
const session = (config: Record<string, unknown> = source.config) =>
createAdminGitLabSession({
owner: { organizationId: 'org' },
userId: 'reader',
Expand Down Expand Up @@ -171,6 +173,56 @@ describe('administrator-managed live GitLab authorization', () => {
)
expect(mocks.acl).toHaveBeenCalledTimes(2)
})
it('serves a commit only from the history of the ref a source is limited to, under the repository ACL', async () => {
const sha = '4109c2d872d5fdb1ed057400d103766aaea97f98'
const commit = { id: sha, container: '42', kind: 'commits' }
const current = await session({ ...source.config, ref: 'v1.2.0' })
client.json.mockResolvedValue({ id: 'aaaaaaa1aaaaaaa1aaaaaaa1aaaaaaa1aaaaaaa1' })
expect(await current.verify(commit)).toBe(false)
client.json.mockRejectedValue(new NativeSearchError('unavailable', 'Unrelated', undefined, 400))
expect(await current.verify(commit)).toBe(false)
expect(mocks.acl).not.toHaveBeenCalled()
client.json.mockResolvedValue({ id: sha })
expect(await current.verify(commit)).toBe(true)
await current.search({
query: 'fix',
limit: 10,
scopes: [],
native: { provider: 'gitlab', query: 'fix', kind: 'commits' },
})
expect(mocks.search).toHaveBeenCalledWith(client, expect.any(Object), { ref: 'v1.2.0' })
expect(mocks.acl).toHaveBeenCalledWith(
'admin-token',
expect.any(Object),
[expect.objectContaining({ externalId: `commit:${sha}` })],
expect.any(Object)
)
})
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)
await current.search({
query: 'fix',
limit: 10,
scopes: [],
native: { provider: 'gitlab', query: 'fix', kind: 'commits' },
})
expect(mocks.search).not.toHaveBeenCalled()
})
it('searches commits only when asked, as a search without a source does', async () => {
mocks.search.mockImplementation(async (_client, input) => ({
documents: [
{ id: '1', container: '42', kind: input.native.kind, title: '', url: '', content: '' },
],
}))
const page = await (await session()).search({ query: 'fix', limit: 10, scopes: [] })
expect(page.documents.map((document) => document.kind).sort()).toEqual([
'code',
'issues',
'merge_requests',
'wiki',
])
Comment thread
waleedlatif1 marked this conversation as resolved.
Resolved
})
it('propagates the caller deadline into the canonical permission directory', async () => {
await session()
expect(mocks.directory).toHaveBeenCalledWith(
Expand Down
Loading
Loading