:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(gitlab): accept a pasted project URL in the project field (#103310)
Tom Owers8a7b986586bb
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gitlab/gitlab.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gitlab/gitlab.pyindex 9a7b0493ca61..5b0166a53693 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/gitlab/gitlab.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gitlab/gitlab.py@@ -26,6 +26,10 @@ MAX_RETRY_AFTER_SECONDS = 60DEFAULT_HOST = "https://gitlab.com"HOST_NOT_ALLOWED_ERROR = "GitLab host is not allowed"HTTP_NOT_ALLOWED_ERROR = "GitLab host must use HTTPS"+PROJECT_REF_ERROR = (+ "PostHog couldn't read a project from that value. Enter group/project (for example, "+ "mygroup/myproject), the numeric project ID, or the project's GitLab URL."+)class GitLabRetryableError(Exception):@@ -74,9 +78,26 @@ def _is_https(host: str | None) -> bool:return urlparse(normalize_host(host)).scheme == "https"+def normalize_project_ref(project: str) -> str:+ """Reduce a pasted project value to the ``group/project`` path or numeric id GitLab addresses.++ The project URL is the value people have in front of them, and it names the project+ unambiguously, so read the path out of it rather than making them retype it. ``/-/`` separates+ a project path from GitLab's own sub-pages (``/-/issues``, ``/-/tree/main``), and an HTTPS+ clone URL ends in ``.git``.+ """+ ref = (project or "").strip()+ if "://" in ref:+ ref = urlparse(ref).path+ ref = ref.split("/-/", 1)[0].strip("/")+ if ref.endswith(".git"):+ ref = ref[: -len(".git")]+ return ref++def _encode_project(project: str) -> str:"""GitLab accepts either a numeric project id or a URL-encoded ``group/project`` path."""- return quote(project.strip().strip("/"), safe="")+ return quote(normalize_project_ref(project), safe="")def _get_headers(personal_access_token: str) -> dict[str, str]:@@ -190,17 +211,14 @@ def validate_credentials(if not project or not project.strip():return False, "Missing project id or path"- # GitLab addresses a project by its numeric id or a group/project path. A pasted URL, a bare- # group name, or a stray leading, trailing, or doubled slash otherwise URL-encodes into a- # nonsense path, 404s, and gets reported as "not found or not accessible with this token", which- # points the user at the token rather than the format.- project_ref = project.strip()+ # GitLab addresses a project by its numeric id or a group/project path. A bare group name, or a+ # stray leading, trailing, or doubled slash otherwise URL-encodes into a nonsense path, 404s,+ # and gets reported as "not found or not accessible with this token", which points the user at+ # the token rather than the format.+ project_ref = normalize_project_ref(project)segments = project_ref.split("/")- if not project_ref.isdigit() and ("://" in project_ref or len(segments) < 2 or not all(segments)):- return (- False,- "Enter the project as group/project (for example, mygroup/myproject) or its numeric project ID, not a full URL.",- )+ if not project_ref.isdigit() and (len(segments) < 2 or not all(segments)):+ return False, PROJECT_REF_ERRORhost_only = _host_only(host)if not host_only:diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gitlab/tests/test_gitlab.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gitlab/tests/test_gitlab.pyindex 2be030a12b23..1655f7e59c1d 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/gitlab/tests/test_gitlab.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gitlab/tests/test_gitlab.py@@ -89,6 +89,12 @@ class TestEncodeProject:("group/project", "group%2Fproject"),("/group/sub/project/", "group%2Fsub%2Fproject"),(" group/project ", "group%2Fproject"),+ # A pasted project URL resolves to the same path, so validation and every sync request+ # address the project the user is looking at.+ ("https://gitlab.com/group/project", "group%2Fproject"),+ ("https://gitlab.example.com/group/sub/project/", "group%2Fsub%2Fproject"),+ ("https://gitlab.com/group/project/-/merge_requests", "group%2Fproject"),+ ("https://gitlab.com/group/project.git", "group%2Fproject"),],)def test_encode_project(self, raw, expected):@@ -283,7 +289,7 @@ class TestValidateCredentials:@pytest.mark.parametrize("project",[- "https://gitlab.com/mygroup/", # pasted URL+ "https://gitlab.com/mygroup/", # pasted URL naming a group rather than a project"mygroup", # bare group, no project and not a numeric id"some-dashboard", # bare name"/myproject", # leading slash: encodes to an empty group segment@@ -298,6 +304,22 @@ class TestValidateCredentials:assert valid is Falseassert "group/project" in (msg or "")+ @pytest.mark.parametrize(+ "project",+ [+ "https://gitlab.com/mygroup/myproject",+ "https://gitlab.com/mygroup/myproject/-/issues",+ "https://gitlab.com/mygroup/myproject.git",+ ],+ )+ def test_pasted_project_url_reaches_the_api(self, project):+ # The URL names the project unambiguously, so it must resolve rather than dead-end on the+ # format check.+ with self._patch_session(_response(status_code=200)) as patched:+ valid, _ = validate_credentials("https://gitlab.com", "tok", project)+ assert valid is True+ assert patched.return_value.get.call_args.args[0].endswith("/projects/mygroup%2Fmyproject")+def test_numeric_project_id_is_not_rejected_as_malformed(self):# A bare numeric id is a valid GitLab project reference, so it must reach the API rather# than trip the format check for bare names.