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
136 changes: 136 additions & 0 deletions packages/backend/src/gerrit.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@

import { expect, test, vi, describe, beforeEach } from 'vitest';
import { getGerritReposFromConfig } from './gerrit';
import fetch from 'cross-fetch';

vi.mock('cross-fetch', () => {
return {
default: vi.fn(),
};
});

vi.mock('@sourcebot/shared', () => ({
createLogger: () => ({
debug: vi.fn(),
info: vi.fn(),
warn: vi.fn(),
error: vi.fn(),
}),
}));

vi.mock('./utils', () => ({
measure: async (fn: () => any) => {
const data = await fn();
return { durationMs: 0, data };
},
fetchWithRetry: async (fn: () => any) => fn(),
}));

describe('getGerritReposFromConfig', () => {
beforeEach(() => {
vi.clearAllMocks();
});

test('sends Basic Auth header when username and password are provided', async () => {
const mockFetch = fetch as unknown as ReturnType<typeof vi.fn>;
mockFetch.mockResolvedValue({
ok: true,
text: async () => '[]',
json: async () => ([]),
});

const config = {
type: 'gerrit' as const,
url: 'https://gerrit.example.com',
username: 'user',
password: 'password',
};

await getGerritReposFromConfig(config);

const expectedToken = Buffer.from('user:password').toString('base64');
expect(mockFetch).toHaveBeenCalledWith(
expect.stringContaining('https://gerrit.example.com/projects/?S=0'),
expect.objectContaining({
headers: {
Authorization: `Basic ${expectedToken}`,
},
})
);
});

test('does not send Authorization header when credentials are missing', async () => {
const mockFetch = fetch as unknown as ReturnType<typeof vi.fn>;
mockFetch.mockResolvedValue({
ok: true,
text: async () => '[]',
json: async () => ([]),
});

const config = {
type: 'gerrit' as const,
url: 'https://gerrit.example.com',
};

await getGerritReposFromConfig(config);

expect(mockFetch).toHaveBeenCalledWith(
expect.stringContaining('https://gerrit.example.com/projects/?S=0'),
expect.objectContaining({
headers: {},
})
);
});

test('does not send Authorization header when only one credential is provided', async () => {
const mockFetch = fetch as unknown as ReturnType<typeof vi.fn>;
mockFetch.mockResolvedValue({
ok: true,
text: async () => '[]',
json: async () => ([]),
});

const config = {
type: 'gerrit' as const,
url: 'https://gerrit.example.com',
username: 'user',
};

await getGerritReposFromConfig(config);

expect(mockFetch).toHaveBeenCalledWith(
expect.stringContaining('https://gerrit.example.com/projects/?S=0'),
expect.objectContaining({
headers: {},
})
);
});

test('correctly encodes credentials with special characters', async () => {
const mockFetch = fetch as unknown as ReturnType<typeof vi.fn>;
mockFetch.mockResolvedValue({
ok: true,
text: async () => '[]',
json: async () => ([]),
});

const config = {
type: 'gerrit' as const,
url: 'https://gerrit.example.com',
username: '[email protected]',
password: 'p@ss:w0rd',
};

await getGerritReposFromConfig(config);

const expectedToken = Buffer.from('[email protected]:p@ss:w0rd').toString('base64');
expect(mockFetch).toHaveBeenCalledWith(
expect.stringContaining('https://gerrit.example.com/projects/?S=0'),
expect.objectContaining({
headers: {
Authorization: `Basic ${expectedToken}`,
},
})
);
});
});
12 changes: 9 additions & 3 deletions packages/backend/src/gerrit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ export const getGerritReposFromConfig = async (config: GerritConnectionConfig):
const url = config.url.endsWith('/') ? config.url : `${config.url}/`;

let { durationMs, data: projects } = await measure(async () => {
const fetchFn = () => fetchAllProjects(url);
const fetchFn = () => fetchAllProjects(url, config.username, config.password);
return fetchWithRetry(fetchFn, `projects from ${url}`, logger);
});

Expand All @@ -61,7 +61,7 @@ export const getGerritReposFromConfig = async (config: GerritConnectionConfig):
return projects;
};

const fetchAllProjects = async (url: string): Promise<GerritProject[]> => {
const fetchAllProjects = async (url: string, username?: string, password?: string): Promise<GerritProject[]> => {
const projectsEndpoint = `${url}projects/`;
let allProjects: GerritProject[] = [];
let start = 0; // Start offset for pagination
Expand All @@ -71,8 +71,14 @@ const fetchAllProjects = async (url: string): Promise<GerritProject[]> => {
const endpointWithParams = `${projectsEndpoint}?S=${start}`;
logger.debug(`Fetching projects from Gerrit at ${endpointWithParams}`);

const headers: Record<string, string> = {};
if (username && password) {
const token = Buffer.from(`${username}:${password}`).toString('base64');
headers['Authorization'] = `Basic ${token}`;
}

let response: Response;
response = await fetch(endpointWithParams);
response = await fetch(endpointWithParams, { headers });
if (!response.ok) {
throw new Error(`Failed to fetch projects from Gerrit at ${endpointWithParams} with status ${response.status}`);
}
Expand Down
8 changes: 8 additions & 0 deletions schemas/v3/gerrit.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,14 @@
],
"pattern": "^https?:\\/\\/[^\\s/$.?#].[^\\s]*$"
},
"username": {
"type": "string",
"description": "The username to use for authentication."
},
"password": {
"type": "string",
"description": "The password (or HTTP password) to use for authentication."
},
"projects": {
"type": "array",
"items": {
Expand Down