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
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { getGitLabOAuthCredentials } from '@/lib/integrations/platforms/gitlab/o
jest.mock('@/lib/user/server');
jest.mock('@/lib/drizzle', () => ({ db: {} }));
jest.mock('@/lib/integrations/gitlab-service', () => ({
normalizeInstanceUrl: jest.fn(),
instanceUrlChanged: jest.fn(),
}));
jest.mock('@/routers/organizations/utils', () => ({
ensureOrganizationAccess: jest.fn(),
Expand Down Expand Up @@ -164,11 +164,11 @@ describe('GET /api/integrations/gitlab/callback', () => {
expect(mockedExchangeGitLabOAuthCode).not.toHaveBeenCalled();
});

test('rejects signed state with an unsafe instance URL before exchanging an OAuth code', async () => {
test('rejects signed state with an http instance URL before exchanging an OAuth code', async () => {
const state = createGitLabOAuthState(
{
owner: { type: 'user', id: USER_ID },
instanceUrl: 'http://127.0.0.1:8080',
instanceUrl: 'http://gitlab.example.com',
customCredentialsRef: 'cached-credentials-ref',
},
USER_ID
Expand All @@ -180,7 +180,7 @@ describe('GET /api/integrations/gitlab/callback', () => {
)
);

expectRedirectLocation(response, '/integrations/gitlab?error=connection_failed');
expectRedirectLocation(response, '/integrations?error=invalid_state');
expect(mockedGetGitLabOAuthCredentials).not.toHaveBeenCalled();
expect(mockedExchangeGitLabOAuthCode).not.toHaveBeenCalled();
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -181,10 +181,10 @@ describe('GET /api/integrations/gitlab/connect', () => {
expect(responseBody.url).toBe('https://gitlab.com/oauth/authorize?state=signed');
});

test('does not initialize self-hosted OAuth for unsafe instance URLs', async () => {
test('does not initialize self-hosted OAuth for http instance URLs', async () => {
const response = await callGitLabConnectPost(
makeJsonRequest('/api/integrations/gitlab/connect', {
instanceUrl: 'http://127.0.0.1:8080',
instanceUrl: 'http://gitlab.example.com',
clientId: 'client-id',
clientSecret: 'client-secret',
})
Expand Down
30 changes: 24 additions & 6 deletions apps/web/src/lib/integrations/gitlab-service.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { normalizeInstanceUrl } from './gitlab-service';
import { instanceUrlChanged, normalizeInstanceUrl } from './gitlab-service';

describe('normalizeInstanceUrl', () => {
it('treats undefined as gitlab.com', () => {
Expand All @@ -24,8 +24,10 @@ describe('normalizeInstanceUrl', () => {
expect(normalizeInstanceUrl('https://gitlab.com')).toBe('https://gitlab.com');
});

it('preserves self-hosted URLs', () => {
expect(normalizeInstanceUrl('http://selfhosted.test:3123')).toBe('http://selfhosted.test:3123');
it('preserves https self-hosted URLs', () => {
expect(normalizeInstanceUrl('https://selfhosted.test:3123')).toBe(
'https://selfhosted.test:3123'
);
});

it('preserves self-hosted base paths', () => {
Expand All @@ -34,6 +36,10 @@ describe('normalizeInstanceUrl', () => {
);
});

it('rejects http self-hosted URLs', () => {
expect(() => normalizeInstanceUrl('http://selfhosted.test:3123')).toThrow('must use https');
});

it('rejects unsafe self-hosted URLs', () => {
expect(() => normalizeInstanceUrl('http://127.0.0.1:8080')).toThrow('host is not allowed');
});
Expand All @@ -44,12 +50,24 @@ describe('normalizeInstanceUrl', () => {

// different instances
expect(normalizeInstanceUrl('https://gitlab.com')).not.toBe(
normalizeInstanceUrl('http://selfhosted.test:3123')
normalizeInstanceUrl('https://selfhosted.test:3123')
);

// same self-hosted instance with trailing slash difference
expect(normalizeInstanceUrl('http://selfhosted.test:3123/')).toBe(
normalizeInstanceUrl('http://selfhosted.test:3123')
expect(normalizeInstanceUrl('https://selfhosted.test:3123/')).toBe(
normalizeInstanceUrl('https://selfhosted.test:3123')
);
});

it('treats a legacy http URL as changed when reconnecting with https', () => {
expect(instanceUrlChanged('http://selfhosted.test:3123', 'https://selfhosted.test:3123')).toBe(
true
);
});

it('still rejects a new http URL when checking for an instance change', () => {
expect(() =>
instanceUrlChanged('https://selfhosted.test:3123', 'http://selfhosted.test:3123')
).toThrow('must use https');
});
});
9 changes: 7 additions & 2 deletions apps/web/src/lib/integrations/gitlab-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,8 +53,13 @@ export function normalizeInstanceUrl(url?: string): string {
* Returns true if the GitLab instance URL has changed between
* the existing integration and the new connection.
*/
function instanceUrlChanged(existingUrl?: string, newUrl?: string): boolean {
return normalizeInstanceUrl(existingUrl) !== normalizeInstanceUrl(newUrl);
export function instanceUrlChanged(existingUrl: string | undefined, newUrl: string): boolean {
const normalizedNewUrl = normalizeInstanceUrl(newUrl);
try {
return normalizeInstanceUrl(existingUrl) !== normalizedNewUrl;
} catch {
return true;
}
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import {
fetchGitLabProjects,
calculateTokenExpiry,
} from '@/lib/integrations/platforms/gitlab/adapter';
import { normalizeInstanceUrl } from '@/lib/integrations/gitlab-service';
import { instanceUrlChanged } from '@/lib/integrations/gitlab-service';
import {
isDefaultGitLabInstanceUrl,
normalizeGitLabInstanceUrl,
Expand Down Expand Up @@ -187,8 +187,10 @@ export async function handleGitLabOAuthCallback(request: NextRequest) {
// Detect if the GitLab instance URL changed (e.g. gitlab.com -> self-hosted)
const isInstanceChange =
existing !== undefined &&
normalizeInstanceUrl(existingMetadata?.gitlab_instance_url as string | undefined) !==
normalizeInstanceUrl(normalizedInstanceUrl);
instanceUrlChanged(
existingMetadata?.gitlab_instance_url as string | undefined,
normalizedInstanceUrl
);

const webhookSecret = isInstanceChange
? generateWebhookSecret()
Expand Down
19 changes: 19 additions & 0 deletions apps/web/src/lib/integrations/platforms/gitlab/adapter.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -350,6 +350,15 @@ describe('validateGitLabInstance', () => {
expect(mockFetch).not.toHaveBeenCalled();
});

it('should return invalid for http instances before fetching', async () => {
const result = await validateGitLabInstance('http://gitlab.example.com');

expect(result.valid).toBe(false);
expect(result.error).toContain('must use https');
expect(mockLookup).not.toHaveBeenCalled();
expect(mockFetch).not.toHaveBeenCalled();
});

it('should return invalid for unsafe hosts before fetching', async () => {
const result = await validateGitLabInstance('http://127.0.0.1:8080');

Expand Down Expand Up @@ -871,6 +880,16 @@ describe('validatePersonalAccessToken', () => {
mockFetch.mockReset();
});

it('rejects http instance URLs before fetching', async () => {
const result = await validatePersonalAccessToken('pat-token', 'http://gitlab.example.com');

expect(result).toEqual({
valid: false,
error: 'Invalid URL protocol. GitLab instance URLs must use https.',
});
expect(mockFetch).not.toHaveBeenCalled();
});

it('rejects unsafe instance URLs before fetching', async () => {
const result = await validatePersonalAccessToken('pat-token', 'http://169.254.169.254');

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ describe('GitLab instance URL safety', () => {

it.each([
['ftp://gitlab.example.com', 'Invalid URL protocol'],
['http://gitlab.example.com', 'must use https'],
[urlWithCredentials.toString(), 'must not include credentials'],
['https://gitlab.example.com?next=/api', 'must not include query strings'],
['https://gitlab.example.com#fragment', 'must not include query strings'],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,10 @@ export function normalizeGitLabInstanceUrl(instanceUrl?: string): string {
throw new GitLabInstanceUrlError('GitLab instance URL host is not allowed.');
}

if (url.protocol !== 'https:') {
throw new GitLabInstanceUrlError('Invalid URL protocol. GitLab instance URLs must use https.');
}

const path = normalizeBasePath(url.pathname);
return `${url.protocol}//${url.host.toLowerCase()}${path}`;
}
Expand Down
12 changes: 12 additions & 0 deletions apps/web/src/lib/integrations/platforms/gitlab/oauth-state.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,18 @@ describe('gitlab oauth state', () => {
});
});

test('rejects signed state for an http instance URL', () => {
const state = createGitLabOAuthState(
{
owner: { type: 'user', id: 'user_123' },
instanceUrl: 'http://gitlab.example.com',
},
'user_123'
);

expect(verifyGitLabOAuthState(state)).toBeNull();
});

test('round-trips a validated return path', () => {
const state = createGitLabOAuthState(
{
Expand Down
7 changes: 3 additions & 4 deletions apps/web/src/lib/integrations/platforms/gitlab/oauth-state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,9 @@ const GITLAB_OAUTH_STATE_PREFIX = 'gitlab:';

export const DEFAULT_GITLAB_OAUTH_INSTANCE_URL = 'https://gitlab.com';

function isHttpInstanceUrl(value: string): boolean {
function isHttpsInstanceUrl(value: string): boolean {
try {
const protocol = new URL(value).protocol;
return protocol === 'http:' || protocol === 'https:';
return new URL(value).protocol === 'https:';
} catch {
return false;
}
Expand All @@ -22,7 +21,7 @@ const GitLabOAuthStatePayloadSchema = z.object({
z.object({ type: z.literal('user'), id: z.string().min(1) }),
z.object({ type: z.literal('org'), id: z.string().min(1) }),
]),
instanceUrl: z.string().url().refine(isHttpInstanceUrl).optional(),
instanceUrl: z.string().url().refine(isHttpsInstanceUrl).optional(),
customCredentialsRef: z.string().min(1).optional(),
returnTo: z
.string()
Expand Down
2 changes: 2 additions & 0 deletions services/git-token-service/.dev.vars.example
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ USER_GITHUB_APP_TOKEN_ACTIVE_PRIVATE_KEY=
# @from NEXTAUTH_SECRET
# Short-lived user-token verification for POST /internal/github-user-authorizations/disconnect
NEXTAUTH_SECRET=
# Dedicated 32-byte base64 AES-GCM key for short-lived SCM session capabilities
SCM_SESSION_CAPABILITY_ENCRYPTION_KEY=

# GitHub Lite App credentials (for OSS organizations with read-only permissions)
# Same format as standard app credentials above
Expand Down
Loading