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(integration): New Integration classes for Redshift (#76745)

Tomás Farías Santanaf1f82a47ccfd
diff --git a/posthog/api/integration.py b/posthog/api/integration.py
index b545a2096e5b..0fe7d7b5eb47 100644
--- a/posthog/api/integration.py
+++ b/posthog/api/integration.py
@@ -60,8 +60,10 @@ from posthog.models.integration import (
SLACK_INTEGRATION_KINDS,
AnthropicIntegration,
ApplePushIntegration,
- AwsS3Integration,
- AwsS3RoleBasedIntegration,
+ AWSRedshiftIntegration,
+ AWSRedshiftRoleBasedIntegration,
+ AWSS3Integration,
+ AWSS3RoleBasedIntegration,
AzureBlobIntegration,
AzureBlobIntegrationError,
ClickUpIntegration,
@@ -76,13 +78,14 @@ from posthog.models.integration import (
GoogleCloudIntegration,
GoogleCloudServiceAccountIntegration,
Integration,
+ IntegrationError,
JiraIntegration,
LinearIntegration,
LinkedInAdsIntegration,
OauthIntegration,
PostgreSQLIntegration,
+ RedshiftIntegration,
S3CompatibleIntegration,
- S3CredentialIntegrationError,
SlackIntegration,
SnowflakeIntegration,
SnowflakeIntegrationError,
@@ -742,101 +745,91 @@ class IntegrationSerializer(serializers.ModelSerializer, UserAccessControlSerial
elif validated_data["kind"] == "aws-s3":
config = validated_data.get("config", {})
+ for key in ("team_id", "created_by", "organization_id"):
+ _ = config.pop(key, None)
+
+ get_organization = self.context.get("get_organization")
+ if get_organization is None:
+ raise ValidationError("Organization context is missing")
+ organization_id = str(get_organization().id)
+
+ s3_integration = AWSS3RoleBasedIntegration if "aws_role_arn" in config else AWSS3Integration
+
+ try:
+ instance = s3_integration.integration_from_config(
+ team_id=team_id,
+ created_by=request.user,
+ organization_id=organization_id,
+ **config,
+ )
+ except IntegrationError as e:
+ raise ValidationError(str(e))
+ return instance
+
+ elif validated_data["kind"] == "aws-redshift":
+ config = validated_data.get("config", {})
+
+ for key in ("team_id", "created_by", "organization_id"):
+ _ = config.pop(key, None)
+
get_organization = self.context.get("get_organization")
if get_organization is None:
raise ValidationError("Organization context is missing")
organization_id = str(get_organization().id)
- integration = AwsS3RoleBasedIntegration if "aws_role_arn" in config else AwsS3Integration
+ if "aws_role_arn" in config:
+ redshift_integration: (
+ type[RedshiftIntegration] | type[AWSRedshiftIntegration] | type[AWSRedshiftRoleBasedIntegration]
+ ) = AWSRedshiftRoleBasedIntegration
+ elif any(required in config for required in ("host", "port", "user", "password")):
+ redshift_integration = RedshiftIntegration
+ elif any(required in config for required in ("aws_access_key_id", "aws_secret_access_key")):
+ redshift_integration = AWSRedshiftIntegration
+ else:
+ raise ValidationError("Missing required inputs")
try:
- instance = integration.integration_from_config(
+ instance = redshift_integration.integration_from_config(
team_id=team_id,
created_by=request.user,
organization_id=organization_id,
**config,
)
- except S3CredentialIntegrationError as e:
+ except IntegrationError as e:
raise ValidationError(str(e))
return instance
elif validated_data["kind"] == "s3-compatible":
config = validated_data.get("config", {})
- name = config.get("name")
- endpoint_url = config.get("endpoint_url")
- aws_access_key_id = config.get("aws_access_key_id")
- aws_secret_access_key = config.get("aws_secret_access_key")
-
- if not (name and endpoint_url and aws_access_key_id and aws_secret_access_key):
- raise ValidationError("Name, endpoint URL, access key ID, and secret access key must be provided")
- if not all(
- isinstance(value, str) for value in (name, endpoint_url, aws_access_key_id, aws_secret_access_key)
- ):
- raise ValidationError("Name, endpoint URL, access key ID, and secret access key must be strings")
+
+ for key in ("team_id", "created_by"):
+ _ = config.pop(key, None)
try:
# SSRF validation of `endpoint_url` happens inside `integration_from_config`.
instance = S3CompatibleIntegration.integration_from_config(
team_id=team_id,
- name=name,
- endpoint_url=endpoint_url,
- aws_access_key_id=aws_access_key_id,
- aws_secret_access_key=aws_secret_access_key,
created_by=request.user,
+ **config,
)
- except S3CredentialIntegrationError as e:
+ except IntegrationError as e:
raise ValidationError(str(e))
return instance
elif validated_data["kind"] == "postgresql":
config = validated_data.get("config", {})
- host = config.get("host")
- port = config.get("port", 5432)
- user = config.get("user")
- password = config.get("password")
- ssl_mode = config.get("ssl_mode", "require")
- ssl_root_cert = config.get("ssl_root_cert")
-
- if not (host and port and user and password):
- raise ValidationError("Host, port, user, and password must be provided")
-
- if not all(isinstance(value, str) for value in (host, user, password)):
- raise ValidationError("Host, user, and password must be strings")
- from products.batch_exports.backend.api.batch_export import resolve_and_validate_host
+ for key in ("team_id", "created_by", "organization_id"):
+ _ = config.pop(key, None)
try:
- resolve_and_validate_host(host)
- except ValueError:
- raise ValidationError(f"Invalid host: '{host}'")
-
- try:
- port = int(port)
- except (TypeError, ValueError):
- raise ValidationError("Port must be an integer")
-
- if port < 0 or port > 65535:
- raise ValidationError("Port must be between 0 and 65535")
-
- if ssl_mode not in ("require", "verify-ca", "verify-full"):
- raise ValidationError("SSL mode must be one of: require, verify-ca, verify-full")
-
- if ssl_mode in ("verify-ca", "verify-full"):
- if not ssl_root_cert:
- raise ValidationError("Root certificate must be provided when verifying server certificates")
- if not isinstance(ssl_root_cert, str):
- raise ValidationError("Root certificate must be a string")
-
- instance = PostgreSQLIntegration.integration_from_config(
- team_id=team_id,
- host=host,
- port=port,
- user=user,
- password=password,
- ssl_mode=ssl_mode,
- ssl_root_cert=ssl_root_cert,
- created_by=request.user,
- )
+ instance = PostgreSQLIntegration.integration_from_config(
+ team_id=team_id,
+ created_by=request.user,
+ **config,
+ )
+ except IntegrationError as e:
+ raise ValidationError(str(e))
return instance
elif validated_data["kind"] in OauthIntegration.supported_kinds:
diff --git a/posthog/api/test/test_integration.py b/posthog/api/test/test_integration.py
index 77522a821a9a..edae306c55b0 100644
--- a/posthog/api/test/test_integration.py
+++ b/posthog/api/test/test_integration.py
@@ -613,23 +613,34 @@ class TestDatabricksIntegration:
assert not Integration.objects.filter(team=self.team, kind="databricks").exists()
-class TestAwsS3Integration:
+class TestAWSIntegration:
+ @pytest.fixture(
+ params=[
+ (Integration.IntegrationKind.AWS_S3),
+ (Integration.IntegrationKind.AWS_REDSHIFT),
+ ],
+ ids=lambda kind: kind.value,
+ )
+ def aws_integration_kind(self, request):
+ return request.param
+
@pytest.fixture(autouse=True)
- def setup_integration(self, db):
+ def setup_integration(self, db, aws_integration_kind):
self.organization = Organization.objects.create(name="Test Org")
self.team = Team.objects.create(organization=self.organization, name="Test Team")
self.user = User.objects.create_and_join(
self.organization, "[email protected]", "test", level=OrganizationMembership.Level.ADMIN
)
+ self.integration_kind = aws_integration_kind
- @patch("posthog.models.integration.AwsS3Integration.validate_credentials", return_value="123456789012")
+ @patch("posthog.models.integration.validate_aws_credentials", return_value="123456789012")
def test_create_with_valid_config(self, mock_validate, client: HttpClient):
client.force_login(self.user)
response = client.post(
f"/api/environments/{self.team.pk}/integrations",
{
- "kind": "aws-s3",
+ "kind": self.integration_kind,
"config": {
"name": "prod-aws",
"aws_access_key_id": "AKIAEXAMPLE",
@@ -640,10 +651,10 @@ class TestAwsS3Integration:
)
assert response.status_code == status.HTTP_201_CREATED, response.json()
- assert response.json()["kind"] == "aws-s3"
+ assert response.json()["kind"] == self.integration_kind
integration = Integration.objects.get(id=response.json()["id"])
- assert integration.kind == "aws-s3"
+ assert integration.kind == self.integration_kind
assert integration.team == self.team
assert integration.integration_id == "prod-aws"
assert integration.config == {"name": "prod-aws", "aws_account_id": "123456789012"}
@@ -658,17 +669,17 @@ class TestAwsS3Integration:
assert "aws_secret_access_key" not in response_body
assert "AKIAEXAMPLE" not in response_body
- @patch("posthog.models.integration.AwsS3Integration.validate_credentials")
+ @patch("posthog.models.integration.validate_aws_credentials")
def test_create_rejects_invalid_credentials(self, mock_validate, client: HttpClient):
- from posthog.models.integration import S3CredentialIntegrationError
+ from posthog.models.integration import IntegrationError
- mock_validate.side_effect = S3CredentialIntegrationError("AWS credentials are not valid: nope")
+ mock_validate.side_effect = IntegrationError("AWS credentials are not valid: nope")
client.force_login(self.user)
response = client.post(
f"/api/environments/{self.team.pk}/integrations",
{
- "kind": "aws-s3",
+ "kind": self.integration_kind,
"config": {
"name": "prod-aws",
"aws_access_key_id": "AKIAEXAMPLE",
@@ -681,11 +692,11 @@ class TestAwsS3Integration:
assert response.status_code == status.HTTP_400_BAD_REQUEST
assert "AWS credentials are not valid" in response.json()["detail"]
- @patch("posthog.models.integration.AwsS3Integration.validate_credentials", return_value="123456789012")
+ @patch("posthog.models.integration.validate_aws_credentials", return_value="123456789012")
def test_create_rejects_duplicate_name(self, mock_validate, client: HttpClient):
client.force_login(self.user)
payload = {
- "kind": "aws-s3",
+ "kind": self.integration_kind,
"config": {"name": "prod-aws", "aws_access_key_id": "AKIAEXAMPLE", "aws_secret_access_key": "secret"},
}
@@ -702,20 +713,20 @@ class TestAwsS3Integration:
[
(
{"aws_access_key_id": "k", "aws_secret_access_key": "s"},
- "A name is required for an AWS S3 integration",
+ "A name is required for AWS integration",
),
(
{"name": "n", "aws_secret_access_key": "s"},
- "Access key ID is required for an AWS S3 integration",
+ "Access key ID is required for AWS integration",
),
(
{"name": "n", "aws_access_key_id": "k"},
- "Secret access key is required for an AWS S3 integration",
+ "Secret access key is required for AWS integration",
),
- ({}, "A name is required for an AWS S3 integration"),
+ ({}, "A name is required for AWS integration"),
(
{"name": "n", "aws_access_key_id": "k", "aws_secret_access_key": 1},
- "Secret access key is required for an AWS S3 integration",
+ "Secret access key is required for AWS integration",
),
],
)
@@ -724,23 +735,39 @@ class TestAwsS3Integration:
response = client.post(
f"/api/environments/{self.team.pk}/integrations",
- {"kind": "aws-s3", "config": invalid_config},
+ {"kind": self.integration_kind, "config": invalid_config},
content_type="application/json",
)
assert response.status_code == status.HTTP_400_BAD_REQUEST
- assert response.json()["detail"] == expected_error_message
+ assert (
+ response.json()["detail"] == expected_error_message
+ # Default Redshift error message on {}
+ or response.json()["detail"] == "Missing required inputs"
+ )
+
+class TestAWSRoleBasedIntegration:
+ @pytest.fixture(
+ params=[
+ (Integration.IntegrationKind.AWS_S3),
+ (Integration.IntegrationKind.AWS_REDSHIFT),
+ ],
+ ids=lambda kind: kind.value,
+ )
+ def aws_integration_kind(self, request):
+ return request.param
-class TestAwsS3RoleBasedIntegration:
@pytest.fixture(autouse=True)
- def setup_integration(self, db):
+ def setup_integration(self, db, aws_integration_kind):
self.organization = Organization.objects.create(name="Test Org")
self.team = Team.objects.create(organization=self.organization, name="Test Team")
self.user = User.objects.create_and_join(
self.organization, "[email protected]", "test", level=OrganizationMembership.Level.ADMIN
)
+ self.integration_kind = aws_integration_kind
+
def test_create_with_valid_config(self, client: HttpClient):
client.force_login(self.user)
@@ -748,7 +775,7 @@ class TestAwsS3RoleBasedIntegration:
response = client.post(
f"/api/environments/{self.team.pk}/integrations",
{
- "kind": "aws-s3",
+ "kind": self.integration_kind,
"config": {
"name": "prod-aws",
"aws_role_arn": role,
@@ -758,10 +785,10 @@ class TestAwsS3RoleBasedIntegration:
)
assert response.status_code == status.HTTP_201_CREATED, response.json()
- assert response.json()["kind"] == "aws-s3"
+ assert response.json()["kind"] == self.integration_kind
integration = Integration.objects.get(id=response.json()["id"])
- assert integration.kind == "aws-s3"
+ assert integration.kind == self.integration_kind
assert integration.team == self.team
assert integration.integration_id == "prod-aws"
assert integration.config == {"name": "prod-aws", "aws_role_arn": role}
@@ -775,7 +802,7 @@ class TestAwsS3RoleBasedIntegration:
)
client.force_login(another_user)
payload = {
- "kind": "aws-s3",
+ "kind": self.integration_kind,
"config": {"name": "prod-aws", "aws_role_arn": "something"},
}
@@ -787,12 +814,12 @@ class TestAwsS3RoleBasedIntegration:
client.force_login(self.user)
second = client.post(f"/api/environments/{self.team.pk}/integrations", payload, content_type="application/json")
assert second.status_code == status.HTTP_400_BAD_REQUEST
- assert "Cannot create AWS S3 integration: Invalid role" in second.json()["detail"]
+ assert "Cannot create AWS integration: Invalid role" in second.json()["detail"]
def test_create_rejects_duplicate_name(self, client: HttpClient):
client.force_login(self.user)
payload = {
- "kind": "aws-s3",
+ "kind": self.integration_kind,
"config": {"name": "prod-aws", "aws_role_arn": "something"},
}
@@ -891,13 +918,13 @@ class TestS3CompatibleIntegration:
[
(
{"endpoint_url": "https://e.com", "aws_access_key_id": "k", "aws_secret_access_key": "s"},
- "Name, endpoint URL, access key ID, and secret access key must be provided",
+ "A name is required for S3-compatible integration",
),
(
{"name": "n", "aws_access_key_id": "k", "aws_secret_access_key": "s"},
- "Name, endpoint URL, access key ID, and secret access key must be provided",
+ "Endpoint URL is required for S3-compatible integration",
),
- ({}, "Name, endpoint URL, access key ID, and secret access key must be provided"),
+ ({}, "A name is required for S3-compatible integration"),
],
)
def test_create_with_invalid_config(self, invalid_config, expected_error_message, client: HttpClient):
@@ -5618,7 +5645,7 @@ class TestIntegrationMembershipPermissions(APIBaseTest):
self.organization_membership.level = OrganizationMembership.Level.MEMBER
self.organization_membership.save()
- @patch("posthog.models.integration.AwsS3Integration.validate_credentials", return_value="123456789012")
+ @patch("posthog.models.integration.validate_aws_credentials", return_value="123456789012")
def test_member_can_create_integration(self, _mock_validate):
response = self.client.post(
f"/api/environments/{self.team.pk}/integrations",
diff --git a/posthog/models/integration.py b/posthog/models/integration.py
index 60a0c520ecc4..989c61937c94 100644
--- a/posthog/models/integration.py
+++ b/posthog/models/integration.py
@@ -8,7 +8,7 @@ import secrets
from collections.abc import Iterable, Mapping
from dataclasses import dataclass
from datetime import datetime, timedelta
-from typing import TYPE_CHECKING, Any, Literal, NamedTuple, NoReturn, Optional, Self, cast
+from typing import TYPE_CHECKING, Any, ClassVar, Literal, NamedTuple, NoReturn, Optional, Self, cast
from urllib.parse import parse_qs, urlencode, urlparse
from posthog.dataclasses import frozen
@@ -665,6 +665,24 @@ class Integration(models.Model):
else:
detail = "access key"
+ return f"{name} ({detail})"
+ if self.kind == Integration.IntegrationKind.AWS_REDSHIFT:
+ name = self.integration_id or "unknown ID"
+
+ account_id = self.config.get("aws_account_id")
+ role = self.config.get("aws_role_arn")
+ host = self.config.get("host")
+ user = self.config.get("user")
+
+ if role:
+ detail = f"AWS role '{role}'"
+ elif account_id:
+ detail = f"AWS account {account_id}"
+ elif user and host:
+ detail = f"{user}@{host}"
+ else:
+ detail = "access key"
+
return f"{name} ({detail})"
if self.kind == Integration.IntegrationKind.S3_COMPATIBLE:
name = self.integration_id or "unknown ID"
@@ -4521,43 +4539,67 @@ class AzureBlobIntegration:
return None
-class S3CredentialIntegrationError(Exception):
- """Error raised when an S3-family credential integration is not valid."""
+class IntegrationError(Exception):
+ """Error raised when an integration or its inputs are not valid."""
pass
-def _read_s3_credentials(integration: Integration) -> AWSKeyPair:
+_AWSKindType = Literal[Integration.IntegrationKind.AWS_REDSHIFT, Integration.IntegrationKind.AWS_S3]
+
+
+def _read_aws_credentials(integration: Integration) -> AWSKeyPair:
try:
+ # SAFETY: Safety is delegated to the integration which must guarantee
+ # sensitive_config keys are correctly assigned.
return AWSKeyPair.unsafe_from_strings(
integration.sensitive_config["aws_access_key_id"], integration.sensitive_config["aws_secret_access_key"]
)
except KeyError as e:
- raise S3CredentialIntegrationError(f"S3 integration is not valid: {str(e)} missing")
+ raise IntegrationError(f"Integration is not valid: {str(e)} missing")
-def _build_s3_sensitive_config(aws_access_key_id: str, aws_secret_access_key: str) -> dict[str, str]:
- return {
- "aws_access_key_id": aws_access_key_id,
- "aws_secret_access_key": aws_secret_access_key,
- }
+def _create_unique_aws_integration(
+ *,
+ team_id: int,
+ kind: _AWSKindType,
+ name: str,
+ account_id: str,
+ credentials: AWSKeyPair,
+ created_by: "User | None",
+) -> Integration:
+ """Create an AWS integration from credentials and an account."""
+ return _create_unique_named_integration(
+ team_id=team_id,
+ kind=kind,
+ name=name,
+ config={"name": name, "aws_account_id": account_id},
+ sensitive_config={
+ "aws_access_key_id": credentials.access_key_id,
+ "aws_secret_access_key": credentials.secret_access_key,
+ },
+ created_by=created_by,
+ )
+
+
+class DuplicateNameError(IntegrationError):
+ pass
-def _create_unique_s3_integration(
+def _create_unique_named_integration(
*,
team_id: int,
kind: str,
name: str,
- config: dict[str, Any],
+ config: dict[str, str],
sensitive_config: dict[str, str],
created_by: "User | None",
) -> Integration:
- """Create an S3-family integration, rejecting a name already taken for this team and kind.
+ """Create an integration, rejecting a name already taken for this team and kind.
Unlike most integrations, `name` is a free-form user-supplied identifier rather than one derived
from the external connection (an OAuth account id, service-account email, etc.). So we create
- rather than upsert — re-using a name is a 400, not a silent overwrite of an unrelated credential
- set.
+ rather than upsert and raise a 400 error, on conflicts.
"""
try:
# Savepoint so the unique-constraint IntegrityError aborts only this INSERT, not the
@@ -4572,7 +4614,7 @@ def _create_unique_s3_integration(
created_by=created_by,
)
except IntegrityError:
- raise S3CredentialIntegrationError(f"An integration named '{name}' already exists")
+ raise DuplicateNameError(f"An integration named '{name}' already exists")
def is_unique_aws_role_by_organization_id(aws_role_arn: str, organization_id: str) -> bool:
@@ -4589,7 +4631,7 @@ def is_unique_aws_role_by_organization_id(aws_role_arn: str, organization_id: st
has_same_aws_role_integrations = (
Integration.objects.select_related("team__organization")
.filter(
- kind=Integration.IntegrationKind.AWS_S3,
+ kind__in=(Integration.IntegrationKind.AWS_S3, Integration.IntegrationKind.AWS_REDSHIFT),
config__aws_role_arn=aws_role_arn,
)
.exclude(team__organization_id=organization_id)
@@ -4601,28 +4643,72 @@ def is_unique_aws_role_by_organization_id(aws_role_arn: str, organization_id: st
return True
-def _return_non_empty_str_from_config(config: Mapping, key: str) -> str | None:
+def _return_non_empty_str_from_config(
+ config: Mapping,
+ key: str,
+ friendly_name: str,
+ kind: str,
+) -> str:
if (value := config.get(key)) is not None and isinstance(value, str) and len(value) > 0:
return value
- return None
+ raise IntegrationError(f"{friendly_name} is required for {kind} integration")
-class AwsS3RoleBasedIntegration:
- """An AWS S3 integration storing a customer's AWS role."""
+def _return_non_empty_str_from_config_for_aws(config: Mapping, key: str, friendly_name: str) -> str:
+ return _return_non_empty_str_from_config(config, key, friendly_name=friendly_name, kind="AWS")
+
+
+def validate_aws_credentials(aws_access_key_id: str, aws_secret_access_key: str) -> str:
+ """Validate AWS credentials via STS GetCallerIdentity, returning the AWS account id.
+
+ GetCallerIdentity requires no IAM permissions, so it verifies the credentials are valid
+ without assuming any particular S3 policy. It hits the fixed global AWS STS endpoint, so
+ there is no user-controlled endpoint and no SSRF surface (unlike S3-compatible).
+
+ This runs synchronously on the request thread, so the timeout budget is kept tight:
+ a single attempt (no retry) bounds the worst case at ~10s (connect + read) if STS is
+ unreachable, rather than blocking the worker while botocore retries.
+ """
+ import boto3 # noqa: PLC0415 — keeps botocore off the module import path (startup time)
+ from botocore.config import Config # noqa: PLC0415
+ from botocore.exceptions import BotoCoreError, ClientError # noqa: PLC0415
+
+ client = boto3.client(
+ "sts",
+ aws_access_key_id=aws_access_key_id,
+ aws_secret_access_key=aws_secret_access_key,
+ config=Config(connect_timeout=5, read_timeout=5, retries={"max_attempts": 1}),
+ )
+ try:
+ identity = client.get_caller_identity()
+ except ClientError as e:
+ message = e.response.get("Error", {}).get("Message") or str(e)
+ raise IntegrationError(f"AWS credentials are not valid: {message}")
+ except BotoCoreError as e:
+ raise IntegrationError(f"Could not validate AWS credentials: {e}")
+
+ return identity["Account"]
+
+
+class AWSRoleBasedIntegration:
+ """An AWS integration storing a customer's AWS role."""
integration: Integration
aws_role_arn: str
+ integration_kind: ClassVar[_AWSKindType]
+
def __init__(self, integration: Integration) -> None:
- if integration.kind != Integration.IntegrationKind.AWS_S3:
- raise S3CredentialIntegrationError(
- f"Integration provided is not an AWS S3 integration (got kind='{integration.kind}')"
+ if integration.kind != self.integration_kind:
+ raise IntegrationError(
+ "Integration provided is not the expected AWS integration "
+ f"(got kind='{integration.kind}', expected kind='{self.integration_kind}')"
)
self.integration = integration
try:
self.aws_role_arn = integration.config["aws_role_arn"]
except KeyError:
- raise S3CredentialIntegrationError("S3 integration is not valid: 'aws_role_arn' missing")
+ raise IntegrationError("AWS integration is not valid: 'aws_role_arn' missing")
@classmethod
def integration_from_config(
@@ -4632,20 +4718,15 @@ class AwsS3RoleBasedIntegration:
created_by: "User | None" = None,
**config,
) -> Integration:
- name = _return_non_empty_str_from_config(config, "name")
- if not name:
- raise S3CredentialIntegrationError("A name is required for an AWS S3 integration")
-
- aws_role_arn = _return_non_empty_str_from_config(config, "aws_role_arn")
- if not aws_role_arn:
- raise S3CredentialIntegrationError("A valid role ARN is required for an AWS S3 integration")
+ name = _return_non_empty_str_from_config_for_aws(config, "name", "A name")
+ aws_role_arn = _return_non_empty_str_from_config_for_aws(config, "aws_role_arn", "A valid role ARN")
if not is_unique_aws_role_by_organization_id(aws_role_arn, organization_id):
- raise ValidationError("Cannot create AWS S3 integration: Invalid role")
+ raise ValidationError("Cannot create AWS integration: Invalid role")
- return _create_unique_s3_integration(
+ return _create_unique_named_integration(
team_id=team_id,
- kind=Integration.IntegrationKind.AWS_S3,
+ kind=cls.integration_kind,
name=name,
config={"name": name, "aws_role_arn": aws_role_arn},
sensitive_config={},
@@ -4653,67 +4734,53 @@ class AwsS3RoleBasedIntegration:
)
-class AwsS3Integration:
- """An AWS S3 integration storing reusable AWS credentials.
+class AWSS3RoleBasedIntegration(AWSRoleBasedIntegration):
+ """An AWS S3 integration storing a customer's AWS role."""
+
+ integration_kind: ClassVar[Literal[Integration.IntegrationKind.AWS_S3]] = Integration.IntegrationKind.AWS_S3
+
+
+class AWSRedshiftRoleBasedIntegration(AWSRoleBasedIntegration):
+ """An AWS Redshift integration storing a customer's AWS role."""
+
+ integration_kind: ClassVar[Literal[Integration.IntegrationKind.AWS_REDSHIFT]] = (
+ Integration.IntegrationKind.AWS_REDSHIFT
+ )
- Holds only credentials; bucket, region, prefix and other export-specific settings stay on the
- batch export destination config, so one credential can be reused across many buckets/regions —
- and, in future, by Redshift COPY-mode exports that stage to S3.
- Unlike `S3CompatibleIntegration` it has no `endpoint_url` — an AWS
+class AWSCredentialsIntegration:
+ """AWS integration for any service that requires storing long-lived AWS credentials.
+
+ Unlike `S3CompatibleIntegration` it has no `endpoint_url` because an AWS
integration must never be pointed at an arbitrary endpoint (SSRF boundary).
"""
integration: Integration
- aws_access_key_id: str
- aws_secret_access_key: str
+ credentials: AWSKeyPair
+
+ integration_kind: ClassVar[_AWSKindType]
def __init__(self, integration: Integration) -> None:
- if integration.kind != Integration.IntegrationKind.AWS_S3:
- raise S3CredentialIntegrationError(
- f"Integration provided is not an AWS S3 integration (got kind='{integration.kind}')"
+ if integration.kind != self.integration_kind:
+ raise IntegrationError(
+ "Integration provided is not the expected AWS integration "
+ f"(got kind='{integration.kind}', expected kind='{self.integration_kind}')"
)
self.integration = integration
- credentials = _read_s3_credentials(integration)
- self.aws_access_key_id = credentials.access_key_id
- self.aws_secret_access_key = credentials.secret_access_key
+ self.credentials = _read_aws_credentials(integration)
@property
def aws_account_id(self) -> str | None:
"""The AWS account id resolved from the credentials at create time, if available."""
return self.integration.config.get("aws_account_id")
- @staticmethod
- def validate_credentials(aws_access_key_id: str, aws_secret_access_key: str) -> str:
- """Validate AWS credentials via STS GetCallerIdentity, returning the AWS account id.
-
- GetCallerIdentity requires no IAM permissions, so it verifies the credentials are valid
- without assuming any particular S3 policy. It hits the fixed global AWS STS endpoint, so
- there is no user-controlled endpoint and no SSRF surface (unlike S3-compatible).
-
- This runs synchronously on the request thread, so the timeout budget is kept tight:
- a single attempt (no retry) bounds the worst case at ~10s (connect + read) if STS is
- unreachable, rather than blocking the worker while botocore retries.
- """
- import boto3 # noqa: PLC0415 — keeps botocore off the module import path (startup time)
- from botocore.config import Config # noqa: PLC0415
- from botocore.exceptions import BotoCoreError, ClientError # noqa: PLC0415
-
- client = boto3.client(
- "sts",
- aws_access_key_id=aws_access_key_id,
- aws_secret_access_key=aws_secret_access_key,
- config=Config(connect_timeout=5, read_timeout=5, retries={"max_attempts": 1}),
- )
- try:
- identity = client.get_caller_identity()
- except ClientError as e:
- message = e.response.get("Error", {}).get("Message") or str(e)
- raise S3CredentialIntegrationError(f"AWS credentials are not valid: {message}")
- except BotoCoreError as e:
- raise S3CredentialIntegrationError(f"Could not validate AWS credentials: {e}")
+ @property
+ def aws_access_key_id(self) -> str:
+ return self.credentials.access_key_id
- return identity["Account"]
+ @property
+ def aws_secret_access_key(self) -> str:
+ return self.credentials.secret_access_key
@classmethod
def integration_from_config(
@@ -4722,33 +4789,58 @@ class AwsS3Integration:
created_by: "User | None" = None,
**config,
) -> Integration:
- name = _return_non_empty_str_from_config(config, "name")
- if not name:
- raise S3CredentialIntegrationError("A name is required for an AWS S3 integration")
-
- aws_access_key_id = _return_non_empty_str_from_config(config, "aws_access_key_id")
- if not aws_access_key_id:
- raise S3CredentialIntegrationError("Access key ID is required for an AWS S3 integration")
-
- aws_secret_access_key = _return_non_empty_str_from_config(config, "aws_secret_access_key")
- if not aws_secret_access_key:
- raise S3CredentialIntegrationError("Secret access key is required for an AWS S3 integration")
+ name = _return_non_empty_str_from_config_for_aws(config, "name", "A name")
+ aws_access_key_id = _return_non_empty_str_from_config_for_aws(
+ config,
+ "aws_access_key_id",
+ "Access key ID",
+ )
+ aws_secret_access_key = _return_non_empty_str_from_config_for_aws(
+ config, "aws_secret_access_key", "Secret access key"
+ )
# Fail fast on invalid/expired credentials, and capture the (non-sensitive) account id.
- account_id = cls.validate_credentials(aws_access_key_id, aws_secret_access_key)
+ account_id = validate_aws_credentials(aws_access_key_id, aws_secret_access_key)
+
+ # SAFETY: We check that each value is non-empty and str type, and, by
+ # validating the credentials directly with AWS, we ensure each of these
+ # values is what they say they are. This call is safe.
+ credentials = AWSKeyPair.unsafe_from_strings(aws_access_key_id, aws_secret_access_key)
# `name` is the unencrypted, frontend-visible identifier — never an AWS credential, which is
# treated as a secret. The account id is non-sensitive and kept for display/debugging.
- return _create_unique_s3_integration(
+ return _create_unique_aws_integration(
team_id=team_id,
- kind=Integration.IntegrationKind.AWS_S3,
+ kind=cls.integration_kind,
name=name,
- config={"name": name, "aws_account_id": account_id},
- sensitive_config=_build_s3_sensitive_config(aws_access_key_id, aws_secret_access_key),
+ account_id=account_id,
+ credentials=credentials,
created_by=created_by,
)
+class AWSS3Integration(AWSCredentialsIntegration):
+ """An AWS S3 integration storing reusable AWS credentials.
+
+ Holds only credentials; bucket, region, prefix and other export-specific settings stay on the
+ batch export destination config, so one credential can be reused across many buckets/regions.
+ """
+
+ integration_kind: ClassVar[Literal[Integration.IntegrationKind.AWS_S3]] = Integration.IntegrationKind.AWS_S3
+
+
+class AWSRedshiftIntegration(AWSCredentialsIntegration):
+ """An AWS Redshift integration storing reusable AWS credentials."""
+
+ integration_kind: ClassVar[Literal[Integration.IntegrationKind.AWS_REDSHIFT]] = (
+ Integration.IntegrationKind.AWS_REDSHIFT
+ )
+
+
+def _return_non_empty_str_from_config_for_s3_compatible(config: Mapping, key: str, friendly_name: str) -> str:
+ return _return_non_empty_str_from_config(config, key, friendly_name=friendly_name, kind="S3-compatible")
+
+
class S3CompatibleIntegration:
"""An S3-compatible storage integration (Cloudflare R2, DigitalOcean Spaces, Hetzner, etc.).
@@ -4761,54 +4853,63 @@ class S3CompatibleIntegration:
"""
integration: Integration
- # The `aws_` prefix applies even to these non-AWS providers: they are AWS Signature V4
- # credentials, which every S3-compatible provider (R2, MinIO, Spaces, ...) uses. The names also
- # match boto3's kwargs and the existing S3-family batch export config fields, so they pass
- # through unchanged.
- aws_access_key_id: str
- aws_secret_access_key: str
+ credentials: AWSKeyPair
endpoint_url: str
def __init__(self, integration: Integration) -> None:
if integration.kind != Integration.IntegrationKind.S3_COMPATIBLE:
- raise S3CredentialIntegrationError(
+ raise IntegrationError(
f"Integration provided is not an S3-compatible integration (got kind='{integration.kind}')"
)
self.integration = integration
- credentials = _read_s3_credentials(integration)
- self.aws_access_key_id = credentials.access_key_id
- self.aws_secret_access_key = credentials.secret_access_key
+ self.credentials = _read_aws_credentials(integration)
try:
self.endpoint_url = integration.config["endpoint_url"]
except KeyError:
- raise S3CredentialIntegrationError("S3-compatible integration is missing required field: 'endpoint_url'")
+ raise IntegrationError("S3-compatible integration is missing required field: 'endpoint_url'")
+
+ @property
+ def aws_access_key_id(self) -> str:
+ return self.credentials.access_key_id
+
+ @property
+ def aws_secret_access_key(self) -> str:
+ return self.credentials.secret_access_key
@classmethod
def integration_from_config(
cls,
team_id: int,
- name: str,
- endpoint_url: str,
- aws_access_key_id: str,
- aws_secret_access_key: str,
created_by: "User | None" = None,
+ **config,
) -> Integration:
- if not name:
- raise S3CredentialIntegrationError("A name is required for an S3-compatible integration")
- if not endpoint_url:
- raise S3CredentialIntegrationError("An endpoint URL is required for an S3-compatible integration")
+ name = _return_non_empty_str_from_config_for_s3_compatible(
+ config,
+ "name",
+ friendly_name="A name",
+ )
+ aws_access_key_id = _return_non_empty_str_from_config_for_s3_compatible(
+ config, "aws_access_key_id", "Access key ID"
+ )
+ aws_secret_access_key = _return_non_empty_str_from_config_for_s3_compatible(
+ config, "aws_secret_access_key", "Secret access key"
+ )
+ endpoint_url = _return_non_empty_str_from_config_for_s3_compatible(config, "endpoint_url", "Endpoint URL")
# SSRF protection — credentials must not be testable against an attacker-controlled endpoint.
allowed, error = is_url_allowed(endpoint_url)
if not allowed:
- raise S3CredentialIntegrationError(f"Invalid endpoint URL: {error}")
+ raise IntegrationError(f"Invalid endpoint URL: {error}")
- return _create_unique_s3_integration(
+ return _create_unique_named_integration(
team_id=team_id,
kind=Integration.IntegrationKind.S3_COMPATIBLE,
name=name,
config={"name": name, "endpoint_url": endpoint_url},
- sensitive_config=_build_s3_sensitive_config(aws_access_key_id, aws_secret_access_key),
+ sensitive_config={
+ "aws_access_key_id": aws_access_key_id,
+ "aws_secret_access_key": aws_secret_access_key,
+ },
created_by=created_by,
)
@@ -5024,27 +5125,75 @@ class TLS(NamedTuple):
ssl_root_cert: str | Literal["system"] = MISSING_CERT_PATH
-class PostgreSQLIntegration:
+_PostgreSQLServerKindType = Literal[Integration.IntegrationKind.AWS_REDSHIFT, Integration.IntegrationKind.POSTGRESQL]
+
+
+class PostgreSQLServerIntegration:
+ """Base class for any integration targetting a PostgreSQL-server."""
+
integration: Integration
+ integration_kind: ClassVar[_PostgreSQLServerKindType]
def __init__(self, integration: Integration) -> None:
+ if integration.kind != self.integration_kind:
+ raise IntegrationError(
+ "Integration provided is not the expected PostgreSQL server integration "
+ f"(got kind='{integration.kind}', expected kind='{self.integration_kind}')"
+ )
+
self.integration = integration
@classmethod
def integration_from_config(
cls,
team_id: int,
- host: str,
- port: int,
- user: str,
- password: str,
- ssl_mode: Literal["prefer", "require", "verify-ca", "verify-full"] = "require",
- ssl_root_cert: str | Literal["system"] | None = None,
created_by: User | None = None,
+ **config,
) -> Integration:
+ from products.batch_exports.backend.api.batch_export import resolve_and_validate_host
+
+ host = _return_non_empty_str_from_config(config, "host", friendly_name="Host", kind=cls.integration_kind)
+ try:
+ resolve_and_validate_host(host)
+ except ValueError:
+ raise IntegrationError(f"Provided host '{host}' is not valid")
+
+ port = config.get("port", None)
+ try:
+ port = int(port) # type: ignore
+ except (TypeError, ValueError):
+ raise IntegrationError("Port must be an integer")
+
+ if port > 65535 or port < 0:
+ raise IntegrationError(f"A valid port is required for an {cls.integration_kind} integration")
+
+ user = _return_non_empty_str_from_config(
+ config,
+ "user",
+ friendly_name="A username",
+ kind=cls.integration_kind,
+ )
+ password = _return_non_empty_str_from_config(
+ config,
+ "password",
+ friendly_name="A password",
+ kind=cls.integration_kind,
+ )
+
+ ssl_mode = config.get("ssl_mode", "require")
+ if ssl_mode not in ("require", "verify-ca", "verify-full"):
+ raise IntegrationError("SSL mode must be one of: require, verify-ca, verify-full")
+
+ ssl_root_cert = config.get("ssl_root_cert", None)
+ if ssl_mode in ("verify-ca", "verify-full"):
+ if not ssl_root_cert:
+ raise IntegrationError("SSL root certificate must be provided when verifying server certificates")
+ if not isinstance(ssl_root_cert, str):
+ raise IntegrationError("SSL root certificate must be a string")
+
integration, _ = Integration.objects.update_or_create(
team_id=team_id,
- kind=Integration.IntegrationKind.POSTGRESQL,
+ kind=cls.integration_kind,
integration_id=f"{team_id}-{host}-{port}-{user}",
defaults={
"config": {
@@ -5084,6 +5233,16 @@ class PostgreSQLIntegration:
return TLS(ssl_mode=self.integration.config["ssl_mode"])
+class PostgreSQLIntegration(PostgreSQLServerIntegration):
+ integration_kind: ClassVar[Literal[Integration.IntegrationKind.POSTGRESQL]] = Integration.IntegrationKind.POSTGRESQL
+
+
+class RedshiftIntegration(PostgreSQLServerIntegration):
+ integration_kind: ClassVar[Literal[Integration.IntegrationKind.AWS_REDSHIFT]] = (
+ Integration.IntegrationKind.AWS_REDSHIFT
+ )
+
+
@receiver(models.signals.post_delete, sender=Integration)
def cleanup_ses_identity_on_integration_delete(sender: Any, instance: Integration, **kwargs: Any) -> None:
# A post_delete signal (rather than viewset perform_destroy) so SES identities are
diff --git a/posthog/models/test/test_integration_model.py b/posthog/models/test/test_integration_model.py
index 7a49e5b75c1e..1fcfad08bc85 100644
--- a/posthog/models/test/test_integration_model.py
+++ b/posthog/models/test/test_integration_model.py
@@ -18,7 +18,7 @@ from django.utils import timezone
import requests
from disposable_email_domains import blocklist as disposable_email_domains_list
-from parameterized import parameterized
+from parameterized import parameterized, parameterized_class
from prometheus_client import REGISTRY
from rest_framework.exceptions import ValidationError
@@ -38,10 +38,11 @@ from posthog.models.integration import (
POSTHOG_CONNECT_IDENTITY_SCOPES,
TLS,
Authority,
- AwsS3Integration,
+ AWSS3Integration,
Credentials,
DatabricksIntegration,
DatabricksIntegrationError,
+ DuplicateNameError,
EmailIntegration,
GitHubIntegration,
GitHubIntegrationError,
@@ -50,12 +51,13 @@ from posthog.models.integration import (
GoogleCloudServiceAccountIntegration,
InstagramIntegration,
Integration,
+ IntegrationError,
JiraIntegration,
LinearIntegration,
OauthIntegration,
PostgreSQLIntegration,
+ RedshiftIntegration,
S3CompatibleIntegration,
- S3CredentialIntegrationError,
SlackIntegration,
SnowflakeIntegration,
SnowflakeIntegrationError,
@@ -64,6 +66,7 @@ from posthog.models.integration import (
oauth_refresh_failure_reason,
oauth_refresh_terminal_counter,
refresh_backoff_active,
+ validate_aws_credentials,
)
from posthog.models.organization import Organization
from posthog.models.team.team import Team
@@ -3407,10 +3410,10 @@ class TestDatabricksIntegrationModel(BaseTest):
)
-class TestAwsS3IntegrationModel(BaseTest):
- @patch("posthog.models.integration.AwsS3Integration.validate_credentials", return_value="123456789012")
+class TestAWSS3IntegrationModel(BaseTest):
+ @patch("posthog.models.integration.validate_aws_credentials", return_value="123456789012")
def test_integration_from_config_with_valid_config(self, mock_validate):
- integration = AwsS3Integration.integration_from_config(
+ integration = AWSS3Integration.integration_from_config(
team_id=self.team.pk,
name="prod-aws",
aws_access_key_id="AKIAEXAMPLE",
@@ -3430,27 +3433,27 @@ class TestAwsS3IntegrationModel(BaseTest):
}
# display_name surfaces AWS account so users can tell integrations apart.
assert integration.display_name == "prod-aws (AWS account 123456789012)"
- assert AwsS3Integration(integration).aws_account_id == "123456789012"
+ assert AWSS3Integration(integration).aws_account_id == "123456789012"
def test_integration_from_config_requires_name(self):
- with pytest.raises(S3CredentialIntegrationError, match="A name is required"):
- AwsS3Integration.integration_from_config(
+ with pytest.raises(IntegrationError, match="A name is required"):
+ AWSS3Integration.integration_from_config(
team_id=self.team.pk,
name="",
aws_access_key_id="AKIAEXAMPLE",
aws_secret_access_key="secret",
)
- @patch("posthog.models.integration.AwsS3Integration.validate_credentials", return_value="123456789012")
+ @patch("posthog.models.integration.validate_aws_credentials", return_value="123456789012")
def test_integration_from_config_rejects_duplicate_name(self, mock_validate):
- AwsS3Integration.integration_from_config(
+ AWSS3Integration.integration_from_config(
team_id=self.team.pk,
name="prod-aws",
aws_access_key_id="AKIAEXAMPLE",
aws_secret_access_key="secret",
)
- with pytest.raises(S3CredentialIntegrationError, match="An integration named 'prod-aws' already exists"):
- AwsS3Integration.integration_from_config(
+ with pytest.raises(DuplicateNameError, match="An integration named 'prod-aws' already exists"):
+ AWSS3Integration.integration_from_config(
team_id=self.team.pk,
name="prod-aws",
aws_access_key_id="AKIAOTHER",
@@ -3459,36 +3462,34 @@ class TestAwsS3IntegrationModel(BaseTest):
assert Integration.objects.filter(team=self.team, integration_id="prod-aws").count() == 1
@patch("boto3.client")
- def test_validate_credentials_returns_account_id(self, mock_boto_client):
+ def test_validate_aws_credentials_returns_account_id(self, mock_boto_client):
mock_boto_client.return_value.get_caller_identity.return_value = {"Account": "123456789012"}
- assert AwsS3Integration.validate_credentials("key", "secret") == "123456789012"
+ assert validate_aws_credentials("key", "secret") == "123456789012"
@patch("boto3.client")
- def test_validate_credentials_raises_on_invalid_credentials(self, mock_boto_client):
+ def test_validate_aws_credentials_raises_on_invalid_credentials(self, mock_boto_client):
from botocore.exceptions import ClientError
mock_boto_client.return_value.get_caller_identity.side_effect = ClientError(
{"Error": {"Code": "InvalidClientTokenId", "Message": "The security token is invalid."}},
"GetCallerIdentity",
)
- with pytest.raises(
- S3CredentialIntegrationError, match="AWS credentials are not valid: The security token is invalid."
- ):
- AwsS3Integration.validate_credentials("key", "secret")
+ with pytest.raises(IntegrationError, match="AWS credentials are not valid: The security token is invalid."):
+ validate_aws_credentials("key", "secret")
def test_wrapping_wrong_kind_raises(self):
integration = Integration.objects.create(
team=self.team, kind=Integration.IntegrationKind.S3_COMPATIBLE, integration_id="x"
)
- with pytest.raises(S3CredentialIntegrationError, match="is not an AWS S3 integration"):
- AwsS3Integration(integration)
+ with pytest.raises(IntegrationError, match="is not the expected AWS integration"):
+ AWSS3Integration(integration)
def test_wrapping_missing_credentials_raises(self):
integration = Integration.objects.create(
team=self.team, kind=Integration.IntegrationKind.AWS_S3, integration_id="x", sensitive_config={}
)
- with pytest.raises(S3CredentialIntegrationError, match="missing"):
- AwsS3Integration(integration)
+ with pytest.raises(IntegrationError, match="missing"):
+ AWSS3Integration(integration)
class TestS3CompatibleIntegrationModel(BaseTest):
@@ -3512,7 +3513,7 @@ class TestS3CompatibleIntegrationModel(BaseTest):
assert integration.display_name == "my-r2 (access key, https://account.r2.cloudflarestorage.com)"
def test_integration_from_config_requires_endpoint_url(self):
- with pytest.raises(S3CredentialIntegrationError, match="endpoint URL is required"):
+ with pytest.raises(IntegrationError, match="Endpoint URL is required"):
S3CompatibleIntegration.integration_from_config(
team_id=self.team.pk,
name="my-r2",
@@ -3529,7 +3530,7 @@ class TestS3CompatibleIntegrationModel(BaseTest):
aws_access_key_id="key",
aws_secret_access_key="secret",
)
- with pytest.raises(S3CredentialIntegrationError, match="An integration named 'my-r2' already exists"):
+ with pytest.raises(DuplicateNameError, match="An integration named 'my-r2' already exists"):
S3CompatibleIntegration.integration_from_config(
team_id=self.team.pk,
name="my-r2",
@@ -3542,7 +3543,7 @@ class TestS3CompatibleIntegrationModel(BaseTest):
# is_url_allowed bypasses validation in DEBUG/test mode, so force the production path to exercise rejection.
@override_settings(FORCE_URL_VALIDATION=True)
def test_integration_from_config_rejects_internal_endpoint(self):
- with pytest.raises(S3CredentialIntegrationError, match="Invalid endpoint URL"):
+ with pytest.raises(IntegrationError, match="Invalid endpoint URL"):
S3CompatibleIntegration.integration_from_config(
team_id=self.team.pk,
name="my-r2",
@@ -3559,7 +3560,7 @@ class TestS3CompatibleIntegrationModel(BaseTest):
config={"name": "x"},
sensitive_config={"aws_access_key_id": "key", "aws_secret_access_key": "secret"},
)
- with pytest.raises(S3CredentialIntegrationError, match="missing required field: 'endpoint_url'"):
+ with pytest.raises(IntegrationError, match="missing required field: 'endpoint_url'"):
S3CompatibleIntegration(integration)
@@ -4375,7 +4376,22 @@ class TestGitLabIntegrationSSRFProtection:
mock_post.assert_not_called()
+@parameterized_class(
+ [
+ {
+ "integration_cls": PostgreSQLIntegration,
+ "integration_kind": Integration.IntegrationKind.POSTGRESQL,
+ },
+ {
+ "integration_cls": RedshiftIntegration,
+ "integration_kind": Integration.IntegrationKind.AWS_REDSHIFT,
+ },
+ ]
+)
class TestPostgreSQLIntegrationModel(BaseTest):
+ integration_kind: Integration.IntegrationKind
+ integration_cls: type[RedshiftIntegration] | type[PostgreSQLIntegration]
+
@parameterized.expand(
[
(
@@ -4419,13 +4435,13 @@ class TestPostgreSQLIntegrationModel(BaseTest):
integration = Integration.objects.create(
team=self.team,
- kind=Integration.IntegrationKind.POSTGRESQL,
+ kind=self.integration_kind,
integration_id=f"{self.team.pk}-db.example.com-5432-exporter",
config=config,
sensitive_config=sensitive_config,
)
- pq = PostgreSQLIntegration(integration)
+ pq = self.integration_cls(integration)
assert pq.tls() == expected_tls
@parameterized.expand(
@@ -4450,23 +4466,24 @@ class TestPostgreSQLIntegrationModel(BaseTest):
def test_integration_from_config(self, _name, overrides, expected_tls):
kwargs = {
"team_id": self.team.pk,
- "host": "db.example.com",
+ "host": "localhost",
"port": 5432,
"user": "exporter",
"password": "super-secret",
}
kwargs.update(overrides)
- integration = PostgreSQLIntegration.integration_from_config(**kwargs) # type: ignore
- pq = PostgreSQLIntegration(integration)
+ integration = self.integration_cls.integration_from_config(**kwargs) # type: ignore
+ pq = self.integration_cls(integration)
- assert pq.authority() == Authority(host="db.example.com", port=5432)
+ assert pq.authority() == Authority(host="localhost", port=5432)
assert pq.credentials() == Credentials(user="exporter", password="super-secret")
assert pq.tls() == expected_tls
assert "password" not in integration.config
assert integration.sensitive_config["password"] == "super-secret"
+ assert pq.integration_kind == self.integration_kind
def _make_resend_jwt(payload: dict) -> str:
diff --git a/products/batch_exports/backend/temporal/destinations/s3_batch_export.py b/products/batch_exports/backend/temporal/destinations/s3_batch_export.py
index fc3c601cff20..d023b11d652b 100644
--- a/products/batch_exports/backend/temporal/destinations/s3_batch_export.py
+++ b/products/batch_exports/backend/temporal/destinations/s3_batch_export.py
@@ -24,11 +24,11 @@ from temporalio import activity, exceptions, workflow
from temporalio.common import RetryPolicy
from posthog.models.integration import (
- AwsS3Integration,
- AwsS3RoleBasedIntegration,
+ AWSS3Integration,
+ AWSS3RoleBasedIntegration,
Integration,
+ IntegrationError,
S3CompatibleIntegration,
- S3CredentialIntegrationError,
)
from posthog.models.team import Team
from posthog.temporal.common.base import PostHogWorkflow
@@ -93,7 +93,7 @@ NON_RETRYABLE_ERROR_TYPES = (
# The linked Integration was deleted or doesn't belong to the team
"S3IntegrationNotFoundError",
# The linked Integration is the wrong kind or has invalid/missing credentials
- "S3CredentialIntegrationError",
+ "IntegrationError",
)
FILE_FORMAT_EXTENSIONS = {
@@ -138,12 +138,12 @@ class S3IntegrationNotFoundError(Exception):
async def _get_s3_integration(
integration_id: int, team_id: int
-) -> AwsS3RoleBasedIntegration | AwsS3Integration | S3CompatibleIntegration:
+) -> AWSS3RoleBasedIntegration | AWSS3Integration | S3CompatibleIntegration:
"""Fetch an S3-family integration from the database.
The kind is validated on create by the batch export serializer, so the wrong-kind branch is
purely defensive against an integration whose kind was changed out from under the export.
- `AwsS3Integration`/`S3CompatibleIntegration` themselves raise `S3CredentialIntegrationError` if
+ `AWSS3Integration`/`S3CompatibleIntegration` themselves raise `IntegrationError` if
the credentials are malformed.
"""
try:
@@ -153,13 +153,13 @@ async def _get_s3_integration(
if integration.kind == Integration.IntegrationKind.AWS_S3:
if "aws_role_arn" in integration.config:
- return AwsS3RoleBasedIntegration(integration)
- return AwsS3Integration(integration)
+ return AWSS3RoleBasedIntegration(integration)
+ return AWSS3Integration(integration)
if integration.kind == Integration.IntegrationKind.S3_COMPATIBLE:
return S3CompatibleIntegration(integration)
- raise S3CredentialIntegrationError(
+ raise IntegrationError(
f"Integration with ID '{integration_id}' for team '{team_id}' is not an S3 integration "
f"(kind='{integration.kind}')"
)
@@ -568,11 +568,11 @@ async def insert_into_s3_activity_from_stage(inputs: S3InsertInputs) -> S3BatchE
if inputs.integration_id is not None:
integration = await _get_s3_integration(inputs.integration_id, inputs.team_id)
- if isinstance(integration, AwsS3Integration):
+ if isinstance(integration, AWSS3Integration):
aws_access_key_id = integration.aws_access_key_id
aws_secret_access_key = integration.aws_secret_access_key
- if isinstance(integration, AwsS3RoleBasedIntegration):
+ if isinstance(integration, AWSS3RoleBasedIntegration):
team = await Team.objects.aget(id=inputs.team_id)
external_id = f"posthog-{team.organization_id}"
diff --git a/products/batch_exports/backend/tests/temporal/destinations/s3/test_activity.py b/products/batch_exports/backend/tests/temporal/destinations/s3/test_activity.py
index 7cc80b9884ce..5b7f035bf595 100644
--- a/products/batch_exports/backend/tests/temporal/destinations/s3/test_activity.py
+++ b/products/batch_exports/backend/tests/temporal/destinations/s3/test_activity.py
@@ -6,7 +6,7 @@ from django.conf import settings
from temporalio.testing._activity import ActivityEnvironment
-from posthog.models.integration import Integration, S3CredentialIntegrationError
+from posthog.models.integration import Integration, IntegrationError
from posthog.temporal.tests.utils.events import generate_test_events_in_clickhouse
from products.batch_exports.backend.service import BatchExportModel, BatchExportSchema
@@ -42,7 +42,7 @@ async def test_get_s3_integration_rejects_wrong_kind(ateam):
sensitive_config={},
)
- with pytest.raises(S3CredentialIntegrationError) as exc_info:
+ with pytest.raises(IntegrationError) as exc_info:
await _get_s3_integration(integration.id, ateam.pk)
assert "not an S3 integration" in str(exc_info.value)
assert "kind='slack'" in str(exc_info.value)