Skip to content

πŸ™Œ OpenHands: AI-Driven Development

feat(enterprise): Self hosted gitlab support (#14141)

Joe Laverty4e63531fa659
diff --git a/enterprise/server/auth/constants.py b/enterprise/server/auth/constants.py
index 20240a6cdc..8ae721833a 100644
--- a/enterprise/server/auth/constants.py
+++ b/enterprise/server/auth/constants.py
@@ -1,5 +1,7 @@
import os
+from openhands.integrations.gitlab.constants import GITLAB_HOST
+
GITHUB_APP_CLIENT_ID = os.getenv('GITHUB_APP_CLIENT_ID', '').strip()
GITHUB_APP_CLIENT_SECRET = os.getenv('GITHUB_APP_CLIENT_SECRET', '').strip()
GITHUB_APP_WEBHOOK_SECRET = os.getenv('GITHUB_APP_WEBHOOK_SECRET', '')
@@ -14,6 +16,7 @@ KEYCLOAK_SERVER_URL_EXT = os.getenv(
KEYCLOAK_ADMIN_PASSWORD = os.getenv('KEYCLOAK_ADMIN_PASSWORD', '')
GITLAB_APP_CLIENT_ID = os.getenv('GITLAB_APP_CLIENT_ID', '').strip()
GITLAB_APP_CLIENT_SECRET = os.getenv('GITLAB_APP_CLIENT_SECRET', '').strip()
+GITLAB_TOKEN_URL = f'https://{GITLAB_HOST}/oauth/token'
BITBUCKET_APP_CLIENT_ID = os.getenv('BITBUCKET_APP_CLIENT_ID', '').strip()
BITBUCKET_APP_CLIENT_SECRET = os.getenv('BITBUCKET_APP_CLIENT_SECRET', '').strip()
ENABLE_ENTERPRISE_SSO = os.getenv('ENABLE_ENTERPRISE_SSO', '').strip()
diff --git a/enterprise/server/auth/token_manager.py b/enterprise/server/auth/token_manager.py
index e409d62c1a..478fc7665c 100644
--- a/enterprise/server/auth/token_manager.py
+++ b/enterprise/server/auth/token_manager.py
@@ -30,6 +30,7 @@ from server.auth.constants import (
GITHUB_APP_CLIENT_SECRET,
GITLAB_APP_CLIENT_ID,
GITLAB_APP_CLIENT_SECRET,
+ GITLAB_TOKEN_URL,
KEYCLOAK_REALM_NAME,
KEYCLOAK_SERVER_URL,
KEYCLOAK_SERVER_URL_EXT,
@@ -417,7 +418,7 @@ class TokenManager:
return await self._parse_refresh_response(data)
async def _refresh_gitlab_token(self, refresh_token: str) -> dict[str, str | int]:
- url = 'https://gitlab.com/oauth/token'
+ url = GITLAB_TOKEN_URL
logger.info(f'Refreshing GitLab token with URL: {url}')
payload = {
diff --git a/enterprise/tests/unit/integrations/gitlab/test_gitlab_service.py b/enterprise/tests/unit/integrations/gitlab/test_gitlab_service.py
index 1f479f9312..ae95840f4f 100644
--- a/enterprise/tests/unit/integrations/gitlab/test_gitlab_service.py
+++ b/enterprise/tests/unit/integrations/gitlab/test_gitlab_service.py
@@ -12,6 +12,16 @@ def gitlab_service():
return SaaSGitLabService(external_auth_id='test_user_id')
+class TestSaaSGitLabServiceInit:
+ """Tests for SaaSGitLabService __init__."""
+
+ def test_explicit_base_domain_overrides_default(self):
+ """An explicit base_domain parameter overrides the upstream class default."""
+ service = SaaSGitLabService(external_auth_id='u1', base_domain='other.host')
+
+ assert service.BASE_URL == 'https://other.host/api/v4'
+
+
class TestGetUserResourcesWithAdminAccess:
"""Test cases for get_user_resources_with_admin_access method."""
diff --git a/frontend/__tests__/components/features/chat/git-control-bar-repo-button.test.tsx b/frontend/__tests__/components/features/chat/git-control-bar-repo-button.test.tsx
index 5a6d15e84b..3111f2e292 100644
--- a/frontend/__tests__/components/features/chat/git-control-bar-repo-button.test.tsx
+++ b/frontend/__tests__/components/features/chat/git-control-bar-repo-button.test.tsx
@@ -32,8 +32,8 @@ vi.mock("#/icons/repo-forked.svg?react", () => ({
default: () => <span data-testid="repo-forked-icon">forked</span>,
}));
-vi.mock("#/hooks/query/use-settings", () => ({
- useSettings: () => ({ data: { provider_tokens_set: {} } }),
+vi.mock("#/hooks/use-provider-host", () => ({
+ useProviderHost: () => null,
}));
// Mock constructRepositoryUrl
diff --git a/frontend/src/api/option-service/option.types.ts b/frontend/src/api/option-service/option.types.ts
index fa93a249ca..9bdb4d28e3 100644
--- a/frontend/src/api/option-service/option.types.ts
+++ b/frontend/src/api/option-service/option.types.ts
@@ -44,5 +44,6 @@ export interface WebClientConfig {
updated_at: string;
github_app_slug: string | null;
gitlab_enabled?: boolean;
+ provider_default_hosts?: Partial<Record<Provider, string>>;
slack_enabled?: boolean;
}
diff --git a/frontend/src/components/features/chat/git-control-bar-branch-button.tsx b/frontend/src/components/features/chat/git-control-bar-branch-button.tsx
index e873da3735..3ba81ee11a 100644
--- a/frontend/src/components/features/chat/git-control-bar-branch-button.tsx
+++ b/frontend/src/components/features/chat/git-control-bar-branch-button.tsx
@@ -4,7 +4,7 @@ import { constructBranchUrl, cn } from "#/utils/utils";
import { Provider } from "#/types/settings";
import { I18nKey } from "#/i18n/declaration";
import { GitExternalLinkIcon } from "./git-external-link-icon";
-import { useSettings } from "#/hooks/query/use-settings";
+import { useProviderHost } from "#/hooks/use-provider-host";
interface GitControlBarBranchButtonProps {
selectedBranch: string | null | undefined;
@@ -18,11 +18,7 @@ export function GitControlBarBranchButton({
gitProvider,
}: GitControlBarBranchButtonProps) {
const { t } = useTranslation();
- const { data: settings } = useSettings();
-
- const providerHost = gitProvider
- ? settings?.provider_tokens_set[gitProvider]
- : null;
+ const providerHost = useProviderHost(gitProvider);
const hasBranch = selectedBranch && selectedRepository && gitProvider;
const branchUrl = hasBranch
diff --git a/frontend/src/components/features/chat/git-control-bar-repo-button.tsx b/frontend/src/components/features/chat/git-control-bar-repo-button.tsx
index fcc2f7fb5f..04de23024c 100644
--- a/frontend/src/components/features/chat/git-control-bar-repo-button.tsx
+++ b/frontend/src/components/features/chat/git-control-bar-repo-button.tsx
@@ -5,7 +5,7 @@ import { I18nKey } from "#/i18n/declaration";
import { GitProviderIcon } from "#/components/shared/git-provider-icon";
import { GitExternalLinkIcon } from "./git-external-link-icon";
import RepoForkedIcon from "#/icons/repo-forked.svg?react";
-import { useSettings } from "#/hooks/query/use-settings";
+import { useProviderHost } from "#/hooks/use-provider-host";
interface GitControlBarRepoButtonProps {
selectedRepository: string | null | undefined;
@@ -21,15 +21,10 @@ export function GitControlBarRepoButton({
disabled,
}: GitControlBarRepoButtonProps) {
const { t } = useTranslation();
- const { data: settings } = useSettings();
+ const providerHost = useProviderHost(gitProvider);
const hasRepository = selectedRepository && gitProvider;
- // Get the host for the current provider from settings
- const providerHost = gitProvider
- ? settings?.provider_tokens_set[gitProvider]
- : null;
-
const repositoryUrl = hasRepository
? constructRepositoryUrl(gitProvider, selectedRepository, providerHost)
: undefined;
diff --git a/frontend/src/hooks/use-provider-host.ts b/frontend/src/hooks/use-provider-host.ts
new file mode 100644
index 0000000000..0cbfbc5d67
--- /dev/null
+++ b/frontend/src/hooks/use-provider-host.ts
@@ -0,0 +1,21 @@
+import { useConfig } from "#/hooks/query/use-config";
+import { useSettings } from "#/hooks/query/use-settings";
+import { Provider } from "#/types/settings";
+
+/**
+ * Resolve the effective host for a git provider: a per-token override from
+ * user settings if present, otherwise the deployment-wide default from the
+ * web client config, otherwise null.
+ */
+export const useProviderHost = (
+ provider: Provider | null | undefined,
+): string | null => {
+ const { data: settings } = useSettings();
+ const { data: config } = useConfig();
+ if (!provider) return null;
+ return (
+ settings?.provider_tokens_set[provider] ||
+ config?.provider_default_hosts?.[provider] ||
+ null
+ );
+};
diff --git a/frontend/src/mocks/settings-handlers.ts b/frontend/src/mocks/settings-handlers.ts
index a718925692..3bff9b60cb 100644
--- a/frontend/src/mocks/settings-handlers.ts
+++ b/frontend/src/mocks/settings-handlers.ts
@@ -63,6 +63,13 @@ export const createMockWebClientConfig = (
updated_at: new Date().toISOString(),
github_app_slug: null,
gitlab_enabled: false,
+ provider_default_hosts: {
+ github: "github.com",
+ gitlab: "gitlab.com",
+ bitbucket: "bitbucket.org",
+ azure_devops: "dev.azure.com",
+ forgejo: "codeberg.org",
+ },
slack_enabled: false,
...overrides,
});
@@ -428,6 +435,13 @@ export const SETTINGS_HANDLERS = [
updated_at: new Date().toISOString(),
github_app_slug: mockSaas ? "openhands" : null,
gitlab_enabled: false,
+ provider_default_hosts: {
+ github: "github.com",
+ gitlab: "gitlab.com",
+ bitbucket: "bitbucket.org",
+ azure_devops: "dev.azure.com",
+ forgejo: "codeberg.org",
+ },
slack_enabled: false,
};
diff --git a/frontend/src/utils/utils.ts b/frontend/src/utils/utils.ts
index 0efdb09ad1..48248c2a44 100644
--- a/frontend/src/utils/utils.ts
+++ b/frontend/src/utils/utils.ts
@@ -182,32 +182,9 @@ export const shouldUseInstallationRepos = (
}
};
-export const getGitProviderBaseUrl = (
- gitProvider: Provider,
- host?: string | null,
-): string => {
- // If custom host provided, use it (with https:// prefix if needed)
- if (host && host.trim() !== "") {
- return host.startsWith("http") ? host : `https://${host}`;
- }
-
- // Fall back to defaults
- switch (gitProvider) {
- case "github":
- return "https://github.com";
- case "gitlab":
- return "https://gitlab.com";
- case "bitbucket":
- return "https://bitbucket.org";
- case "azure_devops":
- return "https://dev.azure.com";
- case "forgejo":
- // Default UI links to Codeberg unless a custom host is available in settings
- // Note: UI link builders don't currently receive host; consider plumbing settings if needed
- return "https://codeberg.org";
- default:
- return "";
- }
+export const ensureHttpsPrefix = (host?: string | null): string => {
+ if (!host || host.trim() === "") return "";
+ return host.startsWith("http") ? host : `https://${host}`;
};
/**
@@ -258,7 +235,7 @@ export const constructPullRequestUrl = (
repositoryName: string,
host?: string | null,
): string => {
- const baseUrl = getGitProviderBaseUrl(provider, host);
+ const baseUrl = ensureHttpsPrefix(host);
switch (provider) {
case "github":
@@ -308,7 +285,7 @@ export const constructMicroagentUrl = (
microagentPath: string,
host?: string | null,
): string => {
- const baseUrl = getGitProviderBaseUrl(gitProvider, host);
+ const baseUrl = ensureHttpsPrefix(host);
switch (gitProvider) {
case "github":
@@ -372,7 +349,7 @@ export const constructRepositoryUrl = (
repositoryName: string,
host?: string | null,
): string => {
- const baseUrl = getGitProviderBaseUrl(provider, host);
+ const baseUrl = ensureHttpsPrefix(host);
if (provider === "bitbucket_data_center") {
const [project, repo] = repositoryName.split("/");
return `${baseUrl}/projects/${project}/repos/${repo}`;
@@ -400,7 +377,7 @@ export const constructBranchUrl = (
branchName: string,
host?: string | null,
): string => {
- const baseUrl = getGitProviderBaseUrl(provider, host);
+ const baseUrl = ensureHttpsPrefix(host);
switch (provider) {
case "github":
diff --git a/openhands/app_server/web_client/default_web_client_config_injector.py b/openhands/app_server/web_client/default_web_client_config_injector.py
index 2c78fa37bc..5dce66b0b1 100644
--- a/openhands/app_server/web_client/default_web_client_config_injector.py
+++ b/openhands/app_server/web_client/default_web_client_config_injector.py
@@ -10,6 +10,7 @@ from openhands.app_server.web_client.web_client_models import (
WebClientConfig,
WebClientFeatureFlags,
)
+from openhands.integrations.provider import ProviderHandler
from openhands.integrations.service_types import ProviderType
@@ -149,6 +150,12 @@ class DefaultWebClientConfigInjector(WebClientConfigInjector):
)
github_app_slug: str | None = Field(default_factory=_get_github_app_slug)
gitlab_enabled: bool = Field(default_factory=_is_gitlab_enabled)
+ provider_default_hosts: dict[str, str] = Field(
+ default_factory=lambda: {
+ provider.value: host
+ for provider, host in ProviderHandler.PROVIDER_DOMAINS.items()
+ }
+ )
slack_enabled: bool = Field(default_factory=_get_slack_enabled)
async def get_web_client_config(self) -> WebClientConfig:
@@ -168,6 +175,7 @@ class DefaultWebClientConfigInjector(WebClientConfigInjector):
updated_at=self.updated_at,
github_app_slug=self.github_app_slug,
gitlab_enabled=self.gitlab_enabled,
+ provider_default_hosts=self.provider_default_hosts,
slack_enabled=self.slack_enabled,
)
return result
diff --git a/openhands/app_server/web_client/web_client_models.py b/openhands/app_server/web_client/web_client_models.py
index ddb4fc53ae..8ebfc4c367 100644
--- a/openhands/app_server/web_client/web_client_models.py
+++ b/openhands/app_server/web_client/web_client_models.py
@@ -1,6 +1,6 @@
from datetime import datetime
-from pydantic import BaseModel, model_validator
+from pydantic import BaseModel, Field, model_validator
from openhands.agent_server.env_parser import DiscriminatedUnionMixin
from openhands.app_server.web_client.web_client_deployment_mode import (
@@ -43,4 +43,5 @@ class WebClientConfig(DiscriminatedUnionMixin):
updated_at: datetime
github_app_slug: str | None
gitlab_enabled: bool = False
+ provider_default_hosts: dict[str, str] = Field(default_factory=dict)
slack_enabled: bool = False
diff --git a/openhands/integrations/gitlab/constants.py b/openhands/integrations/gitlab/constants.py
new file mode 100644
index 0000000000..552df72300
--- /dev/null
+++ b/openhands/integrations/gitlab/constants.py
@@ -0,0 +1,17 @@
+"""GitLab configuration constants.
+
+GITLAB_HOST is the hostname of the GitLab instance (e.g. 'gitlab.example.com').
+Defaults to 'gitlab.com' for GitLab SaaS. Protocol prefixes and trailing
+slashes are stripped, so 'https://gitlab.example.com/' is accepted.
+"""
+
+import os
+
+GITLAB_HOST = (
+ os.environ.get('GITLAB_HOST', 'gitlab.com')
+ .strip()
+ .removeprefix('https://')
+ .removeprefix('http://')
+ .rstrip('/')
+ or 'gitlab.com'
+)
diff --git a/openhands/integrations/gitlab/gitlab_service.py b/openhands/integrations/gitlab/gitlab_service.py
index 31f0d7929d..144737e280 100644
--- a/openhands/integrations/gitlab/gitlab_service.py
+++ b/openhands/integrations/gitlab/gitlab_service.py
@@ -2,6 +2,7 @@ import os
from pydantic import SecretStr
+from openhands.integrations.gitlab.constants import GITLAB_HOST
from openhands.integrations.gitlab.service import (
GitLabBranchesMixin,
GitLabFeaturesMixin,
@@ -39,8 +40,8 @@ class GitLabService(
The class is instantiated via get_impl() in openhands.server.shared.py.
"""
- BASE_URL = 'https://gitlab.com/api/v4'
- GRAPHQL_URL = 'https://gitlab.com/api/graphql'
+ BASE_URL = f'https://{GITLAB_HOST}/api/v4'
+ GRAPHQL_URL = f'https://{GITLAB_HOST}/api/graphql'
def __init__(
self,
diff --git a/openhands/integrations/provider.py b/openhands/integrations/provider.py
index a3d0c79a0c..2a57234b9c 100644
--- a/openhands/integrations/provider.py
+++ b/openhands/integrations/provider.py
@@ -24,6 +24,7 @@ from openhands.integrations.bitbucket_data_center.bitbucket_dc_service import (
)
from openhands.integrations.forgejo.forgejo_service import ForgejoServiceImpl
from openhands.integrations.github.github_service import GithubServiceImpl
+from openhands.integrations.gitlab.constants import GITLAB_HOST
from openhands.integrations.gitlab.gitlab_service import GitLabServiceImpl
from openhands.integrations.service_types import (
AuthenticationError,
@@ -102,7 +103,7 @@ class ProviderHandler:
# Class variable for provider domains
PROVIDER_DOMAINS: dict[ProviderType, str] = {
ProviderType.GITHUB: 'github.com',
- ProviderType.GITLAB: 'gitlab.com',
+ ProviderType.GITLAB: GITLAB_HOST,
ProviderType.BITBUCKET: 'bitbucket.org',
ProviderType.FORGEJO: 'codeberg.org',
ProviderType.AZURE_DEVOPS: 'dev.azure.com',
diff --git a/tests/unit/integrations/gitlab/test_gitlab.py b/tests/unit/integrations/gitlab/test_gitlab.py
index 661992422c..363f7415bb 100644
--- a/tests/unit/integrations/gitlab/test_gitlab.py
+++ b/tests/unit/integrations/gitlab/test_gitlab.py
@@ -1,10 +1,14 @@
"""Tests for GitLab integration."""
+import importlib
from unittest.mock import patch
import pytest
from pydantic import SecretStr
+from openhands.integrations import provider as provider_module
+from openhands.integrations.gitlab import constants as gitlab_constants_module
+from openhands.integrations.gitlab.constants import GITLAB_HOST
from openhands.integrations.gitlab.gitlab_service import GitLabService
from openhands.integrations.service_types import OwnerType, ProviderType, Repository
from openhands.server.types import AppMode
@@ -475,3 +479,45 @@ async def test_gitlab_search_repositories_single_term_query():
# Verify we got the expected repositories
assert len(repositories) == 1
+
+
+class TestGitLabHostEnvVar:
+ """GITLAB_HOST env var configures the deployment-wide GitLab URL."""
+
+ def test_base_url_derived_from_gitlab_host(self):
+ assert GitLabService.BASE_URL == f'https://{GITLAB_HOST}/api/v4'
+ assert GitLabService.GRAPHQL_URL == f'https://{GITLAB_HOST}/api/graphql'
+
+ def test_provider_domains_uses_gitlab_host(self):
+ assert (
+ provider_module.ProviderHandler.PROVIDER_DOMAINS[ProviderType.GITLAB]
+ == GITLAB_HOST
+ )
+
+ def test_empty_gitlab_host_falls_back_to_default(self):
+ """An explicitly empty GITLAB_HOST falls back to gitlab.com."""
+ with patch.dict('os.environ', {'GITLAB_HOST': ''}):
+ reloaded = importlib.reload(gitlab_constants_module)
+ try:
+ assert reloaded.GITLAB_HOST == 'gitlab.com'
+ finally:
+ importlib.reload(gitlab_constants_module)
+
+ @pytest.mark.parametrize(
+ 'raw,expected',
+ [
+ ('gitlab.example.com/', 'gitlab.example.com'),
+ ('https://gitlab.example.com', 'gitlab.example.com'),
+ ('http://gitlab.example.com', 'gitlab.example.com'),
+ ('https://gitlab.example.com/', 'gitlab.example.com'),
+ (' https://gitlab.example.com/ ', 'gitlab.example.com'),
+ ],
+ )
+ def test_gitlab_host_is_sanitized(self, raw, expected):
+ """Common user input mistakes (protocol prefix, trailing slash, whitespace) are stripped."""
+ with patch.dict('os.environ', {'GITLAB_HOST': raw}):
+ reloaded = importlib.reload(gitlab_constants_module)
+ try:
+ assert reloaded.GITLAB_HOST == expected
+ finally:
+ importlib.reload(gitlab_constants_module)