Skip to content

: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.

fix(github): accept a repository pasted as a GitHub URL (#99963)

Tom Owers8101d6704524
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/github/github.py b/products/warehouse_sources/backend/temporal/data_imports/sources/github/github.py
index 3ec1df3387f6..aae9db8f1fcc 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/github/github.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/github/github.py
@@ -38,6 +38,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.htt
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.common.webhook_s3 import WebhookSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.github.naming import normalize_repository
from products.warehouse_sources.backend.temporal.data_imports.sources.github.settings import (
ENDPOINT_REQUIRED_PERMISSION,
GITHUB_ENDPOINTS,
@@ -383,11 +384,11 @@ def validate_credentials(
personal_access_token: str, repository: str, api_version: str = GITHUB_DEFAULT_API_VERSION
) -> tuple[bool, str | None]:
"""Validate GitHub API credentials by making a test request to the repository."""
- # A pasted clone URL (github.com/owner/repo.git) or a bare owner name otherwise reaches the API
- # as a nonsense path, 404s, and gets reported as "not found or not accessible" — which points the
- # user at permissions rather than the real problem, the identifier format. Catch the wrong shape
- # before the request so the message names the fix.
- repo = repository.strip()
+ # A bare owner name otherwise reaches the API as a nonsense path, 404s, and gets reported as
+ # "not found or not accessible" — which points the user at permissions rather than the real
+ # problem, the identifier format. Catch the wrong shape before the request so the message
+ # names the fix.
+ repo = normalize_repository(repository)
if repo.count("/") != 1 or not all(repo.split("/")):
# Name the offending entry, like the 404 message below. Without it, two malformed repos both
# return this identical sentence and the caller joins them into one repeated string that names
@@ -397,7 +398,7 @@ def validate_credentials(
f"'{repo}' isn't a valid repository. Enter it as owner/repo (for example, posthog/posthog), not a full URL or just the owner name.",
)
- url = f"{GITHUB_BASE_URL}/repos/{repository}"
+ url = f"{GITHUB_BASE_URL}/repos/{repo}"
headers = _get_headers(personal_access_token, api_version=api_version)
try:
@@ -410,7 +411,7 @@ def validate_credentials(
return False, "Invalid personal access token"
if response.status_code == 404:
- return False, f"Repository '{repository}' {REPOSITORY_NOT_ACCESSIBLE_REASON}"
+ return False, f"Repository '{repo}' {REPOSITORY_NOT_ACCESSIBLE_REASON}"
try:
body = response.json()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/github/naming.py b/products/warehouse_sources/backend/temporal/data_imports/sources/github/naming.py
index bb36225f8aa2..8df9bf5208cd 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/github/naming.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/github/naming.py
@@ -9,7 +9,9 @@ Legacy single-repo sources keep bare endpoint names (`issues`); those resolve to
`repository` field.
"""
+import re
from typing import TYPE_CHECKING, Any
+from urllib.parse import urlsplit
from products.warehouse_sources.backend.temporal.data_imports.sources.github.settings import ENDPOINTS
@@ -25,6 +27,46 @@ SCHEMA_METADATA_ENDPOINT_KEY = "source_endpoint"
_ENDPOINT_SUFFIXES = sorted(ENDPOINTS, key=lambda name: len(name), reverse=True)
+# GitHub hosts whose URLs name a repository the API can serve.
+_GITHUB_URL_HOSTS = ("github.com", "www.github.com")
+
+# The scp-style clone URL (`[email protected]:owner/repo.git`), which has no scheme for urlsplit to read.
+_GITHUB_SCP_URL = re.compile(r"^(?:ssh://)?git@github\.com[:/](?P<path>.+)$", re.IGNORECASE)
+
+
+def normalize_repository(repository: str) -> str:
+ """`owner/repo` when the value is a GitHub URL, the stripped input otherwise.
+
+ A clone URL, a browser URL and a bare `github.com/owner/repo` all name the repository as
+ unambiguously as `owner/repo` does, so read them rather than rejecting input whose meaning
+ is clear."""
+ value = repository.strip()
+ scp_match = _GITHUB_SCP_URL.match(value)
+ if scp_match:
+ path = scp_match.group("path")
+ elif "://" in value or value.lower().startswith(tuple(f"{host}/" for host in _GITHUB_URL_HOSTS)):
+ parsed = urlsplit(value if "://" in value else f"https://{value}")
+ if (parsed.hostname or "").lower() not in _GITHUB_URL_HOSTS:
+ return value
+ path = parsed.path
+ else:
+ return value
+
+ # Anything past owner/repo is a browser URL's view of the repo (/tree/main, /issues), not part
+ # of its name.
+ parts = [part for part in path.split("/") if part]
+ if len(parts) < 2:
+ return value
+ owner, repo = parts[0], parts[1]
+ # GitHub rejects a repository name ending in `.git`, so any casing of that suffix belongs to
+ # the clone URL rather than to the name.
+ if repo.lower().endswith(".git"):
+ repo = repo[: -len(".git")]
+ if not repo:
+ return value
+ return f"{owner}/{repo}"
+
+
def qualified_schema_name(repository: str, endpoint: str) -> str:
return f"{repository}.{endpoint}"
@@ -68,7 +110,7 @@ def schema_repo_endpoint(
if parsed_repository is not None:
return parsed_repository.strip().lower(), parsed_endpoint
- normalized_legacy = (legacy_repository or "").strip().lower()
+ normalized_legacy = normalize_repository(legacy_repository or "").lower()
return (normalized_legacy or None), parsed_endpoint
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/github/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/github/source.py
index dc82087d970d..4675f49db69e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/github/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/github/source.py
@@ -62,6 +62,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.github.git
validate_credentials as validate_github_credentials,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.github.naming import (
+ normalize_repository,
qualified_schema_name,
resolve_schema_repo_endpoint,
schema_metadata_for,
@@ -428,7 +429,7 @@ If automatic creation failed with a permissions error, the fix depends on how yo
storage_owners: dict[str, str] = {}
repositories: list[str] = []
for repo in raw:
- normalized = repo.strip().lower()
+ normalized = normalize_repository(repo).lower()
if not normalized or normalized in seen:
continue
storage_key = NamingConvention.normalize_identifier(normalized)
@@ -453,7 +454,7 @@ If automatic creation failed with a permissions error, the fix depends on how yo
def is_legacy_bare_repo(config: GithubSourceConfig, repository: str) -> bool:
"""True when `repository` is the pre-multi-repo repo whose schemas keep bare, unqualified
names (`issues`, not `owner/repo.issues`)."""
- return bool(config.repository) and repository == (config.repository or "").strip().lower()
+ return bool(config.repository) and repository == normalize_repository(config.repository or "").lower()
def _get_access_token(self, config: GithubSourceConfig, team_id: int) -> str:
if config.auth_method.selection == "pat":
@@ -599,7 +600,7 @@ If automatic creation failed with a permissions error, the fix depends on how yo
continue
if endpoint not in ORG_SCOPED_ENDPOINTS:
continue
- org_endpoints[name] = (repository or config.repository or "").strip().lower()
+ org_endpoints[name] = normalize_repository(repository or config.repository or "").lower()
if not org_endpoints:
return result
try:
@@ -692,7 +693,7 @@ If automatic creation failed with a permissions error, the fix depends on how yo
# Pin the legacy repository (the one whose rows keep bare event keys) so the template's
# bare-key fallback only fires for its events. Empty when there's no legacy repo (pure
# multi-repo sources have no bare keys, so nothing to bind).
- return {"legacy_repository": (config.repository or "").strip().lower()}
+ return {"legacy_repository": normalize_repository(config.repository or "").lower()}
def get_desired_webhook_events(
self, config: GithubSourceConfig, eligible_schema_names: list[str]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_source_class.py b/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_source_class.py
index 3f180adf502f..83981ada37d6 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_source_class.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_source_class.py
@@ -524,6 +524,9 @@ class TestGithubSource:
(None, ["PostHog/posthog", "posthog/posthog", " Other/Repo "], ["posthog/posthog", "other/repo"]),
# A non-empty `repositories` is the authoritative set; `repository` only marks bare naming.
("posthog/posthog", ["a/b"], ["a/b"]),
+ # A repo pasted as a GitHub URL must route to the same storage as `owner/repo`, or the
+ # same repository would sync into two tables depending on how it was entered.
+ (None, ["https://github.com/PostHog/posthog.git", "posthog/posthog"], ["posthog/posthog"]),
],
)
def test_effective_repositories(self, repository, repositories, expected):
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_validate_credentials.py b/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_validate_credentials.py
index d9c0c1f85c1e..13a9fdcaf482 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_validate_credentials.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_validate_credentials.py
@@ -49,10 +49,10 @@ def test_json_error_message_is_surfaced():
@pytest.mark.parametrize(
"repository",
[
- "https://github.com/owner/repo.git", # pasted clone URL
"owner", # bare owner, no repo
"owner/repo/extra", # too many path segments
"/repo", # missing owner
+ "https://gitlab.com/owner/repo.git", # a URL for another host names no GitHub repo
],
)
def test_malformed_repository_gets_format_guidance(repository):
@@ -65,3 +65,25 @@ def test_malformed_repository_gets_format_guidance(repository):
# Naming the offending entry keeps two malformed repos from collapsing into one repeated
# sentence when the source layer joins their failures.
assert repository.strip() in message
+
+
+ "repository",
+ [
+ "https://github.com/owner/repo.git",
+ "https://github.com/owner/repo/tree/main",
+ "[email protected]:owner/repo.git",
+ "https://github.com/owner/repo.GIT",
+ "github.com/owner/repo",
+ ],
+)
+def test_repository_url_is_read_as_owner_repo(repository):
+ # A pasted GitHub URL names the repo unambiguously, so it must reach the API as owner/repo
+ # instead of being rejected for its format.
+ session = mock.Mock()
+ session.get.return_value = _response(200, json_body={})
+ with mock.patch.object(github, "make_tracked_session", return_value=session):
+ is_valid, message = github.validate_credentials("token", repository)
+
+ assert (is_valid, message) == (True, None)
+ assert session.get.call_args.args[0].endswith("/repos/owner/repo")