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(tasks): check run options and drive against the profile (#127855)

Charles Vienc2ac08f1574c
diff --git a/products/business_knowledge/backend/task_profiles.py b/products/business_knowledge/backend/task_profiles.py
index b91bfe25288c..a2413dd9ef06 100644
--- a/products/business_knowledge/backend/task_profiles.py
+++ b/products/business_knowledge/backend/task_profiles.py
@@ -1,6 +1,7 @@
from products.tasks.backend.facade.profiles import (
AccessGate,
DrivePolicy,
+ GithubAccess,
GithubResolution,
NetworkAccess,
NetworkPolicy,
@@ -37,6 +38,7 @@ BUSINESS_KNOWLEDGE = TaskProfile(
mcp_exclude_tools=BK_HIDDEN_TOOLS,
oauth_app=OAuthApp.ARRAY,
github_resolution=GithubResolution.WITH_REPOSITORY,
+ github_access=GithubAccess.WRITE,
user_authorable_prs=False,
default_pr_authorship=PrAuthorship.BOT,
create_pr=False,
diff --git a/products/tasks/backend/contract_checks.py b/products/tasks/backend/contract_checks.py
new file mode 100644
index 000000000000..09894cc2a1fd
--- /dev/null
+++ b/products/tasks/backend/contract_checks.py
@@ -0,0 +1,39 @@
+import structlog
+
+from products.tasks.backend.facade.profiles import ContractCheck, DrivePolicy, TaskProfile, find_task_profile
+from products.tasks.backend.metrics import observe_contract_violation
+
+logger = structlog.get_logger(__name__)
+
+
+def contract_violation_refused(profile: TaskProfile, check: ContractCheck, detail: str) -> bool:
+ refused = check in profile.enforced_checks
+ observe_contract_violation(check=check.value, profile=profile.key)
+ logger.warning(
+ "task_contract_violation_refused" if refused else "task_contract_violation_would_refuse",
+ check=check.value,
+ profile=profile.key,
+ detail=detail,
+ )
+ return refused
+
+
+def drive_allowed(profile_key: str | None, *, created_by_id: int | None, user_id: int | None) -> bool:
+ if not profile_key:
+ return True
+ profile = find_task_profile(profile_key)
+ if profile is None:
+ observe_contract_violation(check=ContractCheck.DRIVE.value, profile=profile_key)
+ logger.warning(
+ "task_contract_violation_unregistered_profile",
+ check=ContractCheck.DRIVE.value,
+ profile=profile_key,
+ detail=f"no registered profile can say whether user {user_id} may drive a task owned by {created_by_id}",
+ )
+ return True
+ if profile.drive == DrivePolicy.AUDIENCE:
+ return True
+ if profile.drive == DrivePolicy.OWNER and created_by_id is not None and created_by_id == user_id:
+ return True
+ detail = f"drive={profile.drive.value} does not let user {user_id} drive a task owned by {created_by_id}"
+ return not contract_violation_refused(profile, ContractCheck.DRIVE, detail)
diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.py
index c4c59fc9576c..c1af51c12904 100644
--- a/products/tasks/backend/facade/api.py
+++ b/products/tasks/backend/facade/api.py
@@ -103,9 +103,11 @@ from products.tasks.backend.constants import (
is_html_artifact as is_html_artifact,
is_same_run_resume_state,
)
+from products.tasks.backend.contract_checks import drive_allowed
from products.tasks.backend.error_telemetry import truncate_error_message
from products.tasks.backend.facade.gateway import mint_private_gateway_token, revoke_private_gateway_token
from products.tasks.backend.facade.profiles import (
+ GithubAccess,
NetworkAccess,
TaskProfile,
TaskRunOptions,
@@ -3390,12 +3392,17 @@ def task_accessible_for_run_view(
is_trial=Case(When(Task.scout_experiment_q(), then=Value(True)), default=Value(False)),
accessible=Exists(Task.objects.filter(id=OuterRef("pk"), team_id=team_id).filter(visibility)),
)
- .values("is_trial", "accessible")
+ .values("is_trial", "accessible", "profile", "created_by_id")
.first()
)
if task is not None and task["is_trial"]:
tag_queries(is_scout_experiment=True)
- return task is not None and bool(task["accessible"])
+ if task is None or not task["accessible"]:
+ return False
+ acts_on_its_own_task = sandbox_task_id is not None and str(sandbox_task_id) == str(task_id)
+ if for_control and not (bypass_visibility or acts_on_its_own_task):
+ return drive_allowed(task["profile"], created_by_id=task["created_by_id"], user_id=user_id)
+ return True
def list_task_run_ids(task_id: str | UUID, team_id: int) -> list[UUID]:
@@ -6488,6 +6495,9 @@ def _resolve_cloud_pr_authorship_mode(
)
return None, None
+ if task.github_access_limit == GithubAccess.NONE:
+ return PrAuthorshipMode.BOT, None
+
if pr_authorship_mode != PrAuthorshipMode.USER or github_user_token:
return pr_authorship_mode, None
@@ -7228,7 +7238,18 @@ def task_visible(task_id: str | UUID, team_id: int, user_id: int | None, *, for_
the original ordering; the ``run`` action passes ``for_control`` since starting a run drives
the task.
"""
- return _visible_task_qs(team_id, user_id, for_control=for_control).filter(id=task_id).exists()
+ visible = _visible_task_qs(team_id, user_id, for_control=for_control).filter(id=task_id)
+ if not for_control:
+ return visible.exists()
+ row = visible.values_list("profile", "created_by_id").first()
+ if row is None:
+ return False
+ profile_key, created_by_id = row
+ return drive_allowed(profile_key, created_by_id=created_by_id, user_id=user_id)
+
+
+def _task_drive_allowed(task: Task, user_id: int | None) -> bool:
+ return drive_allowed(task.profile, created_by_id=task.created_by_id, user_id=user_id)
def scout_trial_task_ids(team_id: int, *, visible_task_id: UUID | None = None) -> Iterable[UUID]:
@@ -8444,6 +8465,8 @@ def update_task(
task = Task.objects.select_for_update().filter(id=task_id, team_id=team_id, deleted=False).first()
if task is None or not Task.objects.filter(id=task.id).filter(task_control_q(user_id)).exists():
return None
+ if not _task_drive_allowed(task, user_id):
+ return None
previous_repositories = list(task.repositories or [])
previous_integration_id = task.github_integration_id
@@ -8471,11 +8494,15 @@ def update_task(
changes_github_access = not validated_data.keys().isdisjoint(
{"repository", "repositories", "github_integration", "github_user_integration"}
)
+ github_access = task.github_access_limit
if (
- profile is not None
+ (profile is not None or github_access == GithubAccess.NONE)
and changes_github_access
and not Task.attaches_github(
- task.origin_product, profile, has_repository=bool(validated_data.get("repository", task.repository))
+ task.origin_product,
+ profile,
+ has_repository=bool(validated_data.get("repository", task.repository)),
+ github_access=github_access,
)
):
validated_data.pop("github_integration", None)
@@ -8530,6 +8557,8 @@ def soft_delete_task(task_id: str | UUID, team_id: int, user_id: int | None) ->
task = Task.objects.select_for_update().filter(id=task_id, team_id=team_id, deleted=False).first()
if task is None or not Task.objects.filter(id=task.id).filter(task_control_q(user_id)).exists():
return False
+ if not _task_drive_allowed(task, user_id):
+ return False
logger.info("Soft deleting task %s", task.id)
task.soft_delete()
soft_delete_conversations_for_task(task.id)
@@ -8551,6 +8580,8 @@ def handoff_task(
return None
if user_id is None or task.created_by_id != user_id:
return None
+ if not _task_drive_allowed(task, user_id):
+ return None
if task.created_by_id == target_user_id:
raise TaskHandoffError("That person already owns this task.")
previous_owner_id = task.created_by_id
@@ -8686,7 +8717,7 @@ def prepare_task_staged_artifacts(
# Staged artifacts feed the task's next run, so this is control, not viewing.
task = _visible_task_qs(team_id, user_id, for_control=True).filter(id=task_id).first()
- if task is None:
+ if task is None or not _task_drive_allowed(task, user_id):
return None
prepared: list[contracts.StagedArtifactPreparedDTO] = []
@@ -8747,7 +8778,7 @@ def finalize_task_staged_artifacts(
)
task = _visible_task_qs(team_id, user_id, for_control=True).filter(id=task_id).first()
- if task is None:
+ if task is None or not _task_drive_allowed(task, user_id):
return None
artifact_prefix = f"{settings.OBJECT_STORAGE_TASKS_FOLDER}/artifacts/team_{task.team_id}/task_{task.id}/staged/"
@@ -9493,7 +9524,7 @@ def warm_task_resume_sandbox(
)
task = _visible_task_qs(team_id, user_id, for_control=True).select_related("team").filter(id=task_id).first()
- if task is None:
+ if task is None or not _task_drive_allowed(task, user_id):
return None
previous_run = task.runs.filter(id=resume_from_run_id).first()
diff --git a/products/tasks/backend/facade/profiles.py b/products/tasks/backend/facade/profiles.py
index aab048fca04f..45a3ec8c946b 100644
--- a/products/tasks/backend/facade/profiles.py
+++ b/products/tasks/backend/facade/profiles.py
@@ -62,6 +62,16 @@ class NetworkAccess(StrEnum):
CUSTOM = "custom"
+class ContractCheck(StrEnum):
+ PUBLIC_OPTIONS = "public_options"
+ RUNTIMES = "runtimes"
+ SANDBOX_TEMPLATES = "sandbox_templates"
+ MCP_SCOPES = "mcp_scopes"
+ GITHUB_ACCESS = "github_access"
+ IDLE_MINUTES = "idle_minutes"
+ DRIVE = "drive"
+
+
class SourceKind(StrEnum):
SIGNAL_REPORT = "signal_report"
HOG_FLOW = "hog_flow"
@@ -176,6 +186,7 @@ class TaskProfile:
# attaches it only when the task has a repository. NEVER attaches none. Use NEVER for tasks
# that read text members wrote, because a token there turns planted text into repository access.
github_resolution: GithubResolution
+ github_access: GithubAccess
# True lets runs open pull requests as the creator through their personal GitHub installation.
# A creator without a usable installation falls back to the bot. False always uses the bot.
user_authorable_prs: bool
@@ -217,6 +228,8 @@ class TaskProfile:
# wake and snapshots the task.
finish_in_flight: bool
+ enforced_checks: frozenset[ContractCheck] = frozenset()
+
@frozen
class Repository:
@@ -314,6 +327,10 @@ def register_task_profile(profile: TaskProfile) -> None:
existing = _profiles.get(profile.key)
if existing is not None and existing != profile:
raise TaskProfileError(f"Task profile {profile.key!r} is already registered with different values")
+ if (profile.github_access == GithubAccess.NONE) != (profile.github_resolution == GithubResolution.NEVER):
+ raise TaskProfileError(
+ f"Task profile {profile.key!r} must set github_access to none exactly when github_resolution is never"
+ )
for other in _profiles.values():
if other.key == profile.key or other.origin_product != profile.origin_product:
continue
@@ -338,6 +355,10 @@ def get_task_profile(key: str) -> TaskProfile:
raise TaskProfileError(f"Unknown task profile {key!r}") from None
+def find_task_profile(key: str | None) -> TaskProfile | None:
+ return _profiles.get(key) if key else None
+
+
def task_profiles() -> tuple[TaskProfile, ...]:
return tuple(_profiles.values())
diff --git a/products/tasks/backend/metrics.py b/products/tasks/backend/metrics.py
index 2177487f50a8..f06d1fad68ec 100644
--- a/products/tasks/backend/metrics.py
+++ b/products/tasks/backend/metrics.py
@@ -71,6 +71,12 @@ TASK_RUN_STARTED_BESIDE_LIVE_RUN_TOTAL = Counter(
],
)
+TASK_CONTRACT_VIOLATION_TOTAL = Counter(
+ "posthog_tasks_contract_violation_total",
+ "Task profile checks that a call failed. A profile that enforces the check refuses the call. Any other profile only counts it.",
+ labelnames=["check", "profile"],
+)
+
TASK_RUN_WORKFLOW_START_TOTAL = Counter(
"posthog_tasks_task_run_workflow_start_total",
"TaskRun workflow start lifecycle events",
@@ -619,6 +625,10 @@ def observe_task_run_started_beside_live_run(task_run: "TaskRun") -> None:
TASK_RUN_STARTED_BESIDE_LIVE_RUN_TOTAL.labels(**_task_run_labels(task_run)).inc()
+def observe_contract_violation(*, check: str, profile: str) -> None:
+ TASK_CONTRACT_VIOLATION_TOTAL.labels(check=check, profile=profile).inc()
+
+
def observe_sandbox_run_start(*, endpoint: str, outcome: str) -> None:
SANDBOX_RUN_START_TOTAL.labels(endpoint=endpoint, outcome=outcome).inc()
diff --git a/products/tasks/backend/models.py b/products/tasks/backend/models.py
index 5eb441c51726..7cde9290cb74 100644
--- a/products/tasks/backend/models.py
+++ b/products/tasks/backend/models.py
@@ -54,6 +54,7 @@ from products.tasks.backend.dev_stack_image_models import (
)
from products.tasks.backend.error_telemetry import truncate_error_message
from products.tasks.backend.facade.profiles import (
+ GithubAccess,
GithubResolution,
PrAuthorship,
TaskProfile,
@@ -79,7 +80,7 @@ from products.tasks.backend.metrics import (
)
from products.tasks.backend.pr_urls import read_pr_urls
from products.tasks.backend.redis import dedicated_stream_configured, run_uses_dedicated_stream
-from products.tasks.backend.run_options import RunSettings, apply_run_options, run_options_record
+from products.tasks.backend.run_options import RunSettings, apply_run_options, run_options_record, validate_run_options
from products.tasks.backend.storage import append_jsonl_object
from products.tasks.backend.task_sources import apply_task_source, source_from_columns
@@ -693,6 +694,11 @@ class Task(Taggable, DeletedMetaFields, models.Model):
if is_new:
transaction.on_commit(self._track_task_created)
+ @property
+ def github_access_limit(self) -> GithubAccess | None:
+ value = (self.options or {}).get("github_access")
+ return GithubAccess(value) if value else None
+
@property
def stored_profile(self) -> TaskProfile | None:
if not self.profile:
@@ -1316,7 +1322,15 @@ class Task(Taggable, DeletedMetaFields, models.Model):
)
@staticmethod
- def attaches_github(origin_product: str, profile: TaskProfile | None, *, has_repository: bool) -> bool:
+ def attaches_github(
+ origin_product: str,
+ profile: TaskProfile | None,
+ *,
+ has_repository: bool,
+ github_access: GithubAccess | None = None,
+ ) -> bool:
+ if github_access == GithubAccess.NONE:
+ return False
if profile is None:
return Task._github_resolution_allowed(origin_product, has_repository=has_repository)
if profile.github_resolution == GithubResolution.WITH_REPOSITORY:
@@ -1371,6 +1385,7 @@ class Task(Taggable, DeletedMetaFields, models.Model):
mcp_gateway_server_ids: list[str] | None = None,
mcp_tool_allowlist: list[str] | None = None,
profile: TaskProfile | None = None,
+ github_access: GithubAccess | None = None,
) -> tuple["Task", dict[str, Any]]:
"""Prepare an unsaved Task and the initial run's `extra_state`.
@@ -1407,7 +1422,9 @@ class Task(Taggable, DeletedMetaFields, models.Model):
user_github_integration_is_usable,
)
- github_resolution_allowed = Task.attaches_github(origin_product, profile, has_repository=bool(repository))
+ github_resolution_allowed = Task.attaches_github(
+ origin_product, profile, has_repository=bool(repository), github_access=github_access
+ )
github_integration = None
if github_resolution_allowed:
github_integration = next(
@@ -1692,6 +1709,7 @@ class Task(Taggable, DeletedMetaFields, models.Model):
source=source_from_columns(signal_report_id=columns.signal_report_id, hog_flow_id=columns.hog_flow_id),
)
runtime = profile.runtimes[0] if profile is not None else Task.Runtime.ACP.value
+ validate_run_options(profile, options)
if options is not None:
settings = apply_run_options(
options,
@@ -1734,6 +1752,7 @@ class Task(Taggable, DeletedMetaFields, models.Model):
client_provenance=client_provenance,
mcp_credential_owner_id=mcp_credential_owner_id,
mcp_gateway_server_ids=mcp_gateway_server_ids,
+ github_access=options.github_access if options is not None else None,
)
if options is not None:
task.options = run_options_record(options)
@@ -1828,6 +1847,7 @@ class Task(Taggable, DeletedMetaFields, models.Model):
check_task_source(
profile=profile, source=source_from_columns(signal_report_id=signal_report_id, hog_flow_id=hog_flow_id)
)
+ validate_run_options(profile, options)
if options is not None:
settings = apply_run_options(
options,
@@ -1912,6 +1932,7 @@ class Task(Taggable, DeletedMetaFields, models.Model):
mcp_credential_owner_id=mcp_credential_owner_id,
mcp_gateway_server_ids=mcp_gateway_server_ids,
mcp_tool_allowlist=mcp_tool_allowlist,
+ github_access=options.github_access if options is not None else None,
)
if options is not None:
task.options = run_options_record(options)
diff --git a/products/tasks/backend/run_options.py b/products/tasks/backend/run_options.py
index dd271b136adc..1ff21402046c 100644
--- a/products/tasks/backend/run_options.py
+++ b/products/tasks/backend/run_options.py
@@ -1,17 +1,32 @@
import json
-from dataclasses import asdict, replace
+from dataclasses import asdict, fields, replace
+from enum import StrEnum
from typing import TYPE_CHECKING, Any
from pydantic import BaseModel
from posthog.dataclasses import frozen
-
-from products.tasks.backend.facade.profiles import GithubAccess, TaskRunOptions, TaskRunOptionsError
+from posthog.scopes import scopes_not_covered
+from posthog.temporal.oauth import resolve_scopes
+
+from products.tasks.backend.contract_checks import contract_violation_refused
+from products.tasks.backend.facade.profiles import (
+ ContractCheck,
+ GithubAccess,
+ TaskProfile,
+ TaskRunOptions,
+ TaskRunOptionsError,
+)
if TYPE_CHECKING:
from posthog.temporal.oauth import PosthogMcpScopes
+class RunOptionsCaller(StrEnum):
+ SERVER = "server"
+ PUBLIC = "public"
+
+
@frozen
class RunSettings:
runtime: str = "acp"
@@ -98,9 +113,71 @@ def _run_state_from(options: TaskRunOptions) -> dict[str, Any]:
return state
+_GITHUB_ACCESS_RANK = {GithubAccess.NONE: 0, GithubAccess.READ: 1, GithubAccess.WRITE: 2}
+
+
+def _set_option_names(options: TaskRunOptions) -> list[str]:
+ defaults = TaskRunOptions()
+ return [field.name for field in fields(options) if getattr(options, field.name) != getattr(defaults, field.name)]
+
+
+def _scopes_within(requested: "PosthogMcpScopes", ceiling: "PosthogMcpScopes") -> bool:
+ return not scopes_not_covered(resolve_scopes(ceiling), resolve_scopes(requested))
+
+
+def _run_option_violations(
+ profile: TaskProfile, options: TaskRunOptions, caller: RunOptionsCaller
+) -> list[tuple[ContractCheck, str]]:
+ violations: list[tuple[ContractCheck, str]] = []
+ if caller == RunOptionsCaller.PUBLIC:
+ violations.extend(
+ (ContractCheck.PUBLIC_OPTIONS, f"{name} is not a public option of {profile.key}")
+ for name in _set_option_names(options)
+ if name not in profile.public_options
+ )
+ if options.runtime is not None and options.runtime not in profile.runtimes:
+ violations.append((ContractCheck.RUNTIMES, f"runtime {options.runtime} is not allowed for {profile.key}"))
+ if options.sandbox_template is not None and options.sandbox_template not in profile.sandbox_templates:
+ violations.append(
+ (
+ ContractCheck.SANDBOX_TEMPLATES,
+ f"sandbox_template {options.sandbox_template} is not allowed for {profile.key}",
+ )
+ )
+ if options.mcp_scopes is not None and not _scopes_within(options.mcp_scopes, profile.mcp_scopes):
+ violations.append((ContractCheck.MCP_SCOPES, f"mcp_scopes go beyond what {profile.key} allows"))
+ if (
+ options.github_access is not None
+ and _GITHUB_ACCESS_RANK[options.github_access] > _GITHUB_ACCESS_RANK[profile.github_access]
+ ):
+ violations.append(
+ (ContractCheck.GITHUB_ACCESS, f"github_access {options.github_access} is above what {profile.key} allows")
+ )
+ if options.idle_minutes is not None and options.idle_minutes > profile.idle_minutes:
+ violations.append(
+ (ContractCheck.IDLE_MINUTES, f"idle_minutes {options.idle_minutes} is above the {profile.key} limit")
+ )
+ return violations
+
+
+def validate_run_options(
+ profile: TaskProfile | None,
+ options: TaskRunOptions | None,
+ *,
+ caller: RunOptionsCaller = RunOptionsCaller.SERVER,
+) -> None:
+ if profile is None or options is None:
+ return
+ refusals = [
+ detail
+ for check, detail in _run_option_violations(profile, options, caller)
+ if contract_violation_refused(profile, check, detail)
+ ]
+ if refusals:
+ raise TaskRunOptionsError("; ".join(refusals))
+
+
def apply_run_options(options: TaskRunOptions, given: RunSettings, *, creates_run: bool = True) -> RunSettings:
- if options.github_access == GithubAccess.NONE:
- raise TaskRunOptionsError("github_access=none is not supported yet")
settings = _settings_from(options)
run_state = _run_state_from(options)
if not creates_run:
@@ -112,6 +189,10 @@ def apply_run_options(options: TaskRunOptions, given: RunSettings, *, creates_ru
given_run_state = given.extra_run_state or {}
defaults = RunSettings()
conflicts = [name for name in settings if getattr(given, name) != getattr(defaults, name)]
+ if options.github_access == GithubAccess.NONE and (
+ given.github_read_access or "github_read_access" in given_run_state
+ ):
+ conflicts.append("github_read_access")
if "repositories" in settings and given.repository is not None:
conflicts.append("repository")
conflicts.extend(name for name in settings if _SETTING_RUN_STATE_KEYS.get(name) in given_run_state)
diff --git a/products/tasks/backend/temporal/process_task/tests/test_utils.py b/products/tasks/backend/temporal/process_task/tests/test_utils.py
index 461315b4eca6..6fbc7067aca8 100644
--- a/products/tasks/backend/temporal/process_task/tests/test_utils.py
+++ b/products/tasks/backend/temporal/process_task/tests/test_utils.py
@@ -52,6 +52,7 @@ from products.tasks.backend.temporal.process_task.utils import (
mcp_exclude_tools_from_state,
mcp_exec_skills_env_vars,
parse_run_state,
+ resolve_user_github_integration_for_task,
sanitize_mcp_exclude_tools,
upgrade_run_to_user_authorship,
)
@@ -1224,6 +1225,26 @@ class TestGetUserGithubIntegration(TestCase):
assert resolved.integration.integration_id == "222"
+class TestResolveUserGithubIntegrationForTask(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("no_access", {"github_access": "none"}, False),
+ ("read_access", {"github_access": "read"}, True),
+ ("no_limit", None, True),
+ ]
+ )
+ @patch("products.tasks.backend.temporal.process_task.utils.get_user_github_integration")
+ def test_a_task_without_github_access_resolves_no_personal_integration(
+ self, _name: str, options: dict | None, resolves: bool, mock_get_identity: MagicMock
+ ) -> None:
+ identity = MagicMock(name="identity")
+ mock_get_identity.return_value = identity
+
+ resolved = resolve_user_github_integration_for_task(Task(options=options), actor_user=MagicMock())
+
+ assert resolved is (identity if resolves else None)
+
+
class TestGetSandboxGitHubToken(SimpleTestCase):
@parameterized.expand(
[
@@ -1289,6 +1310,33 @@ class TestGetSandboxGitHubToken(SimpleTestCase):
else:
mock_get_github_token.assert_not_called()
+ @parameterized.expand(
+ [
+ ("no_access_user_authored", {"github_access": "none"}, "user", None),
+ ("no_access_bot_authored", {"github_access": "none"}, "bot", None),
+ ("read_access_user_authored", {"github_access": "read"}, "user", "ghp_cached"),
+ ("no_limit_bot_authored", None, "bot", "ghs_team"),
+ ]
+ )
+ @patch("products.tasks.backend.temporal.process_task.utils.get_github_token", return_value="ghs_team")
+ @patch("products.tasks.backend.temporal.process_task.utils.get_cached_github_user_token", return_value="ghp_cached")
+ def test_a_task_without_github_access_resolves_no_token(
+ self,
+ _name: str,
+ options: dict | None,
+ mode: str,
+ expected: str | None,
+ _mock_cached: MagicMock,
+ _mock_get_github_token: MagicMock,
+ ) -> None:
+ task = Task(options=options, github_integration_id=123)
+
+ token = get_sandbox_github_token(
+ 123, run_id="run-1", state={"pr_authorship_mode": mode}, task=task, repository="posthog/posthog"
+ )
+
+ assert token == expected
+
@parameterized.expand(
[
("reauthorization",),
diff --git a/products/tasks/backend/temporal/process_task/utils.py b/products/tasks/backend/temporal/process_task/utils.py
index f47c58fce7c9..90d5c89f5498 100644
--- a/products/tasks/backend/temporal/process_task/utils.py
+++ b/products/tasks/backend/temporal/process_task/utils.py
@@ -51,7 +51,7 @@ from products.tasks.backend.exceptions import (
ProcessTaskTransientError,
)
from products.tasks.backend.facade.gateway import mint_private_gateway_token, revoke_private_gateway_token
-from products.tasks.backend.facade.profiles import MAX_MCP_EXCLUDE_TOOLS, TaskProfile
+from products.tasks.backend.facade.profiles import MAX_MCP_EXCLUDE_TOOLS, GithubAccess, TaskProfile
from products.tasks.backend.feature_flags import is_mcp_exec_skills_enabled
from products.tasks.backend.logic.model_access import ModelAccess, resolve_model_access
from products.tasks.backend.logic.services.desktop_gateway_token import (
@@ -1299,6 +1299,8 @@ def resolve_user_github_integration_for_task(
allow_refresh: bool = False,
) -> UserGitHubIntegration | None:
"""Resolve the UserIntegration that should author a task's GitHub writes."""
+ if task.github_access_limit == GithubAccess.NONE:
+ return None
user = actor_user or task.created_by
if user is None:
return None
@@ -1447,6 +1449,8 @@ def _resolve_sandbox_github_token(
``BOT`` authorship falls through to the team's ``Integration`` installation token.
"""
pr_authorship_mode: PrAuthorshipMode | None
+ if task is not None and task.github_access_limit == GithubAccess.NONE:
+ return None
slack_interaction = is_slack_interaction_state(state)
created_by = actor_user or created_by
if task is not None:
diff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.py
index dcfc86326a04..4c1836491c53 100644
--- a/products/tasks/backend/tests/test_api.py
+++ b/products/tasks/backend/tests/test_api.py
@@ -5235,6 +5235,55 @@ class TestTaskAPI(BaseTaskAPITest):
self.assertIsNone(task.github_user_integration_id)
mock_workflow.assert_not_called()
+ @parameterized.expand(
+ [
+ ("create_run_user_authored", "runs", "user", None, {"github_access": "none"}, "bot", False),
+ ("create_run_bot_authored", "runs", "bot", None, {"github_access": "none"}, "bot", False),
+ ("run_user_authored", "run", "user", None, {"github_access": "none"}, "bot", False),
+ ("run_bot_authored", "run", "bot", None, {"github_access": "none"}, "bot", False),
+ ("run_caller_token", "run", "user", "ghu_test_token", {"github_access": "none"}, "bot", False),
+ ("create_run_without_a_limit", "runs", "user", None, None, "user", True),
+ ("create_run_with_a_read_limit", "runs", "user", None, {"github_access": "read"}, "user", True),
+ ]
+ )
+ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
+ def test_starting_a_run_honors_the_task_github_access_limit(
+ self,
+ _name: str,
+ endpoint: str,
+ requested_mode: str,
+ github_user_token: str | None,
+ options: dict | None,
+ expected_mode: str,
+ attached: bool,
+ _mock_workflow,
+ ):
+ Integration.objects.create(team=self.team, kind="github", config={"access_token": "token"})
+ user_integration = _grant_user_github_access(self.user)
+ task = self.create_task(created_by=self.user)
+ task.repository = "posthog/posthog"
+ task.options = options
+ task.save(update_fields=["repository", "options"])
+ payload = {"pr_authorship_mode": requested_mode, "run_source": "manual"}
+ if endpoint == "runs":
+ payload["environment"] = "cloud"
+ else:
+ payload.update(mode="interactive", branch="main")
+ if github_user_token:
+ payload["github_user_token"] = github_user_token
+
+ response = self.client.post(f"/api/projects/@current/tasks/{task.id}/{endpoint}/", payload, format="json")
+
+ self.assertIn(response.status_code, (status.HTTP_200_OK, status.HTTP_201_CREATED), response.content)
+ task.refresh_from_db()
+ run_id = response.json()["id"] if endpoint == "runs" else response.json()["latest_run"]["id"]
+ task_run = TaskRun.objects.get(id=run_id)
+ self.assertEqual(task_run.state["pr_authorship_mode"], expected_mode)
+ self.assertEqual(task.github_user_integration_id, user_integration.id if attached else None)
+ self.assertIsNone(task.github_integration_id)
+ self.assertEqual("github_credential_source" in task_run.state, attached)
+ self.assertIsNone(get_cached_github_user_token(run_id))
+
@patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
def test_create_run_endpoint_cannot_start_a_product_private_account_audit(self, mock_workflow):
Integration.objects.create(team=self.team, kind="github", config={"access_token": "token"})
@@ -17760,6 +17809,27 @@ class TestCloudUsageGate(BaseTaskAPITest):
self.assertEqual(task.github_integration_id is not None, attached)
self.assertEqual(task.github_user_integration_id is not None, attached and repository is not None)
+ @parameterized.expand(
+ [
+ ("none_refuses_a_later_attachment", {"github_access": "none"}, False),
+ ("read_takes_a_later_attachment", {"github_access": "read"}, True),
+ ("no_options_take_a_later_attachment", None, True),
+ ]
+ )
+ def test_update_follows_the_task_github_access_option(self, _name, options: dict | None, attached: bool):
+ integration = Integration.objects.create(team=self.team, kind="github", config={})
+ task = self.create_task()
+ task.options = options
+ task.save()
+
+ response = self.client.patch(
+ f"/api/projects/@current/tasks/{task.id}/", {"github_integration": integration.id}, format="json"
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())
+ task.refresh_from_db()
+ self.assertEqual(task.github_integration_id is not None, attached)
+
@patch("products.tasks.backend.logic.services.code_usage_gate.get_posthog_code_usage")
def test_start_without_code_access_returns_403(self, mock_gate):
self.set_tasks_feature_flag(False)
diff --git a/products/tasks/backend/tests/test_contract_checks.py b/products/tasks/backend/tests/test_contract_checks.py
new file mode 100644
index 000000000000..96096e94a3cc
--- /dev/null
+++ b/products/tasks/backend/tests/test_contract_checks.py
@@ -0,0 +1,259 @@
+from dataclasses import replace
+
+from unittest.mock import patch
+
+from django.test import SimpleTestCase
+
+import structlog.testing
+from parameterized import parameterized
+from prometheus_client import REGISTRY
+
+from products.tasks.backend.contract_checks import drive_allowed
+from products.tasks.backend.facade.profiles import (
+ ContractCheck,
+ DrivePolicy,
+ GithubAccess,
+ TaskProfile,
+ TaskRunOptions,
+ TaskRunOptionsError,
+ get_task_profile,
+)
+from products.tasks.backend.run_options import RunOptionsCaller, validate_run_options
+
+SERVER = RunOptionsCaller.SERVER
+PUBLIC = RunOptionsCaller.PUBLIC
+
+LOG_PROFILE = replace(
+ get_task_profile("business_knowledge"),
+ key="test.run_option_checks",
+ public_options=frozenset({"model", "idle_minutes"}),
+ runtimes=("acp", "pi"),
+ sandbox_templates=("default_base", "autoresearch_base"),
+ mcp_scopes="read_only",
+ github_access=GithubAccess.READ,
+ idle_minutes=30,
+)
+ENFORCE_PROFILE = replace(LOG_PROFILE, enforced_checks=frozenset(ContractCheck))
+WIDE_OPTIONS = TaskRunOptions(
+ runtime="other",
+ sandbox_template="vm_base",
+ mcp_scopes="full",
+ github_access=GithubAccess.WRITE,
+ idle_minutes=31,
+)
+
+CASES = [
+ ("runtime_in_list", TaskRunOptions(runtime="pi"), SERVER, ()),
+ ("runtime_outside_list", TaskRunOptions(runtime="other"), SERVER, (ContractCheck.RUNTIMES,)),
+ ("template_in_list", TaskRunOptions(sandbox_template="autoresearch_base"), SERVER, ()),
+ ("template_outside_list", TaskRunOptions(sandbox_template="vm_base"), SERVER, (ContractCheck.SANDBOX_TEMPLATES,)),
+ ("scopes_narrower", TaskRunOptions(mcp_scopes=["project:read"]), SERVER, ()),
+ ("scopes_equal", TaskRunOptions(mcp_scopes="read_only"), SERVER, ()),
+ ("scopes_wider", TaskRunOptions(mcp_scopes="full"), SERVER, (ContractCheck.MCP_SCOPES,)),
+ (
+ "scopes_partly_wider",
+ TaskRunOptions(mcp_scopes=["project:read", "dashboard:write"]),
+ SERVER,
+ (ContractCheck.MCP_SCOPES,),
+ ),
+ ("github_none", TaskRunOptions(github_access=GithubAccess.NONE), SERVER, ()),
+ ("github_equal", TaskRunOptions(github_access=GithubAccess.READ), SERVER, ()),
+ ("github_wider", TaskRunOptions(github_access=GithubAccess.WRITE), SERVER, (ContractCheck.GITHUB_ACCESS,)),
+ ("idle_lower", TaskRunOptions(idle_minutes=5), SERVER, ()),
+ ("idle_equal", TaskRunOptions(idle_minutes=30), SERVER, ()),
+ ("idle_higher", TaskRunOptions(idle_minutes=31), SERVER, (ContractCheck.IDLE_MINUTES,)),
+ (
+ "some_options_widen",
+ TaskRunOptions(runtime="pi", sandbox_template="vm_base", idle_minutes=31, mcp_scopes=["project:read"]),
+ SERVER,
+ (ContractCheck.SANDBOX_TEMPLATES, ContractCheck.IDLE_MINUTES),
+ ),
+ (
+ "every_option_widens",
+ WIDE_OPTIONS,
+ SERVER,
+ tuple(set(ContractCheck) - {ContractCheck.PUBLIC_OPTIONS, ContractCheck.DRIVE}),
+ ),
+ ("public_options_only", TaskRunOptions(model="m", idle_minutes=5), PUBLIC, ()),
+ ("public_option_outside_list", TaskRunOptions(runtime="acp"), PUBLIC, (ContractCheck.PUBLIC_OPTIONS,)),
+ (
+ "public_options_partly_outside_list",
+ TaskRunOptions(model="m", idle_minutes=5, fast_mode=True),
+ PUBLIC,
+ (ContractCheck.PUBLIC_OPTIONS,),
+ ),
+ ("public_without_options", TaskRunOptions(), PUBLIC, ()),
+ ("server_sets_option_outside_public_list", TaskRunOptions(runtime="acp"), SERVER, ()),
+]
+
+
+def _violation_counts(profile: TaskProfile) -> dict[ContractCheck, float]:
+ return {
+ check: REGISTRY.get_sample_value(
+ "posthog_tasks_contract_violation_total", {"check": check.value, "profile": profile.key}
+ )
+ or 0
+ for check in ContractCheck
+ }
+
+
+class TestValidateRunOptions(SimpleTestCase):
+ @parameterized.expand(CASES)
+ def test_log_mode_counts_each_violation_and_refuses_nothing(
+ self, _name: str, options: TaskRunOptions, caller: RunOptionsCaller, violated: tuple[ContractCheck, ...]
+ ) -> None:
+ before = _violation_counts(LOG_PROFILE)
+
+ with structlog.testing.capture_logs() as logs:
+ validate_run_options(LOG_PROFILE, options, caller=caller)
+
+ after = _violation_counts(LOG_PROFILE)
+ self.assertEqual({check for check in ContractCheck if after[check] - before[check] == 1}, set(violated))
+ self.assertEqual({check for check in ContractCheck if after[check] - before[check] > 1}, set())
+ self.assertEqual(
+ {(log["event"], log["check"]) for log in logs},
+ {("task_contract_violation_would_refuse", check.value) for check in violated},
+ )
+
+ @parameterized.expand(CASES)
+ def test_enforce_mode_refuses_the_options_that_widen_the_profile(
+ self, _name: str, options: TaskRunOptions, caller: RunOptionsCaller, violated: tuple[ContractCheck, ...]
+ ) -> None:
+ with structlog.testing.capture_logs() as logs:
+ if violated:
+ with self.assertRaises(TaskRunOptionsError):
+ validate_run_options(ENFORCE_PROFILE, options, caller=caller)
+ else:
+ validate_run_options(ENFORCE_PROFILE, options, caller=caller)
+
+ self.assertEqual({log["check"] for log in logs}, {check.value for check in violated})
+ self.assertEqual({log["event"] for log in logs}, {"task_contract_violation_refused"} if violated else set())
+
+ @parameterized.expand(
+ [
+ ("read_under_an_injected_write", ["user:read"], ["task:read"], False),
+ ("business_knowledge_task_read", get_task_profile("business_knowledge").mcp_scopes, ["task:read"], False),
+ ("read_under_an_explicit_write", ["dashboard:write"], ["dashboard:read"], False),
+ ("same_scope", ["dashboard:write"], ["dashboard:write"], False),
+ ("write_over_a_read", ["dashboard:read"], ["dashboard:write"], True),
+ ("read_of_another_object", ["dashboard:write"], ["insight:read"], True),
+ ("some_scopes_outside_the_ceiling", ["dashboard:write"], ["dashboard:read", "insight:read"], True),
+ ]
+ )
+ def test_a_write_scope_in_the_ceiling_covers_the_read_scope(
+ self, _name: str, ceiling: list[str], requested: list[str], violated: bool
+ ) -> None:
+ profile = replace(LOG_PROFILE, key="test.scope_ceiling", mcp_scopes=ceiling)
+ before = _violation_counts(profile)[ContractCheck.MCP_SCOPES]
+
+ validate_run_options(profile, TaskRunOptions(mcp_scopes=requested))
+
+ self.assertEqual(_violation_counts(profile)[ContractCheck.MCP_SCOPES] - before, int(violated))
+
+ @parameterized.expand(
+ [
+ ("enforced_check_violated", {ContractCheck.RUNTIMES}, TaskRunOptions(runtime="other"), True),
+ (
+ "enforced_check_violated_beside_another",
+ {ContractCheck.RUNTIMES},
+ TaskRunOptions(runtime="other", sandbox_template="vm_base"),
+ True,
+ ),
+ ("other_check_violated", {ContractCheck.RUNTIMES}, TaskRunOptions(sandbox_template="vm_base"), False),
+ ("enforced_check_kept", {ContractCheck.RUNTIMES}, TaskRunOptions(runtime="pi", idle_minutes=31), False),
+ ]
+ )
+ def test_enforcement_is_per_check(
+ self, _name: str, enforced: set[ContractCheck], options: TaskRunOptions, refused: bool
+ ) -> None:
+ profile = replace(LOG_PROFILE, enforced_checks=frozenset(enforced))
+
+ if refused:
+ with self.assertRaisesRegex(TaskRunOptionsError, "runtime other") as context:
+ validate_run_options(profile, options)
+ self.assertNotIn("sandbox_template", str(context.exception))
+ else:
+ validate_run_options(profile, options)
+
+ @parameterized.expand([("without_profile", None, WIDE_OPTIONS), ("without_options", ENFORCE_PROFILE, None)])
+ def test_nothing_to_check_changes_nothing(
+ self, _name: str, profile: TaskProfile | None, options: TaskRunOptions | None
+ ) -> None:
+ before = _violation_counts(ENFORCE_PROFILE)
+
+ validate_run_options(profile, options, caller=PUBLIC)
+
+ self.assertEqual(_violation_counts(ENFORCE_PROFILE), before)
+
+
+DRIVE_CASES = [
+ ("audience_owner", DrivePolicy.AUDIENCE, 1, 1, False),
+ ("audience_other_user", DrivePolicy.AUDIENCE, 1, 2, False),
+ ("audience_task_without_owner", DrivePolicy.AUDIENCE, None, 2, False),
+ ("owner_drives_own_task", DrivePolicy.OWNER, 1, 1, False),
+ ("owner_policy_other_user", DrivePolicy.OWNER, 1, 2, True),
+ ("owner_policy_task_without_owner", DrivePolicy.OWNER, None, 2, True),
+ ("owner_policy_without_user", DrivePolicy.OWNER, 1, None, True),
+ ("none_policy_owner", DrivePolicy.NONE, 1, 1, True),
+ ("none_policy_other_user", DrivePolicy.NONE, 1, 2, True),
+]
+
+
+def _drive_profile(drive: DrivePolicy, enforced: frozenset[ContractCheck] = frozenset()) -> TaskProfile:
+ return replace(LOG_PROFILE, key="test.drive_checks", drive=drive, enforced_checks=enforced)
+
+
+class TestDriveAllowed(SimpleTestCase):
+ def _allowed(self, profile: TaskProfile, *, created_by_id: int | None, user_id: int | None) -> bool:
+ with patch.dict("products.tasks.backend.facade.profiles._profiles", {profile.key: profile}):
+ return drive_allowed(profile.key, created_by_id=created_by_id, user_id=user_id)
+
+ @parameterized.expand(DRIVE_CASES)
+ def test_log_mode_allows_every_caller_and_counts_those_it_would_refuse(
+ self, _name: str, drive: DrivePolicy, created_by_id: int | None, user_id: int | None, violates: bool
+ ) -> None:
+ profile = _drive_profile(drive)
+ before = _violation_counts(profile)
+
+ allowed = self._allowed(profile, created_by_id=created_by_id, user_id=user_id)
+
+ self.assertTrue(allowed)
+ self.assertEqual(_violation_counts(profile)[ContractCheck.DRIVE] - before[ContractCheck.DRIVE], int(violates))
+
+ @parameterized.expand(DRIVE_CASES)
+ def test_enforce_mode_refuses_the_callers_the_policy_does_not_allow(
+ self, _name: str, drive: DrivePolicy, created_by_id: int | None, user_id: int | None, violates: bool
+ ) -> None:
+ profile = _drive_profile(drive, frozenset({ContractCheck.DRIVE}))
+
+ self.assertEqual(self._allowed(profile, created_by_id=created_by_id, user_id=user_id), not violates)
+
+ @parameterized.expand([(name, *case) for name, *case in DRIVE_CASES if case[-1]])
+ def test_enforcing_another_check_leaves_drive_in_log_mode(
+ self, _name: str, drive: DrivePolicy, created_by_id: int | None, user_id: int | None, _violates: bool
+ ) -> None:
+ profile = _drive_profile(drive, frozenset({ContractCheck.RUNTIMES}))
+
+ self.assertTrue(self._allowed(profile, created_by_id=created_by_id, user_id=user_id))
+
+ @parameterized.expand([("no_key", None), ("empty_key", "")])
+ def test_a_task_without_a_stored_profile_is_always_drivable(self, _name: str, profile_key: str | None) -> None:
+ before = _violation_counts(_drive_profile(DrivePolicy.NONE))
+
+ self.assertTrue(drive_allowed(profile_key, created_by_id=1, user_id=2))
+
+ self.assertEqual(_violation_counts(_drive_profile(DrivePolicy.NONE)), before)
+
+ def test_a_stored_key_that_is_not_registered_is_counted_by_its_key_and_still_drivable(self) -> None:
+ sample = {"check": ContractCheck.DRIVE.value, "profile": "test.removed_profile"}
+ before = REGISTRY.get_sample_value("posthog_tasks_contract_violation_total", sample) or 0
+
+ with structlog.testing.capture_logs() as logs:
+ allowed = drive_allowed("test.removed_profile", created_by_id=1, user_id=2)
+
+ self.assertTrue(allowed)
+ self.assertEqual((REGISTRY.get_sample_value("posthog_tasks_contract_violation_total", sample) or 0) - before, 1)
+ self.assertEqual(
+ [(log["event"], log["profile"]) for log in logs],
+ [("task_contract_violation_unregistered_profile", "test.removed_profile")],
+ )
diff --git a/products/tasks/backend/tests/test_facade.py b/products/tasks/backend/tests/test_facade.py
index c268be7bc253..a7c8283d7ce1 100644
--- a/products/tasks/backend/tests/test_facade.py
+++ b/products/tasks/backend/tests/test_facade.py
@@ -14,6 +14,7 @@ from django.test import SimpleTestCase, TestCase, TransactionTestCase, override_
from django.utils import timezone as django_timezone
from parameterized import parameterized
+from prometheus_client import REGISTRY
from rest_framework.exceptions import ValidationError
from posthog.clickhouse.query_tagging import get_query_tags, reset_query_tags
@@ -31,6 +32,8 @@ from products.tasks.backend.facade import (
)
from products.tasks.backend.facade.access import PostHogAIAccessDecision
from products.tasks.backend.facade.profiles import (
+ ContractCheck,
+ DrivePolicy,
Read,
Repository,
SourceKind,
@@ -594,6 +597,195 @@ class TestFacadeReadsAndMappers(TestCase):
assert facade.task_accessible_for_run_view(task.id, self.team.id, self.user.id, for_control=for_control)
assert not facade.task_accessible_for_run_view(task.id, self.team.id, outsider.id, for_control=for_control)
+ @parameterized.expand(
+ [
+ ("run_view_in_log_mode", "run_view", DrivePolicy.NONE, frozenset(), True, False, True),
+ ("run_view_enforced", "run_view", DrivePolicy.NONE, frozenset({ContractCheck.DRIVE}), True, False, False),
+ (
+ "run_view_enforced_for_reading",
+ "run_view",
+ DrivePolicy.NONE,
+ frozenset({ContractCheck.DRIVE}),
+ False,
+ False,
+ True,
+ ),
+ (
+ "run_view_enforced_for_the_owner",
+ "run_view",
+ DrivePolicy.OWNER,
+ frozenset({ContractCheck.DRIVE}),
+ True,
+ False,
+ True,
+ ),
+ (
+ "run_view_enforced_for_a_sandbox",
+ "run_view",
+ DrivePolicy.NONE,
+ frozenset({ContractCheck.DRIVE}),
+ True,
+ True,
+ True,
+ ),
+ (
+ "run_view_with_another_check_enforced",
+ "run_view",
+ DrivePolicy.NONE,
+ frozenset({ContractCheck.RUNTIMES}),
+ True,
+ False,
+ True,
+ ),
+ ("task_visible_in_log_mode", "task_visible", DrivePolicy.NONE, frozenset(), True, False, True),
+ (
+ "task_visible_enforced",
+ "task_visible",
+ DrivePolicy.NONE,
+ frozenset({ContractCheck.DRIVE}),
+ True,
+ False,
+ False,
+ ),
+ (
+ "task_visible_enforced_for_reading",
+ "task_visible",
+ DrivePolicy.NONE,
+ frozenset({ContractCheck.DRIVE}),
+ False,
+ False,
+ True,
+ ),
+ (
+ "task_visible_enforced_for_the_owner",
+ "task_visible",
+ DrivePolicy.OWNER,
+ frozenset({ContractCheck.DRIVE}),
+ True,
+ False,
+ True,
+ ),
+ ]
+ )
+ def test_control_gates_apply_the_profile_drive_policy(
+ self,
+ _name: str,
+ gate: str,
+ drive: DrivePolicy,
+ enforced: frozenset[ContractCheck],
+ for_control: bool,
+ bypass_visibility: bool,
+ allowed: bool,
+ ) -> None:
+ profile = replace(
+ get_task_profile("business_knowledge"), key="test.drive", drive=drive, enforced_checks=enforced
+ )
+ task = self._make_task(profile=profile.key)
+
+ with patch.dict("products.tasks.backend.facade.profiles._profiles", {profile.key: profile}):
+ if gate == "run_view":
+ with self.assertNumQueries(1):
+ result = facade.task_accessible_for_run_view(
+ task.id,
+ self.team.id,
+ self.user.id,
+ for_control=for_control,
+ bypass_visibility=bypass_visibility,
+ )
+ else:
+ result = facade.task_visible(task.id, self.team.id, self.user.id, for_control=for_control)
+
+ self.assertIs(result, allowed)
+
+ @parameterized.expand(
+ [
+ ("token_bound_to_this_task", True, "own", True),
+ ("token_bound_to_another_task", True, "other", False),
+ ("token_without_a_bound_task", True, None, False),
+ ("no_sandbox_token", False, None, False),
+ ]
+ )
+ def test_only_a_sandbox_token_bound_to_the_task_skips_the_drive_policy(
+ self, _name: str, sandbox_request: bool, bound: str | None, allowed: bool
+ ) -> None:
+ profile = replace(
+ get_task_profile("business_knowledge"),
+ key="test.drive_sandbox",
+ drive=DrivePolicy.NONE,
+ enforced_checks=frozenset({ContractCheck.DRIVE}),
+ )
+ task = self._make_task(profile=profile.key)
+ sandbox_task_id = {"own": task.id, "other": uuid4(), None: None}[bound]
+
+ with patch.dict("products.tasks.backend.facade.profiles._profiles", {profile.key: profile}):
+ result = facade.task_accessible_for_run_view(
+ task.id,
+ self.team.id,
+ self.user.id,
+ for_control=True,
+ sandbox_request=sandbox_request,
+ sandbox_task_id=sandbox_task_id,
+ )
+
+ self.assertIs(result, allowed)
+
+ @parameterized.expand(
+ [
+ (f"{gate}_{mode}", gate, drive, enforced, refused)
+ for gate in ("prepare_artifacts", "finalize_artifacts", "warm_resume", "update", "delete", "handoff")
+ for mode, drive, enforced, refused in (
+ ("none_policy_in_log_mode", DrivePolicy.NONE, frozenset(), False),
+ ("none_policy_enforced", DrivePolicy.NONE, frozenset({ContractCheck.DRIVE}), True),
+ ("owner_policy_enforced", DrivePolicy.OWNER, frozenset({ContractCheck.DRIVE}), False),
+ )
+ ]
+ )
+ def test_control_gates_outside_the_run_views_apply_the_drive_policy(
+ self, _name: str, gate: str, drive: DrivePolicy, enforced: frozenset[ContractCheck], refused: bool
+ ) -> None:
+ profile = replace(
+ get_task_profile("business_knowledge"), key="test.drive_steering", drive=drive, enforced_checks=enforced
+ )
+ task = self._make_task(profile=profile.key)
+ sample = {"check": ContractCheck.DRIVE.value, "profile": profile.key}
+ before = REGISTRY.get_sample_value("posthog_tasks_contract_violation_total", sample) or 0
+ if gate == "handoff":
+ recipient = User.objects.create(email="[email protected]", distinct_id="recipient-distinct")
+ self.organization.members.add(recipient)
+
+ with patch.dict("products.tasks.backend.facade.profiles._profiles", {profile.key: profile}):
+ if gate == "prepare_artifacts":
+ refused_by_gate = (
+ facade.prepare_task_staged_artifacts(
+ task.id, self.team.id, self.user.id, artifacts=[], upload_expiration_seconds=60
+ )
+ is None
+ )
+ elif gate == "finalize_artifacts":
+ refused_by_gate = (
+ facade.finalize_task_staged_artifacts(task.id, self.team.id, self.user.id, artifacts=[]) is None
+ )
+ elif gate == "update":
+ refused_by_gate = (
+ facade.update_task(task.id, self.team.id, self.user.id, validated_data={"title": "Renamed"}) is None
+ )
+ elif gate == "delete":
+ refused_by_gate = not facade.soft_delete_task(task.id, self.team.id, self.user.id)
+ elif gate == "handoff":
+ refused_by_gate = (
+ facade.handoff_task(task.id, self.team.id, self.user.id, target_user_id=recipient.id) is None
+ )
+ else:
+ refused_by_gate = (
+ facade.warm_task_resume_sandbox(task.id, self.team.id, self.user.id, resume_from_run_id=uuid4())
+ is None
+ )
+
+ counted = (REGISTRY.get_sample_value("posthog_tasks_contract_violation_total", sample) or 0) - before
+ self.assertEqual(counted, 1 if drive == DrivePolicy.NONE else 0)
+ if gate != "warm_resume":
+ self.assertEqual(refused_by_gate, refused)
+
def test_task_control_runtime_and_origin_uses_control_predicate(self):
task = self._make_task(origin_product=Task.OriginProduct.POSTHOG_AI, runtime=Task.Runtime.PI)
self.assertEqual(
diff --git a/products/tasks/backend/tests/test_models.py b/products/tasks/backend/tests/test_models.py
index 82594c3a2f41..042ee1194a83 100644
--- a/products/tasks/backend/tests/test_models.py
+++ b/products/tasks/backend/tests/test_models.py
@@ -24,6 +24,7 @@ from posthog.models.user_integration import UserIntegration
from posthog.storage import object_storage
from products.tasks.backend.facade.profiles import (
+ ContractCheck,
GithubAccess,
GithubResolution,
PrAuthorship,
@@ -65,7 +66,12 @@ POSTHOG_AI_BOT_PROFILE = replace(
github_resolution=GithubResolution.ALWAYS,
)
PI_PROFILE = replace(BUSINESS_KNOWLEDGE, key="test.pi", runtimes=("pi",))
-NO_GITHUB_PROFILE = replace(BUSINESS_KNOWLEDGE, key="test.no_github", github_resolution=GithubResolution.NEVER)
+NO_GITHUB_PROFILE = replace(
+ BUSINESS_KNOWLEDGE,
+ key="test.no_github",
+ github_resolution=GithubResolution.NEVER,
+ github_access=GithubAccess.NONE,
+)
SUPPORT_AGENT_PROFILE = replace(BUSINESS_KNOWLEDGE, key="test.support_agent", mcp_agent="support")
# Far enough back that any bump is unambiguously forward, and stable so a test can assert the
@@ -288,7 +294,16 @@ class TestTask(TestCase):
{"extra_run_state": {"model": "claude-opus-5"}},
TaskRunOptions(model="claude-sonnet-5"),
),
- ("no_github_access", {}, TaskRunOptions(github_access=GithubAccess.NONE)),
+ (
+ "no_github_access_with_read_argument",
+ {"github_read_access": True},
+ TaskRunOptions(github_access=GithubAccess.NONE),
+ ),
+ (
+ "no_github_access_with_read_run_state",
+ {"extra_run_state": {"github_read_access": True}},
+ TaskRunOptions(github_access=GithubAccess.NONE),
+ ),
]
)
def test_run_options_refuse_a_setting_they_cannot_apply(
@@ -309,6 +324,35 @@ class TestTask(TestCase):
self.assertFalse(Task.objects.filter(team=self.team).exists())
+ @parameterized.expand(
+ [
+ ("run_unset", "create_and_run", None, True),
+ ("run_none", "create_and_run", GithubAccess.NONE, False),
+ ("run_read", "create_and_run", GithubAccess.READ, True),
+ ("run_write", "create_and_run", GithubAccess.WRITE, True),
+ ("without_run_none", "create_without_run", GithubAccess.NONE, False),
+ ("without_run_write", "create_without_run", GithubAccess.WRITE, True),
+ ]
+ )
+ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
+ def test_github_access_none_attaches_no_github_integration(
+ self, name: str, entry: str, github_access: GithubAccess | None, attached: bool, _mock_execute_workflow
+ ) -> None:
+ user = User.objects.create(email=f"{name}@test.com")
+ Integration.objects.create(team=self.team, kind="github", config={})
+
+ task = getattr(Task, entry)(
+ team=self.team,
+ title="t",
+ description="d",
+ user_id=user.id,
+ origin_product=Task.OriginProduct.USER_CREATED,
+ options=TaskRunOptions(github_access=github_access) if github_access else None,
+ )
+
+ task.refresh_from_db()
+ self.assertEqual(task.github_integration_id is not None, attached)
+
@parameterized.expand([("empty", []), ("one_server", ["server-1"])])
@patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
def test_run_options_keep_the_mcp_server_allowlist(
@@ -760,6 +804,46 @@ class TestTask(TestCase):
state = TaskRun.objects.get(id=mock_execute_workflow.call_args.kwargs["run_id"]).state
self.assertEqual((task.runtime, state.get("sandbox_template")), expected)
+ @parameterized.expand(
+ [
+ ("run_in_log_mode", "create_and_run", frozenset(), True),
+ ("run_with_the_check_enforced", "create_and_run", frozenset({ContractCheck.RUNTIMES}), False),
+ ("run_with_another_check_enforced", "create_and_run", frozenset({ContractCheck.IDLE_MINUTES}), True),
+ ("without_run_in_log_mode", "create_without_run", frozenset(), True),
+ ("without_run_with_the_check_enforced", "create_without_run", frozenset({ContractCheck.RUNTIMES}), False),
+ (
+ "without_run_with_another_check_enforced",
+ "create_without_run",
+ frozenset({ContractCheck.SANDBOX_TEMPLATES}),
+ True,
+ ),
+ ]
+ )
+ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
+ def test_task_creation_checks_run_options_against_the_profile(
+ self, name: str, entry: str, enforced: frozenset[ContractCheck], created: bool, _mock_execute_workflow
+ ) -> None:
+ user = User.objects.create(email=f"{name}@test.com")
+ profile = replace(BUSINESS_KNOWLEDGE, key="test.checked", enforced_checks=enforced)
+
+ with patch.dict("products.tasks.backend.facade.profiles._profiles", {profile.key: profile}):
+ create = partial(
+ getattr(Task, entry),
+ team=self.team,
+ title="t",
+ description="d",
+ profile=profile,
+ user_id=user.id,
+ options=TaskRunOptions(runtime="pi"),
+ )
+ if created:
+ self.assertEqual(create().runtime, "pi")
+ else:
+ with self.assertRaises(TaskRunOptionsError):
+ create()
+
+ self.assertEqual(Task.objects.filter(team=self.team).exists(), created)
+
@parameterized.expand([("caller_passes_the_key", "support"), ("caller_passes_none", None)])
@patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
def test_create_and_run_takes_the_agent_key_from_the_profile(
diff --git a/products/tasks/backend/tests/test_profile_parity.py b/products/tasks/backend/tests/test_profile_parity.py
index 9b78217bd702..b0ac14ea5cc3 100644
--- a/products/tasks/backend/tests/test_profile_parity.py
+++ b/products/tasks/backend/tests/test_profile_parity.py
@@ -8,6 +8,7 @@ from parameterized import parameterized
from products.tasks.backend.facade.profiles import (
DrivePolicy,
+ GithubAccess,
GithubResolution,
Read,
TaskProfile,
@@ -155,6 +156,14 @@ class TestTaskProfilesMatchMaster(SimpleTestCase):
master = Task._github_resolution_allowed(profile.origin_product, has_repository=has_repository)
self.assertEqual(attaches_github, master)
+ @parameterized.expand(PROFILES)
+ def test_github_access_matches_master(self, _key: str, profile: TaskProfile) -> None:
+ attaches_github = any(
+ Task._github_resolution_allowed(profile.origin_product, has_repository=has_repository)
+ for has_repository in (True, False)
+ )
+ self.assertEqual(profile.github_access, GithubAccess.WRITE if attaches_github else GithubAccess.NONE)
+
@parameterized.expand(PROFILES)
def test_user_authorable_prs_matches_master(self, _key: str, profile: TaskProfile) -> None:
self.assertEqual(profile.user_authorable_prs, profile.origin_product in USER_AUTHORABLE_ORIGIN_PRODUCTS)
diff --git a/products/tasks/backend/tests/test_profiles.py b/products/tasks/backend/tests/test_profiles.py
index 431ddf90386e..060169bfd3f8 100644
--- a/products/tasks/backend/tests/test_profiles.py
+++ b/products/tasks/backend/tests/test_profiles.py
@@ -1,11 +1,15 @@
from contextlib import nullcontext
from dataclasses import replace
+from unittest.mock import patch
+
from django.test import SimpleTestCase
from parameterized import parameterized
from products.tasks.backend.facade.profiles import (
+ GithubAccess,
+ GithubResolution,
Read,
SourceKind,
TaskProfile,
@@ -38,6 +42,33 @@ class TestTaskProfileRegistry(SimpleTestCase):
with self.assertRaises(TaskProfileError):
register_task_profile(conflicting)
+ @parameterized.expand(
+ [
+ ("always_with_write", GithubResolution.ALWAYS, GithubAccess.WRITE, False),
+ ("always_with_read", GithubResolution.ALWAYS, GithubAccess.READ, False),
+ ("with_repository_with_write", GithubResolution.WITH_REPOSITORY, GithubAccess.WRITE, False),
+ ("never_with_none", GithubResolution.NEVER, GithubAccess.NONE, False),
+ ("always_with_none", GithubResolution.ALWAYS, GithubAccess.NONE, True),
+ ("with_repository_with_none", GithubResolution.WITH_REPOSITORY, GithubAccess.NONE, True),
+ ("never_with_read", GithubResolution.NEVER, GithubAccess.READ, True),
+ ("never_with_write", GithubResolution.NEVER, GithubAccess.WRITE, True),
+ ]
+ )
+ def test_register_requires_github_access_to_agree_with_github_resolution(
+ self, _name: str, resolution: GithubResolution, access: GithubAccess, refused: bool
+ ) -> None:
+ candidate = replace(
+ BUSINESS_KNOWLEDGE, key="test.github_pair", github_resolution=resolution, github_access=access
+ )
+
+ with (
+ patch.dict("products.tasks.backend.facade.profiles._profiles"),
+ self.assertRaises(TaskProfileError) if refused else nullcontext(),
+ ):
+ register_task_profile(candidate)
+
+ self.assertEqual(get_task_profile("test.github_pair"), candidate)
+
@parameterized.expand(
[
("profile_only", BUSINESS_KNOWLEDGE, None, None, ("business_knowledge", True, "business_knowledge")),