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.

feat(deployments): connect projects to github repositories (#58490)

Dustin Byrne37663b1d3b51
diff --git a/products/deployments/backend/adapters/__init__.py b/products/deployments/backend/adapters/__init__.py
index 922774f64107..4eb3cec2055e 100644
--- a/products/deployments/backend/adapters/__init__.py
+++ b/products/deployments/backend/adapters/__init__.py
@@ -6,13 +6,14 @@ Temporal workflow control). Build/Infra and GitHub streams substitute real
implementations via `settings.DEPLOYMENTS_*_ADAPTER` (path-string → class)
without touching any of our files.
-For tests and the dev environment, a `Null*` stub is the default — it
-returns canned values so the rest of the codebase exercises real code
-paths without standing up external services.
+For tests and the dev environment, most adapters default to a `Null*` stub
+that returns canned values. GitHub repository reads use the existing PostHog
+GitHub integration by default, while deployment commit resolution remains
+stubbed until the build stream owns that contract.
"""
from .cloudflare import CloudflareAdapter, CloudflareError, NullCloudflareAdapter, get_cloudflare_adapter
-from .github import GitHubAdapter, GitHubError, NullGitHubAdapter, get_github_adapter
+from .github import GitHubAdapter, GitHubBranch, GitHubError, GitHubRepository, NullGitHubAdapter, get_github_adapter
from .microlink import NullScreenshotAdapter, ScreenshotAdapter, get_screenshot_adapter
from .temporal import NullWorkflowAdapter, WorkflowAdapter, WorkflowError, get_workflow_adapter
@@ -20,7 +21,9 @@ __all__ = [
"CloudflareAdapter",
"CloudflareError",
"GitHubAdapter",
+ "GitHubBranch",
"GitHubError",
+ "GitHubRepository",
"NullCloudflareAdapter",
"NullGitHubAdapter",
"NullScreenshotAdapter",
diff --git a/products/deployments/backend/adapters/github.py b/products/deployments/backend/adapters/github.py
index c2e09d9da2c4..579322761190 100644
--- a/products/deployments/backend/adapters/github.py
+++ b/products/deployments/backend/adapters/github.py
@@ -1,19 +1,49 @@
"""GitHub adapter boundary.
-The GitHub auth stream owns the real implementation (resolves HEAD of a
-branch, fetches commit metadata, exchanges PAT/OAuth). We declare the
-Protocol they implement against and a Null stub for tests.
+The rest of Deployments talks to GitHub through this module. For the
+hackathon path, repository selection uses the existing PostHog
+``Integration(kind="github")`` installation rather than a Deployments-specific
+GitHub App or live push webhooks.
"""
from __future__ import annotations
+import re
+from dataclasses import dataclass
from importlib import import_module
-from typing import Protocol
+from typing import TYPE_CHECKING, Any, Protocol
+from urllib.parse import quote
from django.conf import settings
+from posthog.models.github_integration_base import GitHubIntegrationError
+from posthog.models.integration import GitHubIntegration
+
from ..domain.contracts import CommitMetadata
+if TYPE_CHECKING:
+ from posthog.models.integration import Integration
+
+
+_REPO_FULL_NAME_RE = re.compile(r"^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$")
+
+# TODO(deployments-v1): move request-path GitHub verification to async jobs before increasing retry budgets.
+DEPLOYMENTS_GITHUB_API_TIMEOUT_SECONDS = 2
+
+
+@dataclass(frozen=True)
+class GitHubRepository:
+ id: int
+ full_name: str
+ default_branch: str
+ html_url: str
+
+
+@dataclass(frozen=True)
+class GitHubBranch:
+ name: str
+ sha: str
+
class GitHubAdapter(Protocol):
"""Surface we depend on from GitHub.
@@ -33,17 +63,37 @@ class GitHubAdapter(Protocol):
def get_commit(self, *, repo_url: str, sha: str, access_token: str | None) -> CommitMetadata: ...
+ def get_repository_by_id(self, *, integration: Integration, github_repo_id: int) -> GitHubRepository: ...
+
+ def get_repository(self, *, integration: Integration, repo_full_name: str) -> GitHubRepository: ...
+
+ def get_branch(self, *, integration: Integration, repo_full_name: str, branch: str) -> GitHubBranch: ...
+
class GitHubError(Exception):
- """Raised when a GitHub API call fails. Translated to 502 by callers."""
+ """Raised when a GitHub API call fails. Translated by callers."""
+
+
+def validate_repo_full_name(repo_full_name: str) -> None:
+ if not _REPO_FULL_NAME_RE.fullmatch(repo_full_name):
+ raise GitHubError("Repository must be in owner/repo format.")
+ owner, repo = repo_full_name.split("/", 1)
+ if owner in (".", "..") or repo in (".", ".."):
+ raise GitHubError("Repository must be in owner/repo format.")
+
+
+def repo_url_from_full_name(repo_full_name: str) -> str:
+ validate_repo_full_name(repo_full_name)
+ return f"https://github.com/{repo_full_name}"
class NullGitHubAdapter:
- """Stub used in tests and the dev environment.
+ """Stub used in tests and the dev environment for deployment commits.
- Returns synthetic commit metadata that mirrors the shape of a real
- response. The author email matches the test team's owner email pattern
- so author-filter tests can assert against a stable value.
+ Repository/branch selection is implemented by ``GitHubIntegrationAdapter``
+ below because it uses the existing Integration installation token. Commit
+ resolution remains synthetic until the build stream wires the full clone
+ credentials contract.
"""
def head_of_branch(self, *, repo_url: str, branch: str, access_token: str | None) -> CommitMetadata:
@@ -64,11 +114,110 @@ class NullGitHubAdapter:
branch="main",
)
+ def get_repository_by_id(self, *, integration: Integration, github_repo_id: int) -> GitHubRepository:
+ return GitHubRepository(
+ id=github_repo_id,
+ full_name="example-org/site",
+ default_branch="main",
+ html_url="https://github.com/example-org/site",
+ )
+
+ def get_repository(self, *, integration: Integration, repo_full_name: str) -> GitHubRepository:
+ validate_repo_full_name(repo_full_name)
+ return GitHubRepository(
+ id=0,
+ full_name=repo_full_name,
+ default_branch="main",
+ html_url=repo_url_from_full_name(repo_full_name),
+ )
+
+ def get_branch(self, *, integration: Integration, repo_full_name: str, branch: str) -> GitHubBranch:
+ validate_repo_full_name(repo_full_name)
+ return GitHubBranch(name=branch, sha="0" * 40)
+
+
+class GitHubIntegrationAdapter(NullGitHubAdapter):
+ """GitHub adapter backed by the existing PostHog GitHub integration."""
+
+ def _get_json(self, *, integration: Integration, path: str, endpoint: str) -> dict[str, Any]:
+ try:
+ payload = GitHubIntegration(integration)._gh_api_get(
+ path,
+ endpoint=endpoint,
+ timeout=DEPLOYMENTS_GITHUB_API_TIMEOUT_SECONDS,
+ )
+ except GitHubIntegrationError as err:
+ raise GitHubError(str(err)) from err
+ if not isinstance(payload, dict):
+ raise GitHubError("GitHub API returned an unexpected response shape.")
+ return payload
+
+ def _repository_from_payload(self, payload: dict[str, Any]) -> GitHubRepository:
+ repository_id = payload.get("id")
+ full_name = payload.get("full_name")
+ default_branch = payload.get("default_branch")
+ html_url = payload.get("html_url")
+ if not isinstance(repository_id, int):
+ raise GitHubError("GitHub repository response was missing a valid id.")
+ if not isinstance(full_name, str) or not full_name:
+ raise GitHubError("GitHub repository response was missing a full_name.")
+ if not isinstance(default_branch, str) or not default_branch:
+ raise GitHubError("GitHub repository response was missing a default branch.")
+ if not isinstance(html_url, str) or not html_url:
+ html_url = repo_url_from_full_name(full_name)
+
+ return GitHubRepository(
+ id=repository_id,
+ full_name=full_name,
+ default_branch=default_branch,
+ html_url=html_url,
+ )
+
+ def get_repository_by_id(self, *, integration: Integration, github_repo_id: int) -> GitHubRepository:
+ payload = self._get_json(
+ integration=integration,
+ path=f"/repositories/{github_repo_id}",
+ endpoint="/repositories/{repository_id}",
+ )
+ repository = self._repository_from_payload(payload)
+ if repository.id != github_repo_id:
+ raise GitHubError("GitHub repository response id did not match the requested repository.")
+ return repository
+
+ def get_repository(self, *, integration: Integration, repo_full_name: str) -> GitHubRepository:
+ validate_repo_full_name(repo_full_name)
+ payload = self._get_json(
+ integration=integration,
+ path=f"/repos/{repo_full_name}",
+ endpoint="/repos/{owner}/{repo}",
+ )
+
+ return self._repository_from_payload(payload)
+
+ def get_branch(self, *, integration: Integration, repo_full_name: str, branch: str) -> GitHubBranch:
+ validate_repo_full_name(repo_full_name)
+ if not branch:
+ raise GitHubError("A tracked branch is required.")
+ payload = self._get_json(
+ integration=integration,
+ path=f"/repos/{repo_full_name}/branches/{quote(branch, safe='')}",
+ endpoint="/repos/{owner}/{repo}/branches/{branch}",
+ )
+
+ branch_name = payload.get("name")
+ commit = payload.get("commit")
+ sha = commit.get("sha") if isinstance(commit, dict) else None
+ if not isinstance(branch_name, str) or not branch_name:
+ branch_name = branch
+ if not isinstance(sha, str) or not sha:
+ raise GitHubError("GitHub branch response was missing a commit SHA.")
+ return GitHubBranch(name=branch_name, sha=sha)
+
def get_github_adapter() -> GitHubAdapter:
path = getattr(settings, "DEPLOYMENTS_GITHUB_ADAPTER", None)
if not path:
- return NullGitHubAdapter()
+ return GitHubIntegrationAdapter()
module_path, class_name = path.split(":")
module = import_module(module_path)
return getattr(module, class_name)()
diff --git a/products/deployments/backend/api/deployment_projects.py b/products/deployments/backend/api/deployment_projects.py
index 43ef697248d5..929297c1f4da 100644
--- a/products/deployments/backend/api/deployment_projects.py
+++ b/products/deployments/backend/api/deployment_projects.py
@@ -7,12 +7,15 @@ under projects (see api/deployments.py).
from __future__ import annotations
+from dataclasses import dataclass
from typing import Any
from django.utils import timezone
from drf_spectacular.utils import OpenApiResponse, extend_schema
from rest_framework import filters, serializers, status, viewsets
+from rest_framework.decorators import action
+from rest_framework.exceptions import NotFound, ValidationError
from rest_framework.permissions import BasePermission, IsAuthenticated
from rest_framework.request import Request
from rest_framework.response import Response
@@ -20,13 +23,20 @@ from rest_framework.views import APIView
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.auth import OAuthAccessTokenAuthentication, PersonalAPIKeyAuthentication, SessionAuthentication
+from posthog.models.integration import Integration
from posthog.permissions import APIScopePermission
from posthog.rbac.access_control_api_mixin import AccessControlViewSetMixin
+from posthog.rbac.user_access_control import UserAccessControl, access_level_satisfied_for_resource
from ..access import has_deployments_access
-from ..adapters import CloudflareError, get_cloudflare_adapter
+from ..adapters import CloudflareError, get_cloudflare_adapter, get_github_adapter
+from ..adapters.github import GitHubError, repo_url_from_full_name
from ..models import DeploymentProject
-from ..serializers import DeploymentProjectSerializer
+from ..serializers import (
+ DeploymentProjectCreateSerializer,
+ DeploymentProjectSerializer,
+ DeploymentProjectWriteSerializer,
+)
from ..services import provision_project
@@ -40,6 +50,120 @@ class DeploymentsAccessPermission(BasePermission):
return has_deployments_access(request.user, team_id=team_id)
+@dataclass(frozen=True)
+class ResolvedRepositoryConfig:
+ repo_url: str
+ default_branch: str
+ github_integration_id: int | None
+ github_repo_id: int | None
+
+
+@dataclass(frozen=True)
+class RefreshedRepositoryState:
+ repo_url: str
+ default_branch: str
+ commit_sha: str
+
+
+def _can_view_integration(integration: Integration, *, user_access_control: UserAccessControl) -> bool:
+ if user_access_control.check_access_level_for_resource("integration", required_level="viewer"):
+ return user_access_control.check_access_level_for_object(integration, required_level="viewer")
+
+ specific_access_level = user_access_control.specific_access_level_for_object(integration)
+ return bool(
+ specific_access_level
+ and access_level_satisfied_for_resource("integration", specific_access_level, required_level="viewer")
+ )
+
+
+def _get_team_github_integration(
+ *, team_id: int, integration_id: int, user_access_control: UserAccessControl
+) -> Integration:
+ integration = Integration.objects.filter(
+ id=integration_id,
+ team_id=team_id,
+ kind=Integration.IntegrationKind.GITHUB.value,
+ ).first()
+ if integration is None or not _can_view_integration(integration, user_access_control=user_access_control):
+ raise NotFound("GitHub integration not found for this project.")
+ return integration
+
+
+def _resolve_repository_config(
+ data: dict[str, Any], *, team_id: int, user_access_control: UserAccessControl
+) -> ResolvedRepositoryConfig:
+ github_integration_id = data.get("github_integration_id")
+ if github_integration_id is None:
+ raise ValidationError({"github_integration_id": "This field is required."})
+
+ github_repo_id = data.get("github_repo_id")
+ if github_repo_id is None:
+ raise ValidationError({"github_repo_id": "This field is required."})
+
+ integration = _get_team_github_integration(
+ team_id=team_id,
+ integration_id=int(github_integration_id),
+ user_access_control=user_access_control,
+ )
+ adapter = get_github_adapter()
+ try:
+ repository = adapter.get_repository_by_id(integration=integration, github_repo_id=int(github_repo_id))
+ branch_name = str(data.get("default_branch") or repository.default_branch).strip() or repository.default_branch
+ branch = adapter.get_branch(integration=integration, repo_full_name=repository.full_name, branch=branch_name)
+ except GitHubError as err:
+ raise ValidationError({"github": str(err)}) from err
+
+ return ResolvedRepositoryConfig(
+ repo_url=repository.html_url or repo_url_from_full_name(repository.full_name),
+ default_branch=branch.name,
+ github_integration_id=integration.id,
+ github_repo_id=repository.id,
+ )
+
+
+class DeploymentProjectRefreshResponseSerializer(serializers.Serializer):
+ """Response shape for refreshing a deployment project's GitHub branch."""
+
+ detail = serializers.CharField(help_text="Human-readable explanation of the refresh result.")
+ repo_url = serializers.URLField(help_text="HTTPS URL of the connected GitHub repository.")
+ default_branch = serializers.CharField(help_text="Branch checked by the refresh action.")
+ commit_sha = serializers.CharField(help_text="Current GitHub HEAD SHA for default_branch.")
+
+
+def _refresh_project_repository_state(
+ project: DeploymentProject, *, user_access_control: UserAccessControl
+) -> RefreshedRepositoryState:
+ if project.github_integration_id is None or project.github_repo_id is None:
+ raise ValidationError("Deployment project is not connected to a GitHub repository.")
+
+ integration = _get_team_github_integration(
+ team_id=project.team_id,
+ integration_id=project.github_integration_id,
+ user_access_control=user_access_control,
+ )
+ adapter = get_github_adapter()
+ try:
+ repository = adapter.get_repository_by_id(integration=integration, github_repo_id=project.github_repo_id)
+ branch = adapter.get_branch(
+ integration=integration,
+ repo_full_name=repository.full_name,
+ branch=project.default_branch,
+ )
+ except GitHubError as err:
+ raise ValidationError({"github": str(err)}) from err
+
+ repo_url = repository.html_url or repo_url_from_full_name(repository.full_name)
+ if project.repo_url != repo_url:
+ project.repo_url = repo_url
+ project.save(update_fields=["repo_url", "updated_at"])
+
+ return RefreshedRepositoryState(
+ repo_url=repo_url,
+ default_branch=branch.name,
+ commit_sha=branch.sha,
+ )
+
+
@extend_schema(tags=["deployments"])
class DeploymentProjectViewSet(
TeamAndOrgViewSetMixin,
@@ -66,7 +190,7 @@ class DeploymentProjectViewSet(
# and would raise without a team context at class-definition time.
queryset = DeploymentProject.all_teams.all()
filter_backends = [filters.SearchFilter, filters.OrderingFilter]
- search_fields = ["name", "slug", "repo_url"]
+ search_fields = ["name", "slug", "repo_url", "default_branch"]
ordering_fields = ["created_at", "updated_at", "name"]
ordering = ["-created_at"]
# URL parent `project_id` is the PostHog team_id (project/team alias).
@@ -80,15 +204,20 @@ class DeploymentProjectViewSet(
return queryset.filter(team_id=self.team_id).exclude(deleted=True)
@extend_schema(
- request=DeploymentProjectSerializer,
+ request=DeploymentProjectCreateSerializer,
responses={
status.HTTP_201_CREATED: DeploymentProjectSerializer,
status.HTTP_502_BAD_GATEWAY: OpenApiResponse(description="Cloudflare provisioning failed."),
},
)
def create(self, request: Request, *args: Any, **kwargs: Any) -> Response:
- serializer = self.get_serializer(data=request.data)
+ serializer = DeploymentProjectCreateSerializer(data=request.data, context=self.get_serializer_context())
serializer.is_valid(raise_exception=True)
+ repository_config = _resolve_repository_config(
+ serializer.validated_data,
+ team_id=self.team_id,
+ user_access_control=self.user_access_control,
+ )
try:
project = provision_project.execute(
provision_project.ProvisionInput(
@@ -96,9 +225,10 @@ class DeploymentProjectViewSet(
created_by_id=request.user.id if request.user.is_authenticated else None,
name=serializer.validated_data["name"],
slug=serializer.validated_data["slug"],
- repo_url=serializer.validated_data["repo_url"],
- default_branch=serializer.validated_data.get("default_branch", "main"),
- github_integration_id=serializer.validated_data.get("github_integration_id"),
+ repo_url=repository_config.repo_url,
+ default_branch=repository_config.default_branch,
+ github_integration_id=repository_config.github_integration_id,
+ github_repo_id=repository_config.github_repo_id,
build_command=serializer.validated_data.get("build_command"),
output_dir=serializer.validated_data.get("output_dir", "dist"),
framework=serializer.validated_data.get("framework"),
@@ -114,9 +244,78 @@ class DeploymentProjectViewSet(
return Response(self.get_serializer(project).data, status=status.HTTP_201_CREATED)
- @extend_schema(request=DeploymentProjectSerializer, responses={status.HTTP_200_OK: DeploymentProjectSerializer})
+ def _save_with_repository_config(self, instance: DeploymentProject, serializer: Any) -> DeploymentProject:
+ tracking_fields = {"github_integration_id", "github_repo_id", "default_branch"}
+ save_kwargs: dict[str, Any] = {}
+ if tracking_fields.intersection(serializer.validated_data):
+ merged_data = {
+ "default_branch": instance.default_branch,
+ "github_integration_id": instance.github_integration_id,
+ "github_repo_id": instance.github_repo_id,
+ }
+ merged_data.update(serializer.validated_data)
+ repository_config = _resolve_repository_config(
+ merged_data,
+ team_id=self.team_id,
+ user_access_control=self.user_access_control,
+ )
+ save_kwargs = {
+ "repo_url": repository_config.repo_url,
+ "default_branch": repository_config.default_branch,
+ "github_integration_id": repository_config.github_integration_id,
+ "github_repo_id": repository_config.github_repo_id,
+ }
+ return serializer.save(**save_kwargs)
+
+ @extend_schema(
+ request=DeploymentProjectWriteSerializer, responses={status.HTTP_200_OK: DeploymentProjectSerializer}
+ )
+ def update(self, request: Request, *args: Any, **kwargs: Any) -> Response:
+ instance = self.get_object()
+ serializer = DeploymentProjectWriteSerializer(
+ instance,
+ data=request.data,
+ context=self.get_serializer_context(),
+ )
+ serializer.is_valid(raise_exception=True)
+ project = self._save_with_repository_config(instance, serializer)
+ return Response(self.get_serializer(project).data, status=status.HTTP_200_OK)
+
+ @extend_schema(
+ request=DeploymentProjectWriteSerializer, responses={status.HTTP_200_OK: DeploymentProjectSerializer}
+ )
def partial_update(self, request: Request, *args: Any, **kwargs: Any) -> Response:
- return super().partial_update(request, *args, **kwargs)
+ instance = self.get_object()
+ serializer = DeploymentProjectWriteSerializer(
+ instance,
+ data=request.data,
+ partial=True,
+ context=self.get_serializer_context(),
+ )
+ serializer.is_valid(raise_exception=True)
+ project = self._save_with_repository_config(instance, serializer)
+ return Response(self.get_serializer(project).data, status=status.HTTP_200_OK)
+
+ @extend_schema(
+ request=None,
+ responses={status.HTTP_200_OK: OpenApiResponse(response=DeploymentProjectRefreshResponseSerializer)},
+ summary="Refresh a deployment project's GitHub branch",
+ )
+ @action(detail=True, methods=["post"])
+ def refresh(self, request: Request, **kwargs: Any) -> Response:
+ project = self.get_object()
+ refreshed = _refresh_project_repository_state(project, user_access_control=self.user_access_control)
+ return Response(
+ DeploymentProjectRefreshResponseSerializer(
+ {
+ "detail": "GitHub branch refreshed.",
+ "repo_url": refreshed.repo_url,
+ "default_branch": refreshed.default_branch,
+ "commit_sha": refreshed.commit_sha,
+ }
+ ).data,
+ status=status.HTTP_200_OK,
+ )
@extend_schema(responses={status.HTTP_204_NO_CONTENT: None})
def destroy(self, request: Request, *args: Any, **kwargs: Any) -> Response:
diff --git a/products/deployments/backend/api/internal.py b/products/deployments/backend/api/internal.py
index 97e491329c68..df15f0cd2f4e 100644
--- a/products/deployments/backend/api/internal.py
+++ b/products/deployments/backend/api/internal.py
@@ -29,6 +29,7 @@ from rest_framework.request import Request
from rest_framework.response import Response
from posthog.auth import InternalAPIAuthentication
+from posthog.models.scoping import team_scope
from ..domain.status import InvalidStatusTransition, Status
from ..domain.trigger import ErrorStep
@@ -129,36 +130,37 @@ class InternalDeploymentTransitionsViewSet(viewsets.ViewSet):
error_step_raw = body.validated_data.get("error_step")
error_step = ErrorStep(error_step_raw) if error_step_raw else None
- # `update_status.execute` does its own `SELECT FOR UPDATE` on the
- # row, so we catch the missing-row case here instead of pre-fetching
- # (which would just be a wasted query and still race the worker that
- # deletes the row between the two reads). `Deployment.DoesNotExist`
- # otherwise bubbles up as a 500.
- try:
- deployment = update_status.execute(
- update_status.UpdateStatusInput(
- deployment_id=deployment_id,
- status=target,
- cloudflare_deployment_id=body.validated_data.get("cloudflare_deployment_id") or None,
- deployment_url=body.validated_data.get("deployment_url") or None,
- error_message=body.validated_data.get("error_message") or None,
- error_step=error_step,
- started_at=body.validated_data.get("started_at"),
- finished_at=body.validated_data.get("finished_at"),
+ # InternalAPIAuthentication does not set team context. Resolve the row
+ # with `all_teams`, then enter scope so ModelActivityMixin and any
+ # ProductTeamModel writes inside the transition use the deployment's
+ # canonical team.
+ deployment_for_scope = self._get_deployment(deployment_id)
+ with team_scope(deployment_for_scope.team_id, canonical=True):
+ try:
+ deployment = update_status.execute(
+ update_status.UpdateStatusInput(
+ deployment_id=deployment_id,
+ status=target,
+ cloudflare_deployment_id=body.validated_data.get("cloudflare_deployment_id") or None,
+ deployment_url=body.validated_data.get("deployment_url") or None,
+ error_message=body.validated_data.get("error_message") or None,
+ error_step=error_step,
+ started_at=body.validated_data.get("started_at"),
+ finished_at=body.validated_data.get("finished_at"),
+ )
)
- )
- except Deployment.DoesNotExist as exc:
- raise NotFound(f"Deployment {deployment_id} not found.") from exc
- except InvalidStatusTransition as exc:
- logger.warning(
- "internal_deployments.invalid_transition",
- deployment_id=str(deployment_id),
- current=str(exc.current),
- target=str(exc.target),
- )
- return Response({"detail": str(exc)}, status=status.HTTP_409_CONFLICT)
+ except Deployment.DoesNotExist as exc:
+ raise NotFound(f"Deployment {deployment_id} not found.") from exc
+ except InvalidStatusTransition as exc:
+ logger.warning(
+ "internal_deployments.invalid_transition",
+ deployment_id=str(deployment_id),
+ current=str(exc.current),
+ target=str(exc.target),
+ )
+ return Response({"detail": str(exc)}, status=status.HTTP_409_CONFLICT)
- return Response(DeploymentSerializer(deployment).data, status=status.HTTP_200_OK)
+ return Response(DeploymentSerializer(deployment).data, status=status.HTTP_200_OK)
@extend_schema(exclude=True)
def events(self, request: Request, deployment_id: str, *args: Any, **kwargs: Any) -> Response:
@@ -167,13 +169,14 @@ class InternalDeploymentTransitionsViewSet(viewsets.ViewSet):
body = InternalEventInputSerializer(data=request.data)
body.is_valid(raise_exception=True)
- event = DeploymentEvent.objects.create(
- deployment_id=deployment.pk,
- team_id=deployment.team_id,
- event_type=body.validated_data["event_type"],
- payload=body.validated_data.get("payload") or {},
- )
- return Response(
- {"id": str(event.id), "occurred_at": event.occurred_at.isoformat()},
- status=status.HTTP_202_ACCEPTED,
- )
+ with team_scope(deployment.team_id, canonical=True):
+ event = DeploymentEvent.objects.create(
+ deployment_id=deployment.pk,
+ team_id=deployment.team_id,
+ event_type=body.validated_data["event_type"],
+ payload=body.validated_data.get("payload") or {},
+ )
+ return Response(
+ {"id": str(event.id), "occurred_at": event.occurred_at.isoformat()},
+ status=status.HTTP_202_ACCEPTED,
+ )
diff --git a/products/deployments/backend/migrations/0005_deploymentproject_github_tracking.py b/products/deployments/backend/migrations/0005_deploymentproject_github_tracking.py
new file mode 100644
index 000000000000..d7bcfd6fd619
--- /dev/null
+++ b/products/deployments/backend/migrations/0005_deploymentproject_github_tracking.py
@@ -0,0 +1,17 @@
+# Generated manually for Deployments GitHub repository tracking.
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("deployments", "0004_alter_deploymentevent_managers_and_more"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="deploymentproject",
+ name="github_repo_id",
+ field=models.BigIntegerField(blank=True, null=True),
+ ),
+ ]
diff --git a/products/deployments/backend/migrations/0006_deploymentproject_github_indexes_concurrent.py b/products/deployments/backend/migrations/0006_deploymentproject_github_indexes_concurrent.py
new file mode 100644
index 000000000000..1ab38786c9ee
--- /dev/null
+++ b/products/deployments/backend/migrations/0006_deploymentproject_github_indexes_concurrent.py
@@ -0,0 +1,19 @@
+# Generated manually for Deployments GitHub repository tracking indexes.
+
+from django.contrib.postgres.operations import AddIndexConcurrently
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ atomic = False
+
+ dependencies = [
+ ("deployments", "0005_deploymentproject_github_tracking"),
+ ]
+
+ operations = [
+ AddIndexConcurrently(
+ model_name="deploymentproject",
+ index=models.Index(fields=("team_id", "github_integration_id"), name="deploy_project_team_int_idx"),
+ ),
+ ]
diff --git a/products/deployments/backend/migrations/0007_deploymentproject_github_repo_unique_index_concurrent.py b/products/deployments/backend/migrations/0007_deploymentproject_github_repo_unique_index_concurrent.py
new file mode 100644
index 000000000000..6632017bce91
--- /dev/null
+++ b/products/deployments/backend/migrations/0007_deploymentproject_github_repo_unique_index_concurrent.py
@@ -0,0 +1,37 @@
+# Generated manually for Deployments GitHub repository uniqueness.
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ atomic = False
+
+ dependencies = [
+ ("deployments", "0006_deploymentproject_github_indexes_concurrent"),
+ ]
+
+ operations = [
+ migrations.SeparateDatabaseAndState(
+ state_operations=[
+ migrations.AddConstraint(
+ model_name="deploymentproject",
+ constraint=models.UniqueConstraint(
+ condition=models.Q(("github_repo_id__isnull", False))
+ & (models.Q(("deleted", False)) | models.Q(("deleted__isnull", True))),
+ fields=("team_id", "github_repo_id"),
+ name="deploy_project_team_repo_uniq",
+ ),
+ ),
+ ],
+ database_operations=[
+ migrations.RunSQL(
+ sql="""
+ CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS "deploy_project_team_repo_uniq"
+ ON "deployments_deploymentproject" ("team_id", "github_repo_id")
+ WHERE ("github_repo_id" IS NOT NULL AND (NOT "deleted" OR "deleted" IS NULL));
+ """,
+ reverse_sql='DROP INDEX CONCURRENTLY IF EXISTS "deploy_project_team_repo_uniq";',
+ ),
+ ],
+ ),
+ ]
diff --git a/products/deployments/backend/migrations/max_migration.txt b/products/deployments/backend/migrations/max_migration.txt
index a5b64b0a0da5..e4314716d364 100644
--- a/products/deployments/backend/migrations/max_migration.txt
+++ b/products/deployments/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0004_alter_deploymentevent_managers_and_more
+0007_deploymentproject_github_repo_unique_index_concurrent
diff --git a/products/deployments/backend/models.py b/products/deployments/backend/models.py
index ca15a1bfbdad..2367ad61e8ef 100644
--- a/products/deployments/backend/models.py
+++ b/products/deployments/backend/models.py
@@ -41,12 +41,11 @@ class DeploymentProject(ModelActivityMixin, ProductTeamModel, DeletedMetaFields)
# Source
repo_url = models.URLField(max_length=1024)
default_branch = models.CharField(max_length=255, default="main")
- # Pointer to the team's `posthog.Integration` row for the GitHub App that
- # owns access to this repo. We resolve to a short-lived access token at
- # deploy-time via `GitHubIntegration(integration).integration.sensitive_config`.
- # BigIntegerField (no FK) keeps the ProductTeamModel cross-app boundary clean,
- # matching the pattern used for `created_by_id`.
+ # Existing PostHog GitHub integration used for repo/branch access. These
+ # are plain ids because integrations live in the main app and Deployments
+ # keeps product-owned tenant data behind ProductTeamModel.team_id.
github_integration_id = models.BigIntegerField(null=True, blank=True)
+ github_repo_id = models.BigIntegerField(null=True, blank=True)
# Build config
# Null = build worker infers the command from `framework` (or auto-detects
@@ -83,8 +82,17 @@ class DeploymentProject(ModelActivityMixin, ProductTeamModel, DeletedMetaFields)
condition=models.Q(deleted=False) | models.Q(deleted__isnull=True),
name="unique_deploymentproject_slug_per_team",
),
+ models.UniqueConstraint(
+ fields=("team_id", "github_repo_id"),
+ condition=models.Q(github_repo_id__isnull=False)
+ & (models.Q(deleted=False) | models.Q(deleted__isnull=True)),
+ name="deploy_project_team_repo_uniq",
+ ),
+ ]
+ indexes = [
+ models.Index(fields=["team_id", "-created_at"]),
+ models.Index(fields=("team_id", "github_integration_id"), name="deploy_project_team_int_idx"),
]
- indexes = [models.Index(fields=["team_id", "-created_at"])]
def __str__(self) -> str:
return f"DeploymentProject {self.slug} ({self.id})"
diff --git a/products/deployments/backend/serializers/__init__.py b/products/deployments/backend/serializers/__init__.py
index 57520ac769bc..88b9368eecaa 100644
--- a/products/deployments/backend/serializers/__init__.py
+++ b/products/deployments/backend/serializers/__init__.py
@@ -1,9 +1,11 @@
from .deployment import DeploymentSerializer
from .event import DeploymentEventSerializer
-from .project import DeploymentProjectSerializer
+from .project import DeploymentProjectCreateSerializer, DeploymentProjectSerializer, DeploymentProjectWriteSerializer
__all__ = [
"DeploymentEventSerializer",
+ "DeploymentProjectCreateSerializer",
"DeploymentProjectSerializer",
+ "DeploymentProjectWriteSerializer",
"DeploymentSerializer",
]
diff --git a/products/deployments/backend/serializers/project.py b/products/deployments/backend/serializers/project.py
index bd649c507fe2..d70efd16d5e0 100644
--- a/products/deployments/backend/serializers/project.py
+++ b/products/deployments/backend/serializers/project.py
@@ -1,24 +1,31 @@
"""Serializer for DeploymentProject.
-`github_integration` is the id of a `posthog.Integration` row with `kind="github"`
-that belongs to the same team. The serializer validates ownership and kind at
-write time. Secrets (the access token) never travel through the serializer —
-they live on the Integration row and are resolved at deploy time.
+Repository selection is keyed by ``github_integration_id`` + ``github_repo_id``.
+``repo_url`` is derived from GitHub and exposed as read-only display metadata.
+Secrets (the access token) never travel through the serializer — they live on
+the Integration row and are resolved at deploy time.
"""
from __future__ import annotations
+from collections.abc import Mapping
from typing import Any
-from urllib.parse import urlparse
from drf_spectacular.utils import extend_schema_field
from rest_framework import serializers
-from posthog.models.integration import Integration
-
from ..models import DeploymentProject
+class RejectUnknownFieldsMixin(serializers.Serializer):
+ def to_internal_value(self, data: Any) -> Any:
+ if isinstance(data, Mapping):
+ unknown_fields = set(data) - set(self.fields)
+ if unknown_fields:
+ raise serializers.ValidationError(dict.fromkeys(sorted(unknown_fields), "Unknown field."))
+ return super().to_internal_value(data)
+
+
class DeploymentProjectSerializer(serializers.ModelSerializer):
id = serializers.UUIDField(read_only=True, help_text="Unique identifier for the deployment project.")
name = serializers.CharField(max_length=200, help_text="Human-readable project name shown in the UI.")
@@ -32,25 +39,24 @@ class DeploymentProjectSerializer(serializers.ModelSerializer):
)
repo_url = serializers.URLField(
max_length=1024,
- help_text="HTTPS URL of the source repository this project deploys from.",
+ read_only=True,
+ help_text="HTTPS URL of the connected GitHub repository, resolved from the selected repository id.",
)
default_branch = serializers.CharField(
max_length=255,
required=False,
- default="main",
- help_text="Branch the project deploys from when no commit SHA is pinned. Defaults to `main`.",
+ help_text="Branch PostHog tracks for deployment updates. Defaults to the repository default branch.",
)
- github_integration = serializers.IntegerField(
- source="github_integration_id",
+ github_integration_id = serializers.IntegerField(
required=False,
allow_null=True,
- help_text=(
- "ID of the `posthog.Integration` row (kind=github) the project uses to read this "
- "repository. Must belong to the same team. The actual access token lives on the "
- "Integration row and is never exposed through this serializer."
- ),
+ help_text="Existing PostHog GitHub integration id used for repository access.",
+ )
+ github_repo_id = serializers.IntegerField(
+ required=False,
+ allow_null=True,
+ help_text="Stable GitHub repository identifier selected from the existing integration's repository list.",
)
-
build_command = serializers.CharField(
required=False,
allow_null=True,
@@ -127,7 +133,8 @@ class DeploymentProjectSerializer(serializers.ModelSerializer):
"slug",
"repo_url",
"default_branch",
- "github_integration",
+ "github_integration_id",
+ "github_repo_id",
"build_command",
"output_dir",
"framework",
@@ -142,6 +149,7 @@ class DeploymentProjectSerializer(serializers.ModelSerializer):
]
read_only_fields = [
"id",
+ "repo_url",
"cloudflare_project_name",
"subdomain",
"cloudflare_ready_at",
@@ -155,27 +163,124 @@ class DeploymentProjectSerializer(serializers.ModelSerializer):
def get_is_ready_to_deploy(self, obj: DeploymentProject) -> bool:
return obj.cloudflare_ready_at is not None and obj.github_integration_id is not None
- def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:
- # The field uses `source="github_integration_id"`, so the int lands under that key.
- integration_id = attrs.get("github_integration_id")
- if integration_id is None:
- return attrs
- team = self.context["get_team"]()
- if not Integration.objects.filter(id=integration_id, team_id=team.id, kind="github").exists():
- raise serializers.ValidationError(
- {"github_integration": "Integration not found or is not a GitHub integration for this team."}
- )
- return attrs
-
- def validate_repo_url(self, value: str) -> str:
- # v1 deploys from github.com only. Without this check the field
- # would accept any URL — including http://169.254.169.254/... or
- # other internal/link-local hosts the build worker / GitHub
- # adapter would then connect to (SSRF). Restricting scheme +
- # host is the smallest fix that closes that vector.
- parsed = urlparse(value)
- if parsed.scheme != "https":
- raise serializers.ValidationError("repo_url must use HTTPS.")
- if (parsed.hostname or "").lower() != "github.com":
- raise serializers.ValidationError("repo_url must point to github.com.")
- return value
+
+class DeploymentProjectWriteSerializer(RejectUnknownFieldsMixin, serializers.ModelSerializer):
+ name = serializers.CharField(max_length=200, help_text="Human-readable project name shown in the UI.")
+ slug = serializers.SlugField(
+ max_length=80,
+ help_text=(
+ "URL-safe handle. Combined with the team id to form the Cloudflare project name; "
+ "the actual subdomain comes from Cloudflare and is returned in the read-only "
+ "`subdomain` field. Must be unique per team."
+ ),
+ )
+ default_branch = serializers.CharField(
+ max_length=255,
+ required=False,
+ help_text="Branch PostHog tracks for deployment updates. Defaults to the repository default branch.",
+ )
+ github_integration_id = serializers.IntegerField(
+ required=False,
+ allow_null=True,
+ help_text="Existing PostHog GitHub integration id used for repository access.",
+ )
+ github_repo_id = serializers.IntegerField(
+ required=False,
+ allow_null=True,
+ help_text="Stable GitHub repository identifier selected from the existing integration's repository list.",
+ )
+ build_command = serializers.CharField(
+ required=False,
+ allow_null=True,
+ allow_blank=True,
+ help_text=(
+ "Optional shell command run inside the build container. Null = the build worker "
+ "infers it from `framework` (or auto-detection if framework is also null)."
+ ),
+ )
+ output_dir = serializers.CharField(
+ max_length=255,
+ required=False,
+ default="dist",
+ help_text="Directory containing the built static site, relative to the repository root.",
+ )
+ framework = serializers.CharField(
+ max_length=50,
+ required=False,
+ allow_null=True,
+ allow_blank=True,
+ help_text="Optional framework hint (e.g. `nextjs`, `vite`, `astro`). Null = auto-detect.",
+ )
+ inject_posthog_snippet = serializers.BooleanField(
+ required=False,
+ default=False,
+ help_text=(
+ "If true, the build injects a PostHog snippet into every HTML file that registers "
+ "`release = deployment_id` as a super-property — runtime exceptions are then linked "
+ "back to the deployment that introduced them."
+ ),
+ )
+
+ class Meta:
+ model = DeploymentProject
+ fields = [
+ "name",
+ "slug",
+ "default_branch",
+ "github_integration_id",
+ "github_repo_id",
+ "build_command",
+ "output_dir",
+ "framework",
+ "inject_posthog_snippet",
+ ]
+
+
+class DeploymentProjectCreateSerializer(RejectUnknownFieldsMixin, serializers.Serializer):
+ name = serializers.CharField(max_length=200, help_text="Human-readable project name shown in the UI.")
+ slug = serializers.SlugField(
+ max_length=80,
+ help_text="URL-safe handle. Becomes the subdomain `{slug}.posthog-app.com`. Must be unique per team.",
+ )
+ default_branch = serializers.CharField(
+ max_length=255,
+ required=False,
+ help_text="Branch PostHog tracks for deployment updates. Defaults to the repository default branch.",
+ )
+ github_integration_id = serializers.IntegerField(
+ help_text="Existing PostHog GitHub integration id used for repository access."
+ )
+ github_repo_id = serializers.IntegerField(
+ help_text="Stable GitHub repository identifier selected from the existing integration's repository list."
+ )
+ build_command = serializers.CharField(
+ required=False,
+ allow_null=True,
+ allow_blank=True,
+ help_text=(
+ "Optional shell command run inside the build container. Null = the build worker "
+ "infers it from `framework` (or auto-detection if framework is also null)."
+ ),
+ )
+ output_dir = serializers.CharField(
+ max_length=255,
+ required=False,
+ default="dist",
+ help_text="Directory containing the built static site, relative to the repository root.",
+ )
+ framework = serializers.CharField(
+ max_length=50,
+ required=False,
+ allow_null=True,
+ allow_blank=True,
+ help_text="Optional framework hint (e.g. `nextjs`, `vite`, `astro`). Null = auto-detect.",
+ )
+ inject_posthog_snippet = serializers.BooleanField(
+ required=False,
+ default=False,
+ help_text=(
+ "If true, the build injects a PostHog snippet into every HTML file that registers "
+ "`release = deployment_id` as a super-property — runtime exceptions are then linked "
+ "back to the deployment that introduced them."
+ ),
+ )
diff --git a/products/deployments/backend/services/provision_project.py b/products/deployments/backend/services/provision_project.py
index 5dbce399a15c..adbdd4e6e045 100644
--- a/products/deployments/backend/services/provision_project.py
+++ b/products/deployments/backend/services/provision_project.py
@@ -9,9 +9,9 @@ worse — the HTTP response has already been written by the time the
callback fires, so the 502 path becomes unreachable.
If the Cloudflare call fails, no local row exists; the orphaned-CF-project
-risk is zero (there isn't one). If the local insert later fails (rare;
-the partial unique constraint can't fire here), the orphaned CF project
-gets reaped by a periodic cleanup task (deferred to v2).
+risk is zero (there isn't one). If the local insert later loses a uniqueness
+race, the orphaned CF project gets reaped by a periodic cleanup task
+(deferred to v2).
"""
from __future__ import annotations
@@ -34,6 +34,7 @@ class ProvisionInput:
repo_url: str
default_branch: str
github_integration_id: int | None
+ github_repo_id: int | None
build_command: str | None
output_dir: str
framework: str | None
@@ -69,6 +70,7 @@ def execute(
repo_url=payload.repo_url,
default_branch=payload.default_branch,
github_integration_id=payload.github_integration_id,
+ github_repo_id=payload.github_repo_id,
build_command=payload.build_command,
output_dir=payload.output_dir,
framework=payload.framework,
diff --git a/products/deployments/backend/test/test_deployments_api.py b/products/deployments/backend/test/test_deployments_api.py
index 3ecdc5b75ae5..9c611ef84f6c 100644
--- a/products/deployments/backend/test/test_deployments_api.py
+++ b/products/deployments/backend/test/test_deployments_api.py
@@ -11,19 +11,23 @@ The feature flag gate (`DeploymentsAccessPermission`) is mocked via
from __future__ import annotations
from posthog.test.base import APIBaseTest
-from unittest.mock import patch
+from unittest.mock import MagicMock, patch
from django.utils import timezone
from parameterized import parameterized
from rest_framework import status
+from posthog.constants import AvailableFeature
from posthog.models.integration import Integration
from posthog.models.utils import uuid7
+from products.deployments.backend.adapters.github import GitHubBranch, GitHubRepository
from products.deployments.backend.models import Deployment, DeploymentProject
from products.deployments.backend.test._helpers import DeploymentsTeamScopedTestMixin
+from ee.models.rbac.access_control import AccessControl
+
class _BaseDeploymentsAPITest(DeploymentsTeamScopedTestMixin, APIBaseTest):
def setUp(self) -> None:
@@ -40,6 +44,40 @@ class _BaseDeploymentsAPITest(DeploymentsTeamScopedTestMixin, APIBaseTest):
class TestDeploymentProjectsAPI(_BaseDeploymentsAPITest):
+ def _enable_advanced_permissions(self) -> None:
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.ADVANCED_PERMISSIONS, "name": AvailableFeature.ADVANCED_PERMISSIONS}
+ ]
+ self.organization.save(update_fields=["available_product_features"])
+
+ def _restrict_integrations_resource(self) -> None:
+ self._enable_advanced_permissions()
+ AccessControl.objects.create(
+ team=self.team,
+ resource="integration",
+ resource_id=None,
+ access_level="none",
+ )
+
+ def _restrict_integration(self, integration: Integration) -> None:
+ self._enable_advanced_permissions()
+ AccessControl.objects.create(
+ team=self.team,
+ resource="integration",
+ resource_id=str(integration.id),
+ access_level="none",
+ )
+
+ def _github_integration(self) -> Integration:
+ return Integration.objects.create(
+ team=self.team,
+ kind=Integration.IntegrationKind.GITHUB.value,
+ integration_id="12345",
+ config={"account": {"name": "PostHog", "type": "Organization"}},
+ sensitive_config={"access_token": "ghs_test"},
+ errors="",
+ )
+
def test_list_returns_empty_when_no_projects(self) -> None:
response = self.client.get(f"/api/projects/{self.team.id}/deployment_projects/")
self.assertEqual(response.status_code, status.HTTP_200_OK)
@@ -65,35 +103,21 @@ class TestDeploymentProjectsAPI(_BaseDeploymentsAPITest):
slugs = [p["slug"] for p in results]
self.assertEqual(slugs, ["alive"])
- def test_github_integration_is_persisted_and_returned(self) -> None:
- # POST accepts a github_integration id pointing at the team's
- # `posthog.Integration` row; the FK is returned on GETs (it's a
- # reference, not a secret — the access token lives on Integration).
- integration = Integration.objects.create(
- team=self.team,
- kind="github",
- integration_id="42",
- sensitive_config={"access_token": "ghs_short_lived"},
- )
+ def test_create_project_rejects_repo_url_input(self) -> None:
response = self.client.post(
f"/api/projects/{self.team.id}/deployment_projects/",
{
"name": "Site",
"slug": "site",
"repo_url": "https://github.com/example-org/site",
- "github_integration": integration.id,
+ "github_integration_id": 42,
+ "github_repo_id": 42,
},
format="json",
)
- self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.content)
- body = response.json()
- self.assertEqual(body["github_integration"], integration.id)
- # Verify the FK is stored on the row.
- project = DeploymentProject.all_teams.get(pk=body["id"])
- self.assertEqual(project.github_integration_id, integration.id)
- # No secrets exposed via the API surface.
- self.assertNotIn("access_token", body)
- self.assertNotIn("sensitive_config", body)
+
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST, response.content)
+ self.assertEqual(response.json().get("attr"), "repo_url")
def test_github_integration_must_belong_to_team(self) -> None:
# An integration from another team is not selectable.
@@ -109,13 +133,12 @@ class TestDeploymentProjectsAPI(_BaseDeploymentsAPITest):
{
"name": "Site",
"slug": "site",
- "repo_url": "https://github.com/example-org/site",
- "github_integration": outsider.id,
+ "github_integration_id": outsider.id,
+ "github_repo_id": 42,
},
format="json",
)
- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST, response.content)
- self.assertEqual(response.json().get("attr"), "github_integration")
+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND, response.content)
def test_github_integration_kind_must_be_github(self) -> None:
slack = Integration.objects.create(
@@ -129,21 +152,32 @@ class TestDeploymentProjectsAPI(_BaseDeploymentsAPITest):
{
"name": "Site",
"slug": "site",
- "repo_url": "https://github.com/example-org/site",
- "github_integration": slack.id,
+ "github_integration_id": slack.id,
+ "github_repo_id": 42,
},
format="json",
)
- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST, response.content)
- self.assertEqual(response.json().get("attr"), "github_integration")
+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND, response.content)
+
+ @patch("products.deployments.backend.api.deployment_projects.get_github_adapter")
+ def test_create_provisions_cloudflare_via_null_adapter(self, mock_get_github_adapter: MagicMock) -> None:
+ integration = self._github_integration()
+ adapter = mock_get_github_adapter.return_value
+ adapter.get_repository_by_id.return_value = GitHubRepository(
+ id=42,
+ full_name="example-org/site",
+ default_branch="main",
+ html_url="https://github.com/example-org/site",
+ )
+ adapter.get_branch.return_value = GitHubBranch(name="main", sha="abc123")
- def test_create_provisions_cloudflare_via_null_adapter(self) -> None:
response = self.client.post(
f"/api/projects/{self.team.id}/deployment_projects/",
{
"name": "Site",
"slug": "site",
- "repo_url": "https://github.com/example-org/site",
+ "github_integration_id": integration.id,
+ "github_repo_id": 42,
},
format="json",
)
@@ -158,6 +192,173 @@ class TestDeploymentProjectsAPI(_BaseDeploymentsAPITest):
self.assertEqual(body["subdomain"], f"{self.team.id}-site.pages.dev")
self.assertIsNotNone(body["cloudflare_ready_at"])
+ @patch("products.deployments.backend.api.deployment_projects.get_github_adapter")
+ def test_create_project_uses_existing_github_integration(self, mock_get_github_adapter: MagicMock) -> None:
+ integration = self._github_integration()
+ adapter = mock_get_github_adapter.return_value
+ adapter.get_repository_by_id.return_value = GitHubRepository(
+ id=42,
+ full_name="PostHog/posthog",
+ default_branch="master",
+ html_url="https://github.com/PostHog/posthog",
+ )
+ adapter.get_branch.return_value = GitHubBranch(name="master", sha="abc123")
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/deployment_projects/",
+ {
+ "name": "Site",
+ "slug": "site",
+ "github_integration_id": integration.id,
+ "github_repo_id": 42,
+ },
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.content)
+ body = response.json()
+ self.assertEqual(body["github_integration_id"], integration.id)
+ self.assertEqual(body["github_repo_id"], 42)
+ self.assertEqual(body["repo_url"], "https://github.com/PostHog/posthog")
+ self.assertEqual(body["default_branch"], "master")
+ project = DeploymentProject.all_teams.get(team_id=self.team.id, github_repo_id=42)
+ self.assertEqual(project.github_integration_id, integration.id)
+
+ @patch("products.deployments.backend.api.deployment_projects.get_github_adapter")
+ def test_update_project_rejects_repo_url_input(self, mock_get_github_adapter: MagicMock) -> None:
+ integration = self._github_integration()
+ project = DeploymentProject.objects.create(
+ team_id=self.team.id,
+ name="Site",
+ slug="site",
+ repo_url="https://github.com/PostHog/posthog",
+ github_integration_id=integration.id,
+ github_repo_id=42,
+ default_branch="master",
+ )
+
+ response = self.client.put(
+ f"/api/projects/{self.team.id}/deployment_projects/{project.id}/",
+ {
+ "name": "Renamed site",
+ "slug": "site",
+ "repo_url": "https://github.com/Other/repo",
+ "github_integration_id": integration.id,
+ "github_repo_id": 42,
+ },
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST, response.content)
+ self.assertEqual(response.json().get("attr"), "repo_url")
+ mock_get_github_adapter.assert_not_called()
+ project.refresh_from_db()
+ self.assertEqual(project.repo_url, "https://github.com/PostHog/posthog")
+
+ @parameterized.expand(
+ [
+ ("resource",),
+ ("object",),
+ ]
+ )
+ @patch("products.deployments.backend.api.deployment_projects.get_github_adapter")
+ def test_create_project_rejects_restricted_github_integration(
+ self, restriction_kind: str, mock_get_github_adapter: MagicMock
+ ) -> None:
+ integration = self._github_integration()
+ if restriction_kind == "resource":
+ self._restrict_integrations_resource()
+ else:
+ self._restrict_integration(integration)
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/deployment_projects/",
+ {
+ "name": "Site",
+ "slug": "site",
+ "github_integration_id": integration.id,
+ "github_repo_id": 42,
+ },
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
+ mock_get_github_adapter.return_value.get_repository_by_id.assert_not_called()
+
+ def test_create_project_rejects_non_project_github_integration(self) -> None:
+ other_team = self.organization.teams.create(name="Other team")
+ integration = Integration.objects.create(
+ team=other_team,
+ kind=Integration.IntegrationKind.GITHUB.value,
+ integration_id="12345",
+ config={},
+ sensitive_config={"access_token": "ghs_test"},
+ errors="",
+ )
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/deployment_projects/",
+ {
+ "name": "Site",
+ "slug": "site",
+ "github_integration_id": integration.id,
+ "github_repo_id": 42,
+ "default_branch": "master",
+ },
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
+
+ @patch("products.deployments.backend.api.deployment_projects.get_github_adapter")
+ def test_refresh_project_returns_current_branch_sha(self, mock_get_github_adapter: MagicMock) -> None:
+ integration = self._github_integration()
+ project = DeploymentProject.objects.create(
+ team_id=self.team.id,
+ name="Site",
+ slug="site",
+ repo_url="https://github.com/PostHog/posthog",
+ github_integration_id=integration.id,
+ github_repo_id=42,
+ default_branch="master",
+ )
+ adapter = mock_get_github_adapter.return_value
+ adapter.get_repository_by_id.return_value = GitHubRepository(
+ id=42,
+ full_name="PostHog/posthog",
+ default_branch="main",
+ html_url="https://github.com/PostHog/posthog",
+ )
+ adapter.get_branch.return_value = GitHubBranch(name="master", sha="new-sha")
+
+ response = self.client.post(f"/api/projects/{self.team.id}/deployment_projects/{project.id}/refresh/")
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)
+ body = response.json()
+ self.assertEqual(body["default_branch"], "master")
+ self.assertEqual(body["commit_sha"], "new-sha")
+ project.refresh_from_db()
+ self.assertEqual(project.default_branch, "master")
+
+ @patch("products.deployments.backend.api.deployment_projects.get_github_adapter")
+ def test_refresh_project_rejects_restricted_github_integration(self, mock_get_github_adapter: MagicMock) -> None:
+ integration = self._github_integration()
+ self._restrict_integration(integration)
+ project = DeploymentProject.objects.create(
+ team_id=self.team.id,
+ name="Site",
+ slug="site",
+ repo_url="https://github.com/PostHog/posthog",
+ github_integration_id=integration.id,
+ github_repo_id=42,
+ default_branch="master",
+ )
+
+ response = self.client.post(f"/api/projects/{self.team.id}/deployment_projects/{project.id}/refresh/")
+
+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
+ mock_get_github_adapter.return_value.get_repository_by_id.assert_not_called()
+
def test_destroy_is_soft_delete(self) -> None:
project = DeploymentProject.objects.create(
team_id=self.team.id,
@@ -313,6 +514,28 @@ class TestDeploymentsAPINested(_BaseDeploymentsAPITest):
class TestDeploymentsFeatureFlag(_BaseDeploymentsAPITest):
"""Re-verifies the feature-flag gate over the new nested URL."""
+ @patch("products.deployments.backend.api.deployment_projects.get_github_adapter")
+ def test_create_feature_flag_off_does_not_call_github(self, mock_get_github_adapter: MagicMock) -> None:
+ self._flag_patcher.stop()
+ with patch(
+ "products.deployments.backend.access.posthoganalytics.feature_enabled",
+ return_value=False,
+ ):
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/deployment_projects/",
+ {
+ "name": "Site",
+ "slug": "site",
+ "github_integration_id": 42,
+ "github_repo_id": 42,
+ },
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+ mock_get_github_adapter.assert_not_called()
+ self._flag_patcher.start()
+
@parameterized.expand(
[
("flag on returns empty list", True, status.HTTP_200_OK),
diff --git a/products/deployments/backend/test/test_github_adapter.py b/products/deployments/backend/test/test_github_adapter.py
new file mode 100644
index 000000000000..65440b5e3e02
--- /dev/null
+++ b/products/deployments/backend/test/test_github_adapter.py
@@ -0,0 +1,62 @@
+from __future__ import annotations
+
+from typing import cast
+
+from unittest import TestCase
+from unittest.mock import MagicMock, patch
+
+from posthog.models.integration import Integration
+
+from products.deployments.backend.adapters.github import (
+ DEPLOYMENTS_GITHUB_API_TIMEOUT_SECONDS,
+ GitHubIntegrationAdapter,
+)
+
+
+class TestGitHubIntegrationAdapter(TestCase):
+ @patch("products.deployments.backend.adapters.github.GitHubIntegration._gh_api_get")
+ def test_get_json_uses_short_request_path_timeout(self, mock_gh_api_get: MagicMock) -> None:
+ mock_gh_api_get.return_value = {"ok": True}
+ adapter = GitHubIntegrationAdapter()
+ integration_mock = MagicMock()
+ integration_mock.kind = "github"
+ integration = cast(Integration, integration_mock)
+
+ payload = adapter._get_json(
+ integration=integration,
+ path="/repositories/42",
+ endpoint="/repositories/{repository_id}",
+ )
+
+ self.assertEqual(payload, {"ok": True})
+ mock_gh_api_get.assert_called_once_with(
+ "/repositories/42",
+ endpoint="/repositories/{repository_id}",
+ timeout=DEPLOYMENTS_GITHUB_API_TIMEOUT_SECONDS,
+ )
+
+ def test_get_repository_by_id_resolves_current_repository_by_numeric_id(self) -> None:
+ adapter = GitHubIntegrationAdapter()
+ integration = cast(Integration, MagicMock())
+
+ with patch.object(
+ adapter,
+ "_get_json",
+ return_value={
+ "id": 42,
+ "full_name": "PostHog/renamed-repo",
+ "default_branch": "master",
+ "html_url": "https://github.com/PostHog/renamed-repo",
+ },
+ ) as get_json:
+ repository = adapter.get_repository_by_id(integration=integration, github_repo_id=42)
+
+ get_json.assert_called_once_with(
+ integration=integration,
+ path="/repositories/42",
+ endpoint="/repositories/{repository_id}",
+ )
+ self.assertEqual(repository.id, 42)
+ self.assertEqual(repository.full_name, "PostHog/renamed-repo")
+ self.assertEqual(repository.default_branch, "master")
+ self.assertEqual(repository.html_url, "https://github.com/PostHog/renamed-repo")
diff --git a/products/deployments/backend/test/test_internal_auth.py b/products/deployments/backend/test/test_internal_auth.py
index f15ce06027bd..5698f9f81691 100644
--- a/products/deployments/backend/test/test_internal_auth.py
+++ b/products/deployments/backend/test/test_internal_auth.py
@@ -15,6 +15,8 @@ from django.utils import timezone
from rest_framework import status as drf_status
+from posthog.models.scoping import reset_current_team_id, set_current_team_id
+
from products.deployments.backend.domain.status import Status
from products.deployments.backend.models import Deployment, DeploymentEvent, DeploymentProject
from products.deployments.backend.test._helpers import DeploymentsTeamScopedTestMixin
@@ -60,6 +62,17 @@ class TestInternalDeploymentTransitions(DeploymentsTeamScopedTestMixin, APIBaseT
self.assertEqual(self.deployment.status, Deployment.Status.INITIALIZING.value)
self.assertIsNotNone(self.deployment.started_at)
+ def test_valid_secret_runs_without_outer_team_scope(self) -> None:
+ token = set_current_team_id(None)
+ try:
+ response = self._post_transition({"status": Status.INITIALIZING.value})
+ finally:
+ reset_current_team_id(token)
+
+ self.assertEqual(response.status_code, drf_status.HTTP_200_OK, response.content)
+ self.deployment.refresh_from_db()
+ self.assertEqual(self.deployment.status, Deployment.Status.INITIALIZING.value)
+
def test_missing_secret_returns_401(self) -> None:
response = self._post_transition({"status": Status.INITIALIZING.value}, secret=None)
self.assertEqual(response.status_code, drf_status.HTTP_401_UNAUTHORIZED)
@@ -138,6 +151,24 @@ class TestInternalDeploymentEvents(DeploymentsTeamScopedTestMixin, APIBaseTest):
self.assertEqual(event.payload, {"step": "install"})
self.assertEqual(event.team_id, self.team.id)
+ def test_creates_event_without_outer_team_scope(self) -> None:
+ token = set_current_team_id(None)
+ try:
+ response = self.client.post(
+ f"/api/internal/deployments/{self.deployment.id}/events/",
+ {"event_type": "step_started", "payload": {"step": "install"}},
+ format="json",
+ headers={"x-internal-api-secret": SECRET},
+ )
+ finally:
+ reset_current_team_id(token)
+
+ self.assertEqual(response.status_code, drf_status.HTTP_202_ACCEPTED, response.content)
+ self.assertEqual(
+ DeploymentEvent.all_teams.filter(deployment_id=self.deployment.pk, event_type="step_started").count(),
+ 1,
+ )
+
def test_missing_secret_returns_401(self) -> None:
response = self.client.post(
f"/api/internal/deployments/{self.deployment.id}/events/",
diff --git a/products/deployments/backend/test/test_models.py b/products/deployments/backend/test/test_models.py
index 26fae3b10955..98e05d2692c4 100644
--- a/products/deployments/backend/test/test_models.py
+++ b/products/deployments/backend/test/test_models.py
@@ -18,13 +18,19 @@ from products.deployments.backend.test._helpers import DeploymentsTeamScopedTest
class TestDeploymentProject(DeploymentsTeamScopedTestMixin, BaseTest):
- def _make_project(self, slug: str = "alpha") -> DeploymentProject:
+ def _make_project(
+ self,
+ slug: str = "alpha",
+ *,
+ github_repo_id: int | None = None,
+ ) -> DeploymentProject:
return DeploymentProject.objects.create(
team_id=self.team.id,
name=f"Project {slug}",
slug=slug,
repo_url="https://github.com/example-org/site",
default_branch="main",
+ github_repo_id=github_repo_id,
cloudflare_project_name=f"{self.team.id}-{slug}",
subdomain=f"{slug}.posthog-app.com",
cloudflare_ready_at=timezone.now(),
@@ -47,6 +53,28 @@ class TestDeploymentProject(DeploymentsTeamScopedTestMixin, BaseTest):
reused = self._make_project(slug="alpha")
self.assertNotEqual(reused.pk, original.pk)
+ def test_github_repo_uniqueness_per_team(self) -> None:
+ self._make_project(slug="alpha", github_repo_id=42)
+
+ with self.assertRaises(IntegrityError):
+ with transaction.atomic():
+ self._make_project(slug="beta", github_repo_id=42)
+
+ def test_soft_deleted_project_releases_github_repo(self) -> None:
+ original = self._make_project(slug="alpha", github_repo_id=42)
+ original.deleted = True
+ original.deleted_at = timezone.now()
+ original.save(update_fields=["deleted", "deleted_at"])
+
+ reused = self._make_project(slug="beta", github_repo_id=42)
+ self.assertNotEqual(reused.pk, original.pk)
+
+ def test_projects_without_github_repo_id_are_not_repo_constrained(self) -> None:
+ self._make_project(slug="alpha")
+ project = self._make_project(slug="beta")
+
+ self.assertIsNone(project.github_repo_id)
+
def test_current_deployment_accepts_null(self) -> None:
project = self._make_project()
self.assertIsNone(project.current_deployment_id)
diff --git a/products/deployments/frontend/generated/api.schemas.ts b/products/deployments/frontend/generated/api.schemas.ts
index 6e538bbed8dd..053a0b5090ee 100644
--- a/products/deployments/frontend/generated/api.schemas.ts
+++ b/products/deployments/frontend/generated/api.schemas.ts
@@ -22,20 +22,25 @@ export interface DeploymentProjectApi {
*/
slug: string
/**
- * HTTPS URL of the source repository this project deploys from.
+ * HTTPS URL of the connected GitHub repository, resolved from the selected repository id.
* @maxLength 1024
*/
- repo_url: string
+ readonly repo_url: string
/**
- * Branch the project deploys from when no commit SHA is pinned. Defaults to `main`.
+ * Branch PostHog tracks for deployment updates. Defaults to the repository default branch.
* @maxLength 255
*/
default_branch?: string
/**
- * ID of the `posthog.Integration` row (kind=github) the project uses to read this repository. Must belong to the same team. The actual access token lives on the Integration row and is never exposed through this serializer.
+ * Existing PostHog GitHub integration id used for repository access.
+ * @nullable
+ */
+ github_integration_id?: number | null
+ /**
+ * Stable GitHub repository identifier selected from the existing integration's repository list.
* @nullable
*/
- github_integration?: number | null
+ github_repo_id?: number | null
/**
* Optional shell command run inside the build container. Null = the build worker infers it from `framework` (or auto-detection if framework is also null).
* @nullable
@@ -85,6 +90,47 @@ export interface PaginatedDeploymentProjectListApi {
results: DeploymentProjectApi[]
}
+export interface DeploymentProjectCreateApi {
+ /**
+ * Human-readable project name shown in the UI.
+ * @maxLength 200
+ */
+ name: string
+ /**
+ * URL-safe handle. Becomes the subdomain `{slug}.posthog-app.com`. Must be unique per team.
+ * @maxLength 80
+ * @pattern ^[-a-zA-Z0-9_]+$
+ */
+ slug: string
+ /**
+ * Branch PostHog tracks for deployment updates. Defaults to the repository default branch.
+ * @maxLength 255
+ */
+ default_branch?: string
+ /** Existing PostHog GitHub integration id used for repository access. */
+ github_integration_id: number
+ /** Stable GitHub repository identifier selected from the existing integration's repository list. */
+ github_repo_id: number
+ /**
+ * Optional shell command run inside the build container. Null = the build worker infers it from `framework` (or auto-detection if framework is also null).
+ * @nullable
+ */
+ build_command?: string | null
+ /**
+ * Directory containing the built static site, relative to the repository root.
+ * @maxLength 255
+ */
+ output_dir?: string
+ /**
+ * Optional framework hint (e.g. `nextjs`, `vite`, `astro`). Null = auto-detect.
+ * @maxLength 50
+ * @nullable
+ */
+ framework?: string | null
+ /** If true, the build injects a PostHog snippet into every HTML file that registers `release = deployment_id` as a super-property — runtime exceptions are then linked back to the deployment that introduced them. */
+ inject_posthog_snippet?: boolean
+}
+
/**
* * `queued` - Queued
* `initializing` - Initializing
@@ -314,35 +360,33 @@ export interface PaginatedDeploymentEventListApi {
results: DeploymentEventApi[]
}
-export interface PatchedDeploymentProjectApi {
- /** Unique identifier for the deployment project. */
- readonly id?: string
+export interface DeploymentProjectWriteApi {
/**
* Human-readable project name shown in the UI.
* @maxLength 200
*/
- name?: string
+ name: string
/**
* URL-safe handle. Combined with the team id to form the Cloudflare project name; the actual subdomain comes from Cloudflare and is returned in the read-only `subdomain` field. Must be unique per team.
* @maxLength 80
* @pattern ^[-a-zA-Z0-9_]+$
*/
- slug?: string
- /**
- * HTTPS URL of the source repository this project deploys from.
- * @maxLength 1024
- */
- repo_url?: string
+ slug: string
/**
- * Branch the project deploys from when no commit SHA is pinned. Defaults to `main`.
+ * Branch PostHog tracks for deployment updates. Defaults to the repository default branch.
* @maxLength 255
*/
default_branch?: string
/**
- * ID of the `posthog.Integration` row (kind=github) the project uses to read this repository. Must belong to the same team. The actual access token lives on the Integration row and is never exposed through this serializer.
+ * Existing PostHog GitHub integration id used for repository access.
+ * @nullable
+ */
+ github_integration_id?: number | null
+ /**
+ * Stable GitHub repository identifier selected from the existing integration's repository list.
* @nullable
*/
- github_integration?: number | null
+ github_repo_id?: number | null
/**
* Optional shell command run inside the build container. Null = the build worker infers it from `framework` (or auto-detection if framework is also null).
* @nullable
@@ -361,26 +405,67 @@ export interface PatchedDeploymentProjectApi {
framework?: string | null
/** If true, the build injects a PostHog snippet into every HTML file that registers `release = deployment_id` as a super-property — runtime exceptions are then linked back to the deployment that introduced them. */
inject_posthog_snippet?: boolean
- /** Cloudflare Pages project name, assigned during provisioning. */
- readonly cloudflare_project_name?: string
- /** Public subdomain at which deployments of this project serve. */
- readonly subdomain?: string
+}
+
+export interface PatchedDeploymentProjectWriteApi {
/**
- * Timestamp when the Cloudflare project was fully provisioned and ready to receive deploys.
+ * Human-readable project name shown in the UI.
+ * @maxLength 200
+ */
+ name?: string
+ /**
+ * URL-safe handle. Combined with the team id to form the Cloudflare project name; the actual subdomain comes from Cloudflare and is returned in the read-only `subdomain` field. Must be unique per team.
+ * @maxLength 80
+ * @pattern ^[-a-zA-Z0-9_]+$
+ */
+ slug?: string
+ /**
+ * Branch PostHog tracks for deployment updates. Defaults to the repository default branch.
+ * @maxLength 255
+ */
+ default_branch?: string
+ /**
+ * Existing PostHog GitHub integration id used for repository access.
* @nullable
*/
- readonly cloudflare_ready_at?: string | null
+ github_integration_id?: number | null
/**
- * The deployment currently serving traffic for this project. Null if no deployment has ever succeeded.
+ * Stable GitHub repository identifier selected from the existing integration's repository list.
* @nullable
*/
- readonly current_deployment?: string | null
- /** True when the project has both a provisioned Cloudflare backend and a configured GitHub credential — meaning a deploy can be triggered right now. */
- readonly is_ready_to_deploy?: boolean
- /** Timestamp when the project was created. */
- readonly created_at?: string
- /** Timestamp when the project was last modified. */
- readonly updated_at?: string
+ github_repo_id?: number | null
+ /**
+ * Optional shell command run inside the build container. Null = the build worker infers it from `framework` (or auto-detection if framework is also null).
+ * @nullable
+ */
+ build_command?: string | null
+ /**
+ * Directory containing the built static site, relative to the repository root.
+ * @maxLength 255
+ */
+ output_dir?: string
+ /**
+ * Optional framework hint (e.g. `nextjs`, `vite`, `astro`). Null = auto-detect.
+ * @maxLength 50
+ * @nullable
+ */
+ framework?: string | null
+ /** If true, the build injects a PostHog snippet into every HTML file that registers `release = deployment_id` as a super-property — runtime exceptions are then linked back to the deployment that introduced them. */
+ inject_posthog_snippet?: boolean
+}
+
+/**
+ * Response shape for refreshing a deployment project's GitHub branch.
+ */
+export interface DeploymentProjectRefreshResponseApi {
+ /** Human-readable explanation of the refresh result. */
+ detail: string
+ /** HTTPS URL of the connected GitHub repository. */
+ repo_url: string
+ /** Branch checked by the refresh action. */
+ default_branch: string
+ /** Current GitHub HEAD SHA for default_branch. */
+ commit_sha: string
}
export type DeploymentProjectsListParams = {
diff --git a/products/deployments/frontend/generated/api.ts b/products/deployments/frontend/generated/api.ts
index 4dec60097e19..a8e260a48d76 100644
--- a/products/deployments/frontend/generated/api.ts
+++ b/products/deployments/frontend/generated/api.ts
@@ -13,32 +13,18 @@ import type {
DeploymentApi,
DeploymentCreateInputApi,
DeploymentProjectApi,
+ DeploymentProjectCreateApi,
+ DeploymentProjectRefreshResponseApi,
+ DeploymentProjectWriteApi,
DeploymentProjectsDeploymentsEventsListParams,
DeploymentProjectsDeploymentsListParams,
DeploymentProjectsListParams,
PaginatedDeploymentEventListApi,
PaginatedDeploymentListApi,
PaginatedDeploymentProjectListApi,
- PatchedDeploymentProjectApi,
+ PatchedDeploymentProjectWriteApi,
} from './api.schemas'
-// https://stackoverflow.com/questions/49579094/typescript-conditional-types-filter-out-readonly-properties-pick-only-requir/49579497#49579497
-type IfEquals<X, Y, A = X, B = never> = (<T>() => T extends X ? 1 : 2) extends <T>() => T extends Y ? 1 : 2 ? A : B
-
-type WritableKeys<T> = {
- [P in keyof T]-?: IfEquals<{ [Q in P]: T[P] }, { -readonly [Q in P]: T[P] }, P>
-}[keyof T]
-
-type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends (k: infer I) => void ? I : never
-type DistributeReadOnlyOverUnions<T> = T extends any ? NonReadonly<T> : never
-
-type Writable<T> = Pick<T, WritableKeys<T>>
-type NonReadonly<T> = [T] extends [UnionToIntersection<T>]
- ? {
- [P in keyof Writable<T>]: T[P] extends object ? NonReadonly<NonNullable<T[P]>> : T[P]
- }
- : DistributeReadOnlyOverUnions<T>
-
export const getDeploymentProjectsListUrl = (projectId: string, params?: DeploymentProjectsListParams) => {
const normalizedParams = new URLSearchParams()
@@ -88,14 +74,14 @@ task.
*/
export const deploymentProjectsCreate = async (
projectId: string,
- deploymentProjectApi: NonReadonly<DeploymentProjectApi>,
+ deploymentProjectCreateApi: DeploymentProjectCreateApi,
options?: RequestInit
): Promise<DeploymentProjectApi> => {
return apiMutator<DeploymentProjectApi>(getDeploymentProjectsCreateUrl(projectId), {
...options,
method: 'POST',
headers: { 'Content-Type': 'application/json', ...options?.headers },
- body: JSON.stringify(deploymentProjectApi),
+ body: JSON.stringify(deploymentProjectCreateApi),
})
}
@@ -434,14 +420,14 @@ task.
export const deploymentProjectsUpdate = async (
projectId: string,
id: string,
- deploymentProjectApi: NonReadonly<DeploymentProjectApi>,
+ deploymentProjectWriteApi: DeploymentProjectWriteApi,
options?: RequestInit
): Promise<DeploymentProjectApi> => {
return apiMutator<DeploymentProjectApi>(getDeploymentProjectsUpdateUrl(projectId, id), {
...options,
method: 'PUT',
headers: { 'Content-Type': 'application/json', ...options?.headers },
- body: JSON.stringify(deploymentProjectApi),
+ body: JSON.stringify(deploymentProjectWriteApi),
})
}
@@ -460,14 +446,14 @@ task.
export const deploymentProjectsPartialUpdate = async (
projectId: string,
id: string,
- patchedDeploymentProjectApi?: NonReadonly<PatchedDeploymentProjectApi>,
+ patchedDeploymentProjectWriteApi?: PatchedDeploymentProjectWriteApi,
options?: RequestInit
): Promise<DeploymentProjectApi> => {
return apiMutator<DeploymentProjectApi>(getDeploymentProjectsPartialUpdateUrl(projectId, id), {
...options,
method: 'PATCH',
headers: { 'Content-Type': 'application/json', ...options?.headers },
- body: JSON.stringify(patchedDeploymentProjectApi),
+ body: JSON.stringify(patchedDeploymentProjectWriteApi),
})
}
@@ -493,3 +479,27 @@ export const deploymentProjectsDestroy = async (
method: 'DELETE',
})
}
+
+export const getDeploymentProjectsRefreshCreateUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/deployment_projects/${id}/refresh/`
+}
+
+/**
+ * CRUD for DeploymentProject (the connected-repo + hosting-target entity).
+
+Create-time provisioning calls Cloudflare BEFORE writing the DB row
+(see services/provision_project.py for the rationale). Delete is a
+soft-delete; Cloudflare-side cleanup is deferred to a periodic Celery
+task.
+ * @summary Refresh a deployment project's GitHub branch
+ */
+export const deploymentProjectsRefreshCreate = async (
+ projectId: string,
+ id: string,
+ options?: RequestInit
+): Promise<DeploymentProjectRefreshResponseApi> => {
+ return apiMutator<DeploymentProjectRefreshResponseApi>(getDeploymentProjectsRefreshCreateUrl(projectId, id), {
+ ...options,
+ method: 'POST',
+ })
+}
diff --git a/products/deployments/frontend/generated/api.zod.ts b/products/deployments/frontend/generated/api.zod.ts
index a6b0c5aee6f5..b6bee138ef63 100644
--- a/products/deployments/frontend/generated/api.zod.ts
+++ b/products/deployments/frontend/generated/api.zod.ts
@@ -22,9 +22,6 @@ export const deploymentProjectsCreateBodyNameMax = 200
export const deploymentProjectsCreateBodySlugMax = 80
export const deploymentProjectsCreateBodySlugRegExp = new RegExp('^[-a-zA-Z0-9_]+$')
-export const deploymentProjectsCreateBodyRepoUrlMax = 1024
-
-export const deploymentProjectsCreateBodyDefaultBranchDefault = `main`
export const deploymentProjectsCreateBodyDefaultBranchMax = 255
export const deploymentProjectsCreateBodyOutputDirDefault = `dist`
@@ -43,24 +40,16 @@ export const DeploymentProjectsCreateBody = /* @__PURE__ */ zod.object({
.string()
.max(deploymentProjectsCreateBodySlugMax)
.regex(deploymentProjectsCreateBodySlugRegExp)
- .describe(
- 'URL-safe handle. Combined with the team id to form the Cloudflare project name; the actual subdomain comes from Cloudflare and is returned in the read-only `subdomain` field. Must be unique per team.'
- ),
- repo_url: zod
- .url()
- .max(deploymentProjectsCreateBodyRepoUrlMax)
- .describe('HTTPS URL of the source repository this project deploys from.'),
+ .describe('URL-safe handle. Becomes the subdomain `{slug}.posthog-app.com`. Must be unique per team.'),
default_branch: zod
.string()
.max(deploymentProjectsCreateBodyDefaultBranchMax)
- .default(deploymentProjectsCreateBodyDefaultBranchDefault)
- .describe('Branch the project deploys from when no commit SHA is pinned. Defaults to `main`.'),
- github_integration: zod
+ .optional()
+ .describe('Branch PostHog tracks for deployment updates. Defaults to the repository default branch.'),
+ github_integration_id: zod.number().describe('Existing PostHog GitHub integration id used for repository access.'),
+ github_repo_id: zod
.number()
- .nullish()
- .describe(
- 'ID of the `posthog.Integration` row (kind=github) the project uses to read this repository. Must belong to the same team. The actual access token lives on the Integration row and is never exposed through this serializer.'
- ),
+ .describe("Stable GitHub repository identifier selected from the existing integration's repository list."),
build_command: zod
.string()
.nullish()
@@ -127,9 +116,6 @@ export const deploymentProjectsUpdateBodyNameMax = 200
export const deploymentProjectsUpdateBodySlugMax = 80
export const deploymentProjectsUpdateBodySlugRegExp = new RegExp('^[-a-zA-Z0-9_]+$')
-export const deploymentProjectsUpdateBodyRepoUrlMax = 1024
-
-export const deploymentProjectsUpdateBodyDefaultBranchDefault = `main`
export const deploymentProjectsUpdateBodyDefaultBranchMax = 255
export const deploymentProjectsUpdateBodyOutputDirDefault = `dist`
@@ -151,21 +137,19 @@ export const DeploymentProjectsUpdateBody = /* @__PURE__ */ zod.object({
.describe(
'URL-safe handle. Combined with the team id to form the Cloudflare project name; the actual subdomain comes from Cloudflare and is returned in the read-only `subdomain` field. Must be unique per team.'
),
- repo_url: zod
- .url()
- .max(deploymentProjectsUpdateBodyRepoUrlMax)
- .describe('HTTPS URL of the source repository this project deploys from.'),
default_branch: zod
.string()
.max(deploymentProjectsUpdateBodyDefaultBranchMax)
- .default(deploymentProjectsUpdateBodyDefaultBranchDefault)
- .describe('Branch the project deploys from when no commit SHA is pinned. Defaults to `main`.'),
- github_integration: zod
+ .optional()
+ .describe('Branch PostHog tracks for deployment updates. Defaults to the repository default branch.'),
+ github_integration_id: zod
.number()
.nullish()
- .describe(
- 'ID of the `posthog.Integration` row (kind=github) the project uses to read this repository. Must belong to the same team. The actual access token lives on the Integration row and is never exposed through this serializer.'
- ),
+ .describe('Existing PostHog GitHub integration id used for repository access.'),
+ github_repo_id: zod
+ .number()
+ .nullish()
+ .describe("Stable GitHub repository identifier selected from the existing integration's repository list."),
build_command: zod
.string()
.nullish()
@@ -203,9 +187,6 @@ export const deploymentProjectsPartialUpdateBodyNameMax = 200
export const deploymentProjectsPartialUpdateBodySlugMax = 80
export const deploymentProjectsPartialUpdateBodySlugRegExp = new RegExp('^[-a-zA-Z0-9_]+$')
-export const deploymentProjectsPartialUpdateBodyRepoUrlMax = 1024
-
-export const deploymentProjectsPartialUpdateBodyDefaultBranchDefault = `main`
export const deploymentProjectsPartialUpdateBodyDefaultBranchMax = 255
export const deploymentProjectsPartialUpdateBodyOutputDirDefault = `dist`
@@ -229,22 +210,19 @@ export const DeploymentProjectsPartialUpdateBody = /* @__PURE__ */ zod.object({
.describe(
'URL-safe handle. Combined with the team id to form the Cloudflare project name; the actual subdomain comes from Cloudflare and is returned in the read-only `subdomain` field. Must be unique per team.'
),
- repo_url: zod
- .url()
- .max(deploymentProjectsPartialUpdateBodyRepoUrlMax)
- .optional()
- .describe('HTTPS URL of the source repository this project deploys from.'),
default_branch: zod
.string()
.max(deploymentProjectsPartialUpdateBodyDefaultBranchMax)
- .default(deploymentProjectsPartialUpdateBodyDefaultBranchDefault)
- .describe('Branch the project deploys from when no commit SHA is pinned. Defaults to `main`.'),
- github_integration: zod
+ .optional()
+ .describe('Branch PostHog tracks for deployment updates. Defaults to the repository default branch.'),
+ github_integration_id: zod
.number()
.nullish()
- .describe(
- 'ID of the `posthog.Integration` row (kind=github) the project uses to read this repository. Must belong to the same team. The actual access token lives on the Integration row and is never exposed through this serializer.'
- ),
+ .describe('Existing PostHog GitHub integration id used for repository access.'),
+ github_repo_id: zod
+ .number()
+ .nullish()
+ .describe("Stable GitHub repository identifier selected from the existing integration's repository list."),
build_command: zod
.string()
.nullish()
diff --git a/products/deployments/product.yaml b/products/deployments/product.yaml
index 1870b57f5137..e919222d1535 100644
--- a/products/deployments/product.yaml
+++ b/products/deployments/product.yaml
@@ -1,3 +1,6 @@
name: Deployments
owners:
- '@richardsolomou'
+ - '@matheus-vb'
+ - '@rubychilds'
+ - '@dustinbyrne'
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 883ca0237b5e..15152ec9d873 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -12068,20 +12068,25 @@ export namespace Schemas {
*/
slug: string;
/**
- * HTTPS URL of the source repository this project deploys from.
+ * HTTPS URL of the connected GitHub repository, resolved from the selected repository id.
* @maxLength 1024
*/
- repo_url: string;
+ readonly repo_url: string;
/**
- * Branch the project deploys from when no commit SHA is pinned. Defaults to `main`.
+ * Branch PostHog tracks for deployment updates. Defaults to the repository default branch.
* @maxLength 255
*/
default_branch?: string;
/**
- * ID of the `posthog.Integration` row (kind=github) the project uses to read this repository. Must belong to the same team. The actual access token lives on the Integration row and is never exposed through this serializer.
+ * Existing PostHog GitHub integration id used for repository access.
* @nullable
*/
- github_integration?: number | null;
+ github_integration_id?: number | null;
+ /**
+ * Stable GitHub repository identifier selected from the existing integration's repository list.
+ * @nullable
+ */
+ github_repo_id?: number | null;
/**
* Optional shell command run inside the build container. Null = the build worker infers it from `framework` (or auto-detection if framework is also null).
* @nullable
@@ -12122,6 +12127,108 @@ export namespace Schemas {
readonly updated_at: string;
}
+ export interface DeploymentProjectCreate {
+ /**
+ * Human-readable project name shown in the UI.
+ * @maxLength 200
+ */
+ name: string;
+ /**
+ * URL-safe handle. Becomes the subdomain `{slug}.posthog-app.com`. Must be unique per team.
+ * @maxLength 80
+ * @pattern ^[-a-zA-Z0-9_]+$
+ */
+ slug: string;
+ /**
+ * Branch PostHog tracks for deployment updates. Defaults to the repository default branch.
+ * @maxLength 255
+ */
+ default_branch?: string;
+ /** Existing PostHog GitHub integration id used for repository access. */
+ github_integration_id: number;
+ /** Stable GitHub repository identifier selected from the existing integration's repository list. */
+ github_repo_id: number;
+ /**
+ * Optional shell command run inside the build container. Null = the build worker infers it from `framework` (or auto-detection if framework is also null).
+ * @nullable
+ */
+ build_command?: string | null;
+ /**
+ * Directory containing the built static site, relative to the repository root.
+ * @maxLength 255
+ */
+ output_dir?: string;
+ /**
+ * Optional framework hint (e.g. `nextjs`, `vite`, `astro`). Null = auto-detect.
+ * @maxLength 50
+ * @nullable
+ */
+ framework?: string | null;
+ /** If true, the build injects a PostHog snippet into every HTML file that registers `release = deployment_id` as a super-property — runtime exceptions are then linked back to the deployment that introduced them. */
+ inject_posthog_snippet?: boolean;
+ }
+
+ /**
+ * Response shape for refreshing a deployment project's GitHub branch.
+ */
+ export interface DeploymentProjectRefreshResponse {
+ /** Human-readable explanation of the refresh result. */
+ detail: string;
+ /** HTTPS URL of the connected GitHub repository. */
+ repo_url: string;
+ /** Branch checked by the refresh action. */
+ default_branch: string;
+ /** Current GitHub HEAD SHA for default_branch. */
+ commit_sha: string;
+ }
+
+ export interface DeploymentProjectWrite {
+ /**
+ * Human-readable project name shown in the UI.
+ * @maxLength 200
+ */
+ name: string;
+ /**
+ * URL-safe handle. Combined with the team id to form the Cloudflare project name; the actual subdomain comes from Cloudflare and is returned in the read-only `subdomain` field. Must be unique per team.
+ * @maxLength 80
+ * @pattern ^[-a-zA-Z0-9_]+$
+ */
+ slug: string;
+ /**
+ * Branch PostHog tracks for deployment updates. Defaults to the repository default branch.
+ * @maxLength 255
+ */
+ default_branch?: string;
+ /**
+ * Existing PostHog GitHub integration id used for repository access.
+ * @nullable
+ */
+ github_integration_id?: number | null;
+ /**
+ * Stable GitHub repository identifier selected from the existing integration's repository list.
+ * @nullable
+ */
+ github_repo_id?: number | null;
+ /**
+ * Optional shell command run inside the build container. Null = the build worker infers it from `framework` (or auto-detection if framework is also null).
+ * @nullable
+ */
+ build_command?: string | null;
+ /**
+ * Directory containing the built static site, relative to the repository root.
+ * @maxLength 255
+ */
+ output_dir?: string;
+ /**
+ * Optional framework hint (e.g. `nextjs`, `vite`, `astro`). Null = auto-detect.
+ * @maxLength 50
+ * @nullable
+ */
+ framework?: string | null;
+ /** If true, the build injects a PostHog snippet into every HTML file that registers `release = deployment_id` as a super-property — runtime exceptions are then linked back to the deployment that introduced them. */
+ inject_posthog_snippet?: boolean;
+ }
+
export interface DeprovisionWarehouseResponse {
status: string;
team: string;
@@ -25543,9 +25650,7 @@ export namespace Schemas {
readonly team?: number;
}
- export interface PatchedDeploymentProject {
- /** Unique identifier for the deployment project. */
- readonly id?: string;
+ export interface PatchedDeploymentProjectWrite {
/**
* Human-readable project name shown in the UI.
* @maxLength 200
@@ -25558,20 +25663,20 @@ export namespace Schemas {
*/
slug?: string;
/**
- * HTTPS URL of the source repository this project deploys from.
- * @maxLength 1024
- */
- repo_url?: string;
- /**
- * Branch the project deploys from when no commit SHA is pinned. Defaults to `main`.
+ * Branch PostHog tracks for deployment updates. Defaults to the repository default branch.
* @maxLength 255
*/
default_branch?: string;
/**
- * ID of the `posthog.Integration` row (kind=github) the project uses to read this repository. Must belong to the same team. The actual access token lives on the Integration row and is never exposed through this serializer.
+ * Existing PostHog GitHub integration id used for repository access.
* @nullable
*/
- github_integration?: number | null;
+ github_integration_id?: number | null;
+ /**
+ * Stable GitHub repository identifier selected from the existing integration's repository list.
+ * @nullable
+ */
+ github_repo_id?: number | null;
/**
* Optional shell command run inside the build container. Null = the build worker infers it from `framework` (or auto-detection if framework is also null).
* @nullable
@@ -25590,26 +25695,6 @@ export namespace Schemas {
framework?: string | null;
/** If true, the build injects a PostHog snippet into every HTML file that registers `release = deployment_id` as a super-property — runtime exceptions are then linked back to the deployment that introduced them. */
inject_posthog_snippet?: boolean;
- /** Cloudflare Pages project name, assigned during provisioning. */
- readonly cloudflare_project_name?: string;
- /** Public subdomain at which deployments of this project serve. */
- readonly subdomain?: string;
- /**
- * Timestamp when the Cloudflare project was fully provisioned and ready to receive deploys.
- * @nullable
- */
- readonly cloudflare_ready_at?: string | null;
- /**
- * The deployment currently serving traffic for this project. Null if no deployment has ever succeeded.
- * @nullable
- */
- readonly current_deployment?: string | null;
- /** True when the project has both a provisioned Cloudflare backend and a configured GitHub credential — meaning a deploy can be triggered right now. */
- readonly is_ready_to_deploy?: boolean;
- /** Timestamp when the project was created. */
- readonly created_at?: string;
- /** Timestamp when the project was last modified. */
- readonly updated_at?: string;
}
export interface PatchedDesktopRecording {
diff --git a/tach.toml b/tach.toml
index 34964b385ce8..0fc6454d6fde 100644
--- a/tach.toml
+++ b/tach.toml
@@ -181,6 +181,7 @@ layer = "modules"
[[modules]]
path = "products.deployments"
depends_on = [
+ "ee",
"posthog",
# `error_tracking` is not isolated (no contract-check script), so we
# import its model directly to upsert an ErrorTrackingRelease row on