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): stop returning files over 1 MB as empty (#98690)

Raúl Negrón-Otero0a08714871ef
diff --git a/posthog/models/github_integration_base.py b/posthog/models/github_integration_base.py
index b02300807cce..6c7b5148ebc4 100644
--- a/posthog/models/github_integration_base.py
+++ b/posthog/models/github_integration_base.py
@@ -2364,6 +2364,7 @@ class GitHubIntegrationBase:
timeout: int = 10,
retry_transient: bool | None = None,
priority: Priority | None = None,
+ stream: bool = False,
) -> requests.Response:
"""Authenticated request against ``https://api.github.com`` returning the raw response.
@@ -2409,6 +2410,7 @@ class GitHubIntegrationBase:
params=params,
json=json_body,
timeout=timeout,
+ stream=stream,
)
except requests.RequestException as exc:
if retry_transient and attempt == 0:
diff --git a/posthog/models/integration/github.py b/posthog/models/integration/github.py
index cc46b0b0b1fd..1f09d378ef64 100644
--- a/posthog/models/integration/github.py
+++ b/posthog/models/integration/github.py
@@ -37,6 +37,7 @@ _GITHUB_COMMIT_SHA_RE = re.compile(r"^[0-9a-fA-F]{7,40}$")
# Upper bound on the diff text we return, to keep a pathological diff (generated/vendored
# files) from bloating the JSON response and worker memory. ~1 MB of text.
_MAX_DIFF_CHARS = 1_000_000
+_MAX_FILE_CONTENTS_BYTES = 10 * 1024 * 1024
def _is_safe_github_repo_path(repo_path: str) -> bool:
@@ -839,6 +840,7 @@ class GitHubIntegration(GitHubIntegrationBase):
exist — a missing file is a normal state, not an error. The SHA lets a caller
pass it straight to ``update_file`` for a conflict-safe write. Counterpart to
``update_file``, kept here so URL and token handling stay inside the client.
+ Raises ``GitHubIntegrationError`` rather than return a partial or oversized file.
"""
repo_path = repository if "/" in repository else f"{self.organization()}/{repository}"
@@ -856,7 +858,39 @@ class GitHubIntegration(GitHubIntegrationBase):
status_code=response.status_code,
)
payload = response.json()
- return {"content": base64.b64decode(payload["content"]).decode("utf-8"), "sha": payload["sha"]}
+ size = payload["size"]
+ if size > _MAX_FILE_CONTENTS_BYTES:
+ raise GitHubIntegrationError(
+ f"{file_path} in {repository} is {size} bytes, over the {_MAX_FILE_CONTENTS_BYTES} byte limit"
+ )
+ content: bytes | bytearray
+ if payload["encoding"] == "none":
+ # The contents API omits content above 1 MB.
+ blob_response = self.api_request(
+ "GET",
+ f"/repos/{repo_path}/git/blobs/{payload['sha']}",
+ endpoint="/repos/{owner}/{repo}/git/blobs/{file_sha}",
+ headers={"Accept": "application/vnd.github.raw+json"},
+ stream=True,
+ )
+ try:
+ if blob_response.status_code != 200:
+ raise GitHubIntegrationError(
+ f"Failed to read {file_path} from {repository}: {blob_response.text}",
+ status_code=blob_response.status_code,
+ )
+ content = bytearray()
+ for chunk in blob_response.iter_content(chunk_size=64 * 1024):
+ content += chunk
+ if len(content) > size:
+ break
+ finally:
+ blob_response.close()
+ else:
+ content = base64.b64decode(payload["content"])
+ if len(content) != size:
+ raise GitHubIntegrationError(f"Read {len(content)} of {size} bytes of {file_path} from {repository}")
+ return {"content": content.decode("utf-8"), "sha": payload["sha"]}
def create_pull_request(
self, repository: str, title: str, body: str, head_branch: str, base_branch: str | None = None
diff --git a/posthog/models/test/integration/test_github.py b/posthog/models/test/integration/test_github.py
index 1ece8e2df30d..1c2ccade19d0 100644
--- a/posthog/models/test/integration/test_github.py
+++ b/posthog/models/test/integration/test_github.py
@@ -1,6 +1,8 @@
"""Tests for the GitHub App integration."""
import time
+import base64
+from collections.abc import Iterator
from datetime import UTC, datetime, timedelta
from typing import Any, Optional
@@ -36,6 +38,7 @@ from posthog.models.integration import (
Integration,
invalidate_github_repository_caches_for_installation,
)
+from posthog.models.integration.github import _MAX_FILE_CONTENTS_BYTES
from posthog.models.user_integration import UserGitHubIntegration, UserIntegration
@@ -601,6 +604,57 @@ class TestGitHubIntegrationModel(BaseTest):
assert result["diff"].startswith("x" * 100)
assert "truncated" in result["diff"]
+ @parameterized.expand([("inline", False), ("over_contents_api_limit", True)])
+ def test_get_file_contents_returns_whole_file(self, _name: str, over_contents_api_limit: bool) -> None:
+ github = GitHubIntegration(self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"}))
+ text = b"version: 1\nsnapshots: {}\n"
+ contents = {
+ "sha": "abc123",
+ "size": len(text),
+ "encoding": "base64",
+ "content": base64.b64encode(text).decode(),
+ }
+ responses: dict[str, MagicMock] = {}
+ if over_contents_api_limit:
+ contents = {**contents, "encoding": "none", "content": ""}
+ responses["/repos/PostHog/posthog/git/blobs/abc123"] = MagicMock(
+ status_code=200, iter_content=MagicMock(return_value=[text[:8], text[8:]])
+ )
+ responses["/repos/PostHog/posthog/contents/snapshots.yml"] = MagicMock(
+ status_code=200, json=MagicMock(return_value=contents)
+ )
+
+ with patch.object(github, "api_request", side_effect=lambda method, path, **kwargs: responses[path]):
+ result = github.get_file_contents("PostHog/posthog", "snapshots.yml")
+ assert result == {"content": text.decode(), "sha": "abc123"}
+
+ @parameterized.expand(
+ [
+ ("over_size_limit", {"size": _MAX_FILE_CONTENTS_BYTES + 1, "encoding": "none", "content": ""}),
+ (
+ "inline_shorter_than_size",
+ {"size": 100, "encoding": "base64", "content": base64.b64encode(b"version: 1\n").decode()},
+ ),
+ ("blob_longer_than_size", {"size": 4, "encoding": "none", "content": ""}),
+ ]
+ )
+ def test_get_file_contents_rejects_file_it_cannot_return_whole(self, _name: str, contents: dict[str, Any]) -> None:
+ github = GitHubIntegration(self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"}))
+
+ def blob_chunks(chunk_size: int) -> Iterator[bytes]:
+ yield b"version: 1\n"
+ raise AssertionError("read past the declared size")
+
+ responses = {
+ "/repos/PostHog/posthog/contents/snapshots.yml": MagicMock(
+ status_code=200, json=MagicMock(return_value={"sha": "abc123", **contents})
+ ),
+ "/repos/PostHog/posthog/git/blobs/abc123": MagicMock(status_code=200, iter_content=blob_chunks),
+ }
+ with patch.object(github, "api_request", side_effect=lambda method, path, **kwargs: responses[path]):
+ with pytest.raises(GitHubIntegrationError):
+ github.get_file_contents("PostHog/posthog", "snapshots.yml")
+
@parameterized.expand(
[
("repo_traversal", {"repository": "../../other/repo"}),
diff --git a/products/visual_review/backend/tests/conftest.py b/products/visual_review/backend/tests/conftest.py
index 0b0eead5a7b7..56881dd1410f 100644
--- a/products/visual_review/backend/tests/conftest.py
+++ b/products/visual_review/backend/tests/conftest.py
@@ -258,6 +258,7 @@ def mock_github_api(local_git_repo):
"content": encoded,
"sha": blob_sha,
"encoding": "base64",
+ "size": len(content.encode()),
}
),
)
diff --git a/products/visual_review/backend/tests/test_github_integration.py b/products/visual_review/backend/tests/test_github_integration.py
index 005691901309..d02f4cfb4136 100644
--- a/products/visual_review/backend/tests/test_github_integration.py
+++ b/products/visual_review/backend/tests/test_github_integration.py
@@ -163,6 +163,7 @@ def mock_github_api(local_git_repo):
"content": encoded,
"sha": blob_sha,
"encoding": "base64",
+ "size": len(content.encode()),
}
),
)