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(skills): publish community skills as a dedicated github app (#88352)

Andrew Maguire07d12e7b82cb
diff --git a/docs/internal/skills/community-skills-api.md b/docs/internal/skills/community-skills-api.md
index cdfc1c02ef04..5c0af545695b 100644
--- a/docs/internal/skills/community-skills-api.md
+++ b/docs/internal/skills/community-skills-api.md
@@ -106,13 +106,43 @@ Rendering and the GitHub calls are in `community_publish_services.py`.
| Setting | Effect |
| ----------------------------------------- | ----------------------------------------------------------------------------------- |
-| `COMMUNITY_SKILLS_GITHUB_INSTALLATION_ID` | Installation of the GitHub App that opens the PRs. Empty (the default) returns 503. |
+| `COMMUNITY_SKILLS_GITHUB_APP_CLIENT_ID` | Client id of the publisher App, and the issuer of the App JWT that mints the token. |
+| `COMMUNITY_SKILLS_GITHUB_APP_PRIVATE_KEY` | PEM the App JWT is signed with. Escaped newlines are restored before signing. |
+| `COMMUNITY_SKILLS_GITHUB_INSTALLATION_ID` | Installation of that App on the publish repo. Empty (the default) returns 503. |
| `COMMUNITY_SKILLS_GITHUB_REPO` | Bare repo name to publish into. The owner comes from the installation's account. |
+Publishing runs as its own dedicated GitHub App, installed on the publish repo alone. It does not
+fall back to the core `GITHUB_APP_*` App, which is installed across the whole PostHog org: a
+dedicated App cannot reach another repository whatever the publish path asks it for. One App serves
+every region, so the client id and the installation id hold the same value everywhere and only the
+private key is per-region. Any of the three being empty keeps publishing off.
+
`COMMUNITY_SKILLS_GITHUB_REPO` is publish-only. The hourly catalog sync reads `registry.json` from the
repo pinned in `community_skill_sync.py`, so pointing this setting elsewhere sends pull requests to a
repo the sync never reads back.
+### The App and its privileges
+
+Registering and installing the App is manual org-admin work in the GitHub UI. Nothing in
+`posthog-cloud-infra` manages App installations, and the env values land through `PostHog/charts`
+(`shared/posthog-django/common.prod-us.yaml` and `common.prod-eu.yaml`, next to the
+`STAMPHOG_GITHUB_APP_*` block, with the private key in `secret_env`). Least privilege is held at
+three layers, and only the last one is code:
+
+1. **App registration.** The App declares `Contents: write`, `Pull requests: write`, and
+ `Metadata: read`, and nothing else. No webhook, no user-authorization flow, so it has no client
+ secret and no webhook secret. Private, owned by the PostHog org. This is the ceiling on anything
+ the App can ever do.
+2. **Installation.** Installed with "Only select repositories" and the publish repo as the one
+ selection. This caps the repo scope, and is why the core `GITHUB_APP_*` App cannot serve here.
+3. **Token mint.** `PUBLISHER_TOKEN_PERMISSIONS` in `community_publish_services.py` requests an
+ installation token holding exactly those three permissions on `COMMUNITY_SKILLS_GITHUB_REPO`
+ alone. GitHub only lets a token request narrow what the two layers above granted, so a later
+ over-grant in the UI still cannot reach a publish.
+
+Keep the three in step: a permission the App does not declare makes the token mint fail with a 422
+rather than a scoped token, which the publish path reports as a gateway error.
+
### Repo writes
The target repo is public, so a failed publish must not leave anything behind:
@@ -128,8 +158,9 @@ The target repo is public, so a failed publish must not leave anything behind:
that with the user is a UI concern, and it gates enabling the flag rather than shipping this code.
Errors surface as `400` (invalid payload), `404` (unknown skill), `502` (GitHub refused a step), or
-`503` when the instance has no `COMMUNITY_SKILLS_GITHUB_INSTALLATION_ID` configured. The 503 is the
-fail-safe that keeps publishing off until the GitHub App is installed.
+`503` when the instance has no publisher App configured. The 503 is the fail-safe that keeps
+publishing off until the GitHub App is installed. A private key that cannot sign is a 503 too: it is
+a deployment nobody can retry their way out of, so it must not read as GitHub being down.
The three are kept apart on purpose, because each sends the publisher somewhere different. The skill
is rendered before GitHub is touched, so a skill that has to be edited answers `400` even while the
diff --git a/posthog/settings/integrations.py b/posthog/settings/integrations.py
index b9dbe9aafdbc..5b2d60140a36 100644
--- a/posthog/settings/integrations.py
+++ b/posthog/settings/integrations.py
@@ -79,9 +79,15 @@ STAMPHOG_GITHUB_APP_SLUG = get_from_env("STAMPHOG_GITHUB_APP_SLUG", "")
# PyPI, the LLM gateway host, the PostHog capture host). Comma-separated; an ops escape hatch for
# when a legitimate dependency host is missing — never a way to open the sandbox wide.
STAMPHOG_SANDBOX_EXTRA_EGRESS_DOMAINS = get_list(get_from_env("STAMPHOG_SANDBOX_EXTRA_EGRESS_DOMAINS", ""))
-# Installation id of the GitHub App on the PostHog/community-skills repo, used by the in-product
-# "Publish to community" flow to open skill PRs. Empty (the default) disables publishing → the
-# endpoint returns 503 and the UI falls back to the manual-PR path.
+# The in-product "Publish to community" flow runs as its own dedicated GitHub App, installed on the
+# PostHog/community-skills repo alone. It does not fall back to the core GITHUB_APP_* App above,
+# which is installed across the whole PostHog org: a dedicated App cannot reach another repository
+# whatever the publish path asks it for. One App serves every region, so the client id and the
+# installation id below hold the same value everywhere, and only the private key is per-region.
+COMMUNITY_SKILLS_GITHUB_APP_CLIENT_ID = get_from_env("COMMUNITY_SKILLS_GITHUB_APP_CLIENT_ID", "")
+COMMUNITY_SKILLS_GITHUB_APP_PRIVATE_KEY = get_from_env("COMMUNITY_SKILLS_GITHUB_APP_PRIVATE_KEY", "")
+# Installation id of that App on the PostHog/community-skills repo. Empty (the default) disables
+# publishing → the endpoint returns 503 and the UI falls back to the manual-PR path.
COMMUNITY_SKILLS_GITHUB_INSTALLATION_ID = get_from_env("COMMUNITY_SKILLS_GITHUB_INSTALLATION_ID", "")
# Bare repo name (no owner prefix) — the owner is the App installation's account. Defaults to the
# PostHog/community-skills repo. Publish-only: the hourly catalog sync reads its registry from the
diff --git a/products/skills/backend/api/community_publish_services.py b/products/skills/backend/api/community_publish_services.py
index a93b9bfcb125..d2c19b2ffddf 100644
--- a/products/skills/backend/api/community_publish_services.py
+++ b/products/skills/backend/api/community_publish_services.py
@@ -9,17 +9,19 @@ from __future__ import annotations
import re
import json
+import time
import hashlib
from typing import Any
from django.conf import settings
+import jwt
import yaml
import requests
import structlog
from posthog.dataclasses import frozen
-from posthog.egress.github.transport import GitHubRateLimitError
+from posthog.egress.github.transport import GitHubRateLimitError, github_request
from posthog.models.github_integration_base import GitHubIntegrationError
from posthog.models.integration import GitHubIntegration, Integration
@@ -36,6 +38,9 @@ from .skill_services import (
logger = structlog.get_logger(__name__)
+# Per-subsystem attribution on the shared GitHub egress metrics.
+_EGRESS_SOURCE = "community_skills"
+
MAX_SLUG_LENGTH = 64
# GitHub caps one create-tree request at 7 MB, and commit_files_to_branch inlines every file's
# content in that single request, so a skill above the cap can only ever fail with a 502. Measured
@@ -387,32 +392,90 @@ def _publisher_token_request_body() -> dict[str, Any]:
return body
+def _publisher_app_jwt() -> str | None:
+ """Sign a short-lived App JWT for the dedicated community-skills publisher App, or None.
+
+ ``iat`` is backdated to tolerate clock skew against GitHub, and ``exp`` stays inside GitHub's
+ 10-minute maximum. Returns None when the App is unconfigured, and also when its private key
+ cannot sign: a key GitHub would reject is a deployment nobody can retry their way out of, so it
+ has to read as "this instance cannot publish" rather than as a GitHub outage.
+ """
+ client_id = settings.COMMUNITY_SKILLS_GITHUB_APP_CLIENT_ID
+ private_key = settings.COMMUNITY_SKILLS_GITHUB_APP_PRIVATE_KEY
+ if not client_id or not private_key:
+ return None
+
+ now = int(time.time())
+ try:
+ return jwt.encode(
+ {"iat": now - 60, "exp": now + 540, "iss": str(client_id)},
+ # Environment variables commonly carry the PEM with its newlines escaped.
+ private_key.replace("\\n", "\n").strip(),
+ algorithm="RS256",
+ )
+ except Exception:
+ logger.error("community_skills_publisher_key_unusable", exc_info=True)
+ return None
+
+
+def _publisher_app_request(
+ path: str,
+ *,
+ app_jwt: str,
+ telemetry_endpoint: str,
+ method: str = "GET",
+ json_body: dict[str, Any] | None = None,
+) -> requests.Response:
+ """Call the GitHub App API as the publisher App, through the shared egress transport.
+
+ Identity-blind on purpose: App-JWT calls are metered per App rather than per installation, so
+ there is no installation budget to gate them under, but volume telemetry still counts.
+ """
+ return github_request(
+ method,
+ f"https://api.github.com/app/{path}",
+ source=_EGRESS_SOURCE,
+ headers={"Authorization": f"Bearer {app_jwt}"},
+ endpoint=telemetry_endpoint,
+ timeout=10,
+ # requests omits the body entirely when json is None
+ json=json_body,
+ )
+
+
def get_community_skills_publisher() -> GitHubIntegration | None:
"""Build a GitHubIntegration bound to the central community-skills installation, or None.
- Mints a fresh installation token via the GitHub App JWT (the same flow the per-team integration
- uses), downscoped to the publish repository and the permissions a publish needs, and wraps it in a
- transient, unsaved Integration — we never persist a teamless central row. Returns None when the
- App or the community-skills installation isn't configured, so callers can surface a clean "not
- configured" error instead of failing.
+ Mints a fresh installation token from the dedicated publisher App, downscoped to the publish
+ repository and the permissions a publish needs, and wraps it in a transient, unsaved Integration,
+ because we never persist a teamless central row. Returns None when that App or its
+ community-skills installation isn't configured, so callers can surface a clean "not configured"
+ error instead of failing.
Raises CommunitySkillPublishError when GitHub can't be reached to mint the token: an outage here
is the same failure as an outage on the write that follows, and must not read as "not configured".
"""
installation_id = settings.COMMUNITY_SKILLS_GITHUB_INSTALLATION_ID
- if not installation_id or not settings.GITHUB_APP_CLIENT_ID or not settings.GITHUB_APP_PRIVATE_KEY:
+ app_jwt = _publisher_app_jwt()
+ if not installation_id or app_jwt is None:
return None
try:
- info_response = GitHubIntegration.client_request(f"installations/{installation_id}")
- token_response = GitHubIntegration.client_request(
+ info_response = _publisher_app_request(
+ f"installations/{installation_id}",
+ app_jwt=app_jwt,
+ telemetry_endpoint="/app/installations/{installation_id}",
+ )
+ token_response = _publisher_app_request(
f"installations/{installation_id}/access_tokens",
+ app_jwt=app_jwt,
+ telemetry_endpoint="/app/installations/{installation_id}/access_tokens",
method="POST",
json_body=_publisher_token_request_body(),
)
except (requests.RequestException, GitHubIntegrationError, GitHubRateLimitError) as err:
- # client_request talks to the transport directly, so unlike api_request it hands a timeout
- # back raw. Without this the publish path answers a GitHub outage with an unhandled 500.
+ # The transport hands a timeout back raw. Without this the publish path answers a GitHub
+ # outage with an unhandled 500.
logger.warning("community_skills_publisher_unreachable", exc_info=True)
raise CommunitySkillPublishError(
"Could not reach GitHub to publish this skill. Try again in a few minutes."
@@ -452,7 +515,8 @@ def get_community_skills_publisher() -> GitHubIntegration | None:
config={"account": {"name": account["login"], "type": account.get("type")}},
sensitive_config={"access_token": token},
)
- return _CommunitySkillsPublisher(integration)
+ # The same source as the App-JWT calls above, so every publish request lands under one label.
+ return _CommunitySkillsPublisher(integration, source=_EGRESS_SOURCE)
def _community_pr_body(*, name: str, slug: str, author_handle: str) -> str:
diff --git a/products/skills/backend/api/test/test_community_publish_services.py b/products/skills/backend/api/test/test_community_publish_services.py
index 1dc66cc1c9e3..29b6514ddebd 100644
--- a/products/skills/backend/api/test/test_community_publish_services.py
+++ b/products/skills/backend/api/test/test_community_publish_services.py
@@ -8,6 +8,8 @@ from django.test import override_settings
import yaml
import requests
+from cryptography.hazmat.primitives import serialization
+from cryptography.hazmat.primitives.asymmetric import rsa
from parameterized import parameterized
from posthog.models.github_integration_base import GitHubIntegrationError
@@ -250,6 +252,30 @@ class TestPublishableSize:
)
+# Generated per run rather than checked in: a PEM in a public repo trips secret scanners, and the
+# publisher settings take a real key because the App JWT is signed for real in these tests.
+PUBLISHER_PRIVATE_KEY = (
+ rsa.generate_private_key(public_exponent=65537, key_size=2048)
+ .private_bytes(
+ encoding=serialization.Encoding.PEM,
+ format=serialization.PrivateFormat.PKCS8,
+ encryption_algorithm=serialization.NoEncryption(),
+ )
+ .decode()
+)
+PUBLISHER_SETTINGS = {
+ "COMMUNITY_SKILLS_GITHUB_INSTALLATION_ID": "4242",
+ "COMMUNITY_SKILLS_GITHUB_REPO": "community-skills",
+ "COMMUNITY_SKILLS_GITHUB_APP_CLIENT_ID": "Iv23licommunity",
+ "COMMUNITY_SKILLS_GITHUB_APP_PRIVATE_KEY": PUBLISHER_PRIVATE_KEY,
+ # A usable core App, which the publish path must never fall back to: that App is installed
+ # across the whole PostHog org, so a fallback hands publishing a credential for every
+ # repository in it. Configured here so every case below holds publishing to its own App.
+ "GITHUB_APP_CLIENT_ID": "core",
+ "GITHUB_APP_PRIVATE_KEY": PUBLISHER_PRIVATE_KEY,
+}
+
+
class TestCommunitySkillsPublisher:
def _response(self, status_code: int, payload: dict) -> MagicMock:
response = MagicMock()
@@ -257,20 +283,18 @@ class TestCommunitySkillsPublisher:
response.json.return_value = payload
return response
- @override_settings(
- COMMUNITY_SKILLS_GITHUB_INSTALLATION_ID="4242",
- COMMUNITY_SKILLS_GITHUB_REPO="community-skills",
- GITHUB_APP_CLIENT_ID="client",
- GITHUB_APP_PRIVATE_KEY="key",
- )
- @patch("products.skills.backend.api.community_publish_services.GitHubIntegration.client_request")
+ @override_settings(**PUBLISHER_SETTINGS)
+ @patch("products.skills.backend.api.community_publish_services._publisher_app_request")
def test_mints_a_token_scoped_to_the_publish_repository(self, mock_request: MagicMock) -> None:
mock_request.side_effect = [
self._response(200, {"account": {"login": "PostHog", "type": "Organization"}}),
self._response(201, {"token": "ghs_x"}),
]
- assert get_community_skills_publisher() is not None
+ publisher = get_community_skills_publisher()
+ assert publisher is not None
+ # Every write the publisher makes must share the App-JWT calls' egress label.
+ assert publisher.source == "community_skills"
mint_body = mock_request.call_args.kwargs["json_body"]
assert mint_body["repositories"] == ["community-skills"]
@@ -291,17 +315,9 @@ class TestCommunitySkillsPublisher:
# None here becomes the endpoint's 503, which tells the publisher this instance can't publish
# at all. A transient failure must not say that: it sends them to the manual path over an
# outage that clears by itself.
- settings_override = override_settings(
- COMMUNITY_SKILLS_GITHUB_INSTALLATION_ID="4242",
- COMMUNITY_SKILLS_GITHUB_REPO="community-skills",
- GITHUB_APP_CLIENT_ID="client",
- GITHUB_APP_PRIVATE_KEY="key",
- )
with (
- settings_override,
- patch(
- "products.skills.backend.api.community_publish_services.GitHubIntegration.client_request"
- ) as mock_request,
+ override_settings(**PUBLISHER_SETTINGS),
+ patch("products.skills.backend.api.community_publish_services._publisher_app_request") as mock_request,
):
mock_request.side_effect = [
self._response(200, {"account": {"login": "PostHog", "type": "Organization"}}),
@@ -314,21 +330,37 @@ class TestCommunitySkillsPublisher:
else:
assert get_community_skills_publisher() is None
- @override_settings(
- COMMUNITY_SKILLS_GITHUB_INSTALLATION_ID="4242",
- COMMUNITY_SKILLS_GITHUB_REPO="community-skills",
- GITHUB_APP_CLIENT_ID="client",
- GITHUB_APP_PRIVATE_KEY="key",
- )
- @patch("products.skills.backend.api.community_publish_services.GitHubIntegration.client_request")
+ @override_settings(**PUBLISHER_SETTINGS)
+ @patch("products.skills.backend.api.community_publish_services._publisher_app_request")
def test_github_being_unreachable_while_minting_raises_a_publish_error(self, mock_request: MagicMock) -> None:
- # client_request goes to the transport directly, so a timeout arrives raw rather than as the
+ # The App-JWT calls go to the transport directly, so a timeout arrives raw rather than as the
# GitHubIntegrationError api_request would wrap it in. Unhandled, the endpoint answers 500.
mock_request.side_effect = requests.ConnectTimeout("boom")
with pytest.raises(CommunitySkillPublishError):
get_community_skills_publisher()
+ @parameterized.expand(
+ [
+ ("no client id", {"COMMUNITY_SKILLS_GITHUB_APP_CLIENT_ID": ""}),
+ ("no private key", {"COMMUNITY_SKILLS_GITHUB_APP_PRIVATE_KEY": ""}),
+ ("a private key that cannot sign", {"COMMUNITY_SKILLS_GITHUB_APP_PRIVATE_KEY": "not-a-pem"}),
+ ("no installation", {"COMMUNITY_SKILLS_GITHUB_INSTALLATION_ID": ""}),
+ ]
+ )
+ def test_an_unusable_publisher_app_never_reaches_github(self, _label: str, overrides: dict[str, str]) -> None:
+ # Publishing is off on this instance, which is the endpoint's 503. Reaching GitHub anyway
+ # would answer a deployment nobody can retry their way out of as though it were an outage,
+ # and reaching it under the core App would publish with an org-wide credential.
+ with (
+ override_settings(**{**PUBLISHER_SETTINGS, **overrides}),
+ patch(
+ "products.skills.backend.api.community_publish_services._publisher_app_request",
+ side_effect=AssertionError("GitHub was called with an unusable publisher App"),
+ ),
+ ):
+ assert get_community_skills_publisher() is None
+
TEAM_A = "11111111-1111-1111-1111-111111111111"
TEAM_B = "22222222-2222-2222-2222-222222222222"