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.

refactor(security): return typed credential objects instead of tuples (#73268)

Arno Hillen954fd71ce72f
diff --git a/ee/api/scim/auth.py b/ee/api/scim/auth.py
index c97f80760cef..398a70d67bf4 100644
--- a/ee/api/scim/auth.py
+++ b/ee/api/scim/auth.py
@@ -1,3 +1,5 @@
+import secrets
+from dataclasses import dataclass, field
from typing import Optional
from django.contrib.auth.hashers import check_password, make_password
@@ -85,13 +87,15 @@ class SCIMBearerTokenAuthentication(BaseAuthentication):
return None
-def generate_scim_token() -> tuple[str, str]:
- """
- Generate a new SCIM bearer token.
- Returns (plain_token, hashed_token) tuple.
- """
- import secrets
+@dataclass(frozen=True)
+class ScimToken:
+ # `plain` is shown to the user once. Only `hashed` is persisted.
+ plain: str = field(repr=False)
+ hashed: str
+
+def generate_scim_token() -> ScimToken:
+ """Generate a new SCIM bearer token."""
plain_token = secrets.token_urlsafe(32)
hashed_token = make_password(plain_token)
- return plain_token, hashed_token
+ return ScimToken(plain=plain_token, hashed=hashed_token)
diff --git a/ee/api/scim/test/test_groups_api.py b/ee/api/scim/test/test_groups_api.py
index a4bcefcf48f2..bdeda1b7b737 100644
--- a/ee/api/scim/test/test_groups_api.py
+++ b/ee/api/scim/test/test_groups_api.py
@@ -36,9 +36,10 @@ class TestSCIMGroupsAPI(APILicensedTest):
)
# Generate SCIM token
- self.plain_token, hashed_token = generate_scim_token()
+ token = generate_scim_token()
+ self.plain_token = token.plain
config = IdentityProviderConfig.objects.create(
- organization=self.organization, scim_enabled=True, scim_bearer_token=hashed_token
+ organization=self.organization, scim_enabled=True, scim_bearer_token=token.hashed
)
self.domain.identity_provider_config = config
self.domain.save()
diff --git a/ee/api/scim/test/test_scim_api.py b/ee/api/scim/test/test_scim_api.py
index 5804c1e3dca7..579db0760d68 100644
--- a/ee/api/scim/test/test_scim_api.py
+++ b/ee/api/scim/test/test_scim_api.py
@@ -34,9 +34,10 @@ class TestSCIMAPI(APILicensedTest):
)
# Generate SCIM token
- self.plain_token, hashed_token = generate_scim_token()
+ token = generate_scim_token()
+ self.plain_token = token.plain
config = IdentityProviderConfig.objects.create(
- organization=self.organization, scim_enabled=True, scim_bearer_token=hashed_token
+ organization=self.organization, scim_enabled=True, scim_bearer_token=token.hashed
)
self.domain.identity_provider_config = config
self.domain.save()
@@ -69,14 +70,15 @@ class TestSCIMAPI(APILicensedTest):
def test_unverified_domain_is_rejected(self):
# SCIM can be enabled on a config independently of any domain, so an unverified domain with
# a SCIM-enabled config must still be rejected — provisioning stays gated behind verification.
- plain_token, hashed_token = generate_scim_token()
+ token = generate_scim_token()
+ plain_token = token.plain
unverified = OrganizationDomain.objects.create(
organization=self.organization,
domain="unverified.example.com",
verified_at=None,
)
config = IdentityProviderConfig.objects.create(
- organization=self.organization, scim_enabled=True, scim_bearer_token=hashed_token
+ organization=self.organization, scim_enabled=True, scim_bearer_token=token.hashed
)
unverified.identity_provider_config = config
unverified.save()
@@ -272,9 +274,10 @@ class TestSCIMEmailDomainValidation(APILicensedTest):
verified_at="2024-01-01T00:00:00Z",
)
- self.plain_token, hashed_token = generate_scim_token()
+ token = generate_scim_token()
+ self.plain_token = token.plain
config = IdentityProviderConfig.objects.create(
- organization=self.organization, scim_enabled=True, scim_bearer_token=hashed_token
+ organization=self.organization, scim_enabled=True, scim_bearer_token=token.hashed
)
self.domain.identity_provider_config = config
self.domain.save()
@@ -511,9 +514,10 @@ class TestSCIMAuditLogging(APILicensedTest):
verified_at="2024-01-01T00:00:00Z",
)
- self.plain_token, hashed_token = generate_scim_token()
+ token = generate_scim_token()
+ self.plain_token = token.plain
config = IdentityProviderConfig.objects.create(
- organization=self.organization, scim_enabled=True, scim_bearer_token=hashed_token
+ organization=self.organization, scim_enabled=True, scim_bearer_token=token.hashed
)
self.domain.identity_provider_config = config
self.domain.save()
@@ -607,9 +611,10 @@ class TestSCIMGroupAuditLogging(APILicensedTest):
verified_at="2024-01-01T00:00:00Z",
)
- self.plain_token, hashed_token = generate_scim_token()
+ token = generate_scim_token()
+ self.plain_token = token.plain
config = IdentityProviderConfig.objects.create(
- organization=self.organization, scim_enabled=True, scim_bearer_token=hashed_token
+ organization=self.organization, scim_enabled=True, scim_bearer_token=token.hashed
)
self.domain.identity_provider_config = config
self.domain.save()
diff --git a/ee/api/scim/test/test_scim_request_log.py b/ee/api/scim/test/test_scim_request_log.py
index 2994c22865cc..adf1a8663968 100644
--- a/ee/api/scim/test/test_scim_request_log.py
+++ b/ee/api/scim/test/test_scim_request_log.py
@@ -36,9 +36,10 @@ class TestSCIMRequestLogCapture(APILicensedTest):
domain="example.com",
verified_at="2024-01-01T00:00:00Z",
)
- self.plain_token, hashed_token = generate_scim_token()
+ token = generate_scim_token()
+ self.plain_token = token.plain
config = IdentityProviderConfig.objects.create(
- organization=self.organization, scim_enabled=True, scim_bearer_token=hashed_token
+ organization=self.organization, scim_enabled=True, scim_bearer_token=token.hashed
)
self.domain.identity_provider_config = config
self.domain.save()
diff --git a/ee/api/scim/test/test_users_api.py b/ee/api/scim/test/test_users_api.py
index d1464b026685..14a3dfe1c6a8 100644
--- a/ee/api/scim/test/test_users_api.py
+++ b/ee/api/scim/test/test_users_api.py
@@ -34,9 +34,10 @@ class TestSCIMUsersAPI(APILicensedTest):
)
# Generate SCIM token
- self.plain_token, hashed_token = generate_scim_token()
+ token = generate_scim_token()
+ self.plain_token = token.plain
config = IdentityProviderConfig.objects.create(
- organization=self.organization, scim_enabled=True, scim_bearer_token=hashed_token
+ organization=self.organization, scim_enabled=True, scim_bearer_token=token.hashed
)
self.domain.identity_provider_config = config
self.domain.save()
diff --git a/ee/api/scim/utils.py b/ee/api/scim/utils.py
index ab81606ff19a..a9d4a8555a15 100644
--- a/ee/api/scim/utils.py
+++ b/ee/api/scim/utils.py
@@ -93,13 +93,13 @@ def enable_scim_for_config(config: IdentityProviderConfig) -> str:
Enable SCIM for an IdentityProviderConfig and generate a new bearer token.
Returns the plain text token (only shown once).
"""
- plain_token, hashed_token = generate_scim_token()
+ token = generate_scim_token()
config.scim_enabled = True
- config.scim_bearer_token = hashed_token
+ config.scim_bearer_token = token.hashed
config.save()
- return plain_token
+ return token.plain
def disable_scim_for_config(config: IdentityProviderConfig) -> None:
@@ -116,12 +116,12 @@ def regenerate_scim_token_for_config(config: IdentityProviderConfig) -> str:
Regenerate SCIM bearer token for an IdentityProviderConfig.
Returns the new plain text token (only shown once).
"""
- plain_token, hashed_token = generate_scim_token()
+ token = generate_scim_token()
- config.scim_bearer_token = hashed_token
+ config.scim_bearer_token = token.hashed
config.save()
- return plain_token
+ return token.plain
def get_scim_base_url(domain: OrganizationDomain, request=None) -> str:
diff --git a/posthog/api/oauth/toolbar_service.py b/posthog/api/oauth/toolbar_service.py
index 16f1c74929ea..5c2669ceba54 100644
--- a/posthog/api/oauth/toolbar_service.py
+++ b/posthog/api/oauth/toolbar_service.py
@@ -8,8 +8,6 @@ Non-obvious behavior documented here:
"""
import re
-import base64
-import hashlib
import secrets
from dataclasses import dataclass
from datetime import UTC, datetime
@@ -377,13 +375,5 @@ def refresh_tokens(
)
-def generate_pkce_pair() -> tuple[str, str]:
- """Generate a PKCE code_verifier and its S256 code_challenge."""
- code_verifier = secrets.token_urlsafe(48)
- digest = hashlib.sha256(code_verifier.encode("ascii")).digest()
- code_challenge = base64.urlsafe_b64encode(digest).rstrip(b"=").decode("ascii")
- return code_verifier, code_challenge
-
-
def new_state_nonce() -> str:
return secrets.token_urlsafe(24)
diff --git a/posthog/clickhouse/client/connection.py b/posthog/clickhouse/client/connection.py
index f4752e651604..947fea82ef31 100644
--- a/posthog/clickhouse/client/connection.py
+++ b/posthog/clickhouse/client/connection.py
@@ -2,6 +2,7 @@ import os
import logging
from collections.abc import Mapping
from contextlib import contextmanager
+from dataclasses import dataclass, field
from enum import StrEnum
from functools import cache
from typing import TYPE_CHECKING
@@ -88,18 +89,26 @@ class ClickHouseUser(StrEnum):
DICT_READER = "dict_reader"
-__user_dict: Mapping[ClickHouseUser, tuple[str, str]] | None = None
+@dataclass(frozen=True)
+class ClickHouseCredentials:
+ user: str
+ password: str = field(repr=False)
-def init_clickhouse_users() -> Mapping[ClickHouseUser, tuple[str, str]]:
+__user_dict: Mapping[ClickHouseUser, ClickHouseCredentials] | None = None
+
+
+def init_clickhouse_users() -> Mapping[ClickHouseUser, ClickHouseCredentials]:
user_dict = {
- ClickHouseUser.DEFAULT: (data_stores.CLICKHOUSE_USER, data_stores.CLICKHOUSE_PASSWORD),
+ ClickHouseUser.DEFAULT: ClickHouseCredentials(
+ user=data_stores.CLICKHOUSE_USER, password=data_stores.CLICKHOUSE_PASSWORD
+ ),
}
for u in ClickHouseUser:
user = os.getenv(f"CLICKHOUSE_{u.name.upper()}_USER")
password = os.getenv(f"CLICKHOUSE_{u.name.upper()}_PASSWORD")
if user and password:
- user_dict[u] = (user, password)
+ user_dict[u] = ClickHouseCredentials(user=user, password=password)
elif bool(user) != bool(password):
logging.warning(f"only one of clickhouse user/password provided, check your config")
user_names = ",".join([x.name for x in user_dict.keys()])
@@ -107,7 +116,7 @@ def init_clickhouse_users() -> Mapping[ClickHouseUser, tuple[str, str]]:
return user_dict
-def get_clickhouse_creds(user: ClickHouseUser) -> tuple[str, str]:
+def get_clickhouse_creds(user: ClickHouseUser) -> ClickHouseCredentials:
"""
Retrieve ClickHouse credentials for the specified user.
@@ -122,15 +131,11 @@ def get_clickhouse_creds(user: ClickHouseUser) -> tuple[str, str]:
Args:
user (ClickHouseUser): The user whose ClickHouse credentials need
to be retrieved.
-
- Returns:
- tuple[str, str]: A tuple containing the username and password associated
- with the specified user.
"""
global __user_dict
if not __user_dict:
__user_dict = init_clickhouse_users()
- return __user_dict[user] if user in __user_dict else __user_dict[ClickHouseUser.DEFAULT]
+ return __user_dict.get(user, __user_dict[ClickHouseUser.DEFAULT])
class ProxyClient:
@@ -224,8 +229,8 @@ def get_kwargs_for_client(
"secure": settings.CLICKHOUSE_LOGS_CLUSTER_SECURE,
}
- (user, password) = get_clickhouse_creds(ch_user)
- base_kwargs = {"user": user, "password": password}
+ creds = get_clickhouse_creds(ch_user)
+ base_kwargs = {"user": creds.user, "password": creds.password}
if team_id is not None and str(team_id) in settings.CLICKHOUSE_PER_TEAM_SETTINGS:
user_settings = settings.CLICKHOUSE_PER_TEAM_SETTINGS[str(team_id)]
diff --git a/posthog/clickhouse/dictionaries.py b/posthog/clickhouse/dictionaries.py
index 9a8bdbc7a003..efb2722836b3 100644
--- a/posthog/clickhouse/dictionaries.py
+++ b/posthog/clickhouse/dictionaries.py
@@ -7,10 +7,10 @@ def dictionary_source_clickhouse(table: str) -> str:
"""Build a dictionary SOURCE(CLICKHOUSE(...)) clause authed as the dedicated
low-privilege dict_reader user (falls back to the default user when the
CLICKHOUSE_DICT_READER_* env vars are unset)."""
- user, password = get_clickhouse_creds(ClickHouseUser.DICT_READER)
+ creds = get_clickhouse_creds(ClickHouseUser.DICT_READER)
connection_settings = f"TABLE {table} DB '{settings.CLICKHOUSE_DATABASE}'"
- if user:
- connection_settings += f" USER '{user}'"
- if password:
- connection_settings += f" PASSWORD '{password}'"
+ if creds.user:
+ connection_settings += f" USER '{creds.user}'"
+ if creds.password:
+ connection_settings += f" PASSWORD '{creds.password}'"
return f"SOURCE(CLICKHOUSE({connection_settings}))"
diff --git a/posthog/credentials.py b/posthog/credentials.py
new file mode 100644
index 000000000000..93d1b44320a8
--- /dev/null
+++ b/posthog/credentials.py
@@ -0,0 +1,34 @@
+from dataclasses import dataclass, field
+from typing import NewType
+
+# Distinct static types for the two halves of an AWS key pair. They are plain `str` at runtime.
+# The point is that a type checker rejects passing a secret where a key id is expected.
+AWSAccessKeyId = NewType("AWSAccessKeyId", str)
+AWSSecretAccessKey = NewType("AWSSecretAccessKey", str)
+
+
+@dataclass(frozen=True)
+class AWSKeyPair:
+ """An AWS access key and its secret, kept together.
+
+ Pass this rather than the two halves: callers taking a single argument have no order to get
+ wrong, and code holding one cannot end up with the key present and the secret missing. Where
+ credentials are optional (keyless IAM auth), use `AWSKeyPair | None` so that "no credentials"
+ stays distinct from "half a pair".
+ """
+
+ access_key_id: AWSAccessKeyId
+ secret_access_key: AWSSecretAccessKey = field(repr=False)
+
+ @classmethod
+ def unsafe_from_strings(cls, access_key_id: str, secret_access_key: str) -> "AWSKeyPair":
+ """Brand two raw strings as a key pair.
+
+ Unsafe because nothing checks the arguments are the right way round: this is the only
+ place where getting it wrong is possible. Call it where a credential enters the process
+ (settings, integration config, a secrets manager), and pass the pair around from there.
+ """
+ return cls(
+ access_key_id=AWSAccessKeyId(access_key_id),
+ secret_access_key=AWSSecretAccessKey(secret_access_key),
+ )
diff --git a/posthog/dags/common/resources.py b/posthog/dags/common/resources.py
index 661f0ed3e481..d76c5319dfa0 100644
--- a/posthog/dags/common/resources.py
+++ b/posthog/dags/common/resources.py
@@ -142,10 +142,10 @@ class BackupsClickhouseClusterResource(dagster.ConfigurableResource):
def create_resource(self, context: dagster.InitResourceContext) -> ClickhouseCluster:
assert context.log is not None
- user, password = get_clickhouse_creds(ClickHouseUser.BACKUPS)
+ creds = get_clickhouse_creds(ClickHouseUser.BACKUPS)
from django.conf import settings as django_settings
- if user == django_settings.CLICKHOUSE_USER:
+ if creds.user == django_settings.CLICKHOUSE_USER:
context.log.warning(
"CLICKHOUSE_BACKUPS_USER not configured, falling back to default user. "
"Backups will not use the dedicated 'backups' profile with use_concurrency_control=0."
@@ -160,7 +160,7 @@ class BackupsClickhouseClusterResource(dagster.ConfigurableResource):
delay=ExponentialBackoff(20, max_delay=60),
exceptions=_is_retryable_clickhouse_exception,
),
- connection_overrides={"user": user, "password": password},
+ connection_overrides={"user": creds.user, "password": creds.password},
)
@@ -181,12 +181,12 @@ class PartBreakerClickhouseClusterResource(dagster.ConfigurableResource):
def create_resource(self, context: dagster.InitResourceContext) -> ClickhouseCluster:
assert context.log is not None
- user, password = get_clickhouse_creds(ClickHouseUser.PART_BREAKER)
+ creds = get_clickhouse_creds(ClickHouseUser.PART_BREAKER)
from django.conf import settings as django_settings
- if user == django_settings.CLICKHOUSE_USER:
+ if creds.user == django_settings.CLICKHOUSE_USER:
context.log.warning(
- f"CLICKHOUSE_PART_BREAKER_USER not configured, falling back to default user '{user}'. "
+ f"CLICKHOUSE_PART_BREAKER_USER not configured, falling back to default user '{creds.user}'. "
"Part breaker will not use a dedicated user with restricted permissions."
)
return get_cluster(
@@ -197,7 +197,7 @@ class PartBreakerClickhouseClusterResource(dagster.ConfigurableResource):
delay=ExponentialBackoff(20, max_delay=60),
exceptions=_is_retryable_clickhouse_exception,
),
- connection_overrides={"user": user, "password": password},
+ connection_overrides={"user": creds.user, "password": creds.password},
)
diff --git a/posthog/hogql/database/schema/web_analytics_s3.py b/posthog/hogql/database/schema/web_analytics_s3.py
index cc1f66bbfd3e..19a5f1e1c1cf 100644
--- a/posthog/hogql/database/schema/web_analytics_s3.py
+++ b/posthog/hogql/database/schema/web_analytics_s3.py
@@ -1,3 +1,5 @@
+from dataclasses import dataclass, field
+
from posthog.hogql.database.models import FieldOrTable
from posthog.hogql.database.s3_table import S3Table
from posthog.hogql.database.schema.web_analytics_preaggregated import (
@@ -76,22 +78,29 @@ WEB_BOUNCES_S3_FIELDS: dict[str, FieldOrTable] = {
}
-def _get_s3_credentials() -> tuple[str | None, str | None]:
+@dataclass(frozen=True)
+class S3WebCredentials:
+ # Both None outside DEBUG, where the external web-analytics bucket is read without keys.
+ access_key: str | None
+ access_secret: str | None = field(repr=False)
+
+
+def _get_s3_credentials() -> S3WebCredentials:
if DEBUG:
- return OBJECT_STORAGE_ACCESS_KEY_ID, OBJECT_STORAGE_SECRET_ACCESS_KEY
- return None, None
+ return S3WebCredentials(access_key=OBJECT_STORAGE_ACCESS_KEY_ID, access_secret=OBJECT_STORAGE_SECRET_ACCESS_KEY)
+ return S3WebCredentials(access_key=None, access_secret=None)
def _create_s3_web_table(team_id: int, table_name: str, s3_name: str, structure_func, fields: dict) -> S3Table:
url = get_s3_url(table_name=table_name, team_id=team_id)
- access_key, access_secret = _get_s3_credentials()
+ creds = _get_s3_credentials()
return S3Table(
name=s3_name,
url=url,
format="Native",
- access_key=access_key,
- access_secret=access_secret,
+ access_key=creds.access_key,
+ access_secret=creds.access_secret,
structure=structure_func(),
fields=fields,
)
diff --git a/posthog/models/async_deletion/delete_person.py b/posthog/models/async_deletion/delete_person.py
index 7ff038d5f045..dfb687d4c346 100644
--- a/posthog/models/async_deletion/delete_person.py
+++ b/posthog/models/async_deletion/delete_person.py
@@ -38,7 +38,7 @@ def remove_deleted_person_data():
loaded into a dictionary once and deleted with dictHas(), so each part is scanned a single
time instead of re-running a whole-table subquery per affected part.
"""
- dict_reader_user, dict_reader_password = get_clickhouse_creds(ClickHouseUser.DICT_READER)
+ dict_reader_creds = get_clickhouse_creds(ClickHouseUser.DICT_READER)
# Unique per invocation so overlapping runs never create, consume, or drop a shared
# cluster-wide dictionary out from under each other.
@@ -61,7 +61,7 @@ def remove_deleted_person_data():
LAYOUT(COMPLEX_KEY_HASHED())
LIFETIME(0)
""",
- {"dict_reader_user": dict_reader_user, "dict_reader_password": dict_reader_password},
+ {"dict_reader_user": dict_reader_creds.user, "dict_reader_password": dict_reader_creds.password},
workload=Workload.OFFLINE,
)
diff --git a/posthog/models/channel_type/sql.py b/posthog/models/channel_type/sql.py
index 7e2a67b6b454..d71f4da78445 100644
--- a/posthog/models/channel_type/sql.py
+++ b/posthog/models/channel_type/sql.py
@@ -59,7 +59,9 @@ INSERT INTO channel_definition (domain, kind, domain_type, type_if_paid, type_if
"""
)
-CLICKHOUSE_DICT_READER_USER, CLICKHOUSE_DICT_READER_PASSWORD = get_clickhouse_creds(ClickHouseUser.DICT_READER)
+_dict_reader_creds = get_clickhouse_creds(ClickHouseUser.DICT_READER)
+CLICKHOUSE_DICT_READER_USER = _dict_reader_creds.user
+CLICKHOUSE_DICT_READER_PASSWORD = _dict_reader_creds.password
# Use COMPLEX_KEY_HASHED, as we have a composite key
CHANNEL_DEFINITION_DICTIONARY_SQL = lambda on_cluster=True: (
diff --git a/posthog/models/dmat_slot_assignments/sql.py b/posthog/models/dmat_slot_assignments/sql.py
index 13697fd1d8da..ca1ac4a80a7d 100644
--- a/posthog/models/dmat_slot_assignments/sql.py
+++ b/posthog/models/dmat_slot_assignments/sql.py
@@ -64,7 +64,9 @@ FINAL
""".replace("\n", " ").strip()
-CLICKHOUSE_DICT_READER_USER, CLICKHOUSE_DICT_READER_PASSWORD = get_clickhouse_creds(ClickHouseUser.DICT_READER)
+_dict_reader_creds = get_clickhouse_creds(ClickHouseUser.DICT_READER)
+CLICKHOUSE_DICT_READER_USER = _dict_reader_creds.user
+CLICKHOUSE_DICT_READER_PASSWORD = _dict_reader_creds.password
def DMAT_SLOT_ASSIGNMENTS_DICTIONARY_SQL(on_cluster: bool = False) -> str:
diff --git a/posthog/models/exchange_rate/sql.py b/posthog/models/exchange_rate/sql.py
index 2ac15e210ede..da9a504b9d34 100644
--- a/posthog/models/exchange_rate/sql.py
+++ b/posthog/models/exchange_rate/sql.py
@@ -201,7 +201,9 @@ WINDOW w AS (
)
EXCHANGE_RATE_DICTIONARY_QUERY = re.sub(r"\s\s+", " ", EXCHANGE_RATE_DICTIONARY_QUERY)
-CLICKHOUSE_DICT_READER_USER, CLICKHOUSE_DICT_READER_PASSWORD = get_clickhouse_creds(ClickHouseUser.DICT_READER)
+_dict_reader_creds = get_clickhouse_creds(ClickHouseUser.DICT_READER)
+CLICKHOUSE_DICT_READER_USER = _dict_reader_creds.user
+CLICKHOUSE_DICT_READER_PASSWORD = _dict_reader_creds.password
# Use RANGE_HASHED to simplify queries by date
diff --git a/posthog/models/integration.py b/posthog/models/integration.py
index 5db464902f21..caecf5ee57b5 100644
--- a/posthog/models/integration.py
+++ b/posthog/models/integration.py
@@ -43,6 +43,7 @@ from slack_sdk.errors import SlackApiError
from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_fixed
from posthog.cache_utils import cache_for
+from posthog.credentials import AWSKeyPair
from posthog.egress.github.transport import github_request
from posthog.egress.limiter.policies import Priority
from posthog.exceptions_capture import capture_exception
@@ -1882,8 +1883,14 @@ class SlackIntegration:
return config
-def sign_slack_request(body: bytes, signing_secret: str) -> tuple[str, str]:
- """Sign a body with the Slack HMAC-SHA256 scheme; returns (signature, timestamp).
+@dataclass(frozen=True)
+class SlackRequestSignature:
+ signature: str
+ timestamp: str
+
+
+def sign_slack_request(body: bytes, signing_secret: str) -> SlackRequestSignature:
+ """Sign a body with the Slack HMAC-SHA256 scheme.
Used by both prod (PostHog→PostHog cross-region calls that reuse the Slack signing scheme)
and tests. The matching verifier is `validate_slack_request` below.
@@ -1891,7 +1898,7 @@ def sign_slack_request(body: bytes, signing_secret: str) -> tuple[str, str]:
ts = str(int(time.time()))
sig_basestring = f"v0:{ts}:{body.decode('utf-8')}".encode()
signature = "v0=" + hmac.new(signing_secret.encode("utf-8"), sig_basestring, digestmod=hashlib.sha256).hexdigest()
- return signature, ts
+ return SlackRequestSignature(signature=signature, timestamp=ts)
def validate_slack_request(request: HttpRequest | Request, signing_secret: str) -> None:
@@ -4097,11 +4104,10 @@ class S3CredentialIntegrationError(Exception):
pass
-def _read_s3_credentials(integration: Integration) -> tuple[str, str]:
+def _read_s3_credentials(integration: Integration) -> AWSKeyPair:
try:
- return (
- integration.sensitive_config["aws_access_key_id"],
- integration.sensitive_config["aws_secret_access_key"],
+ 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")
@@ -4245,7 +4251,9 @@ class AwsS3Integration:
f"Integration provided is not an AWS S3 integration (got kind='{integration.kind}')"
)
self.integration = integration
- self.aws_access_key_id, self.aws_secret_access_key = _read_s3_credentials(integration)
+ credentials = _read_s3_credentials(integration)
+ self.aws_access_key_id = credentials.access_key_id
+ self.aws_secret_access_key = credentials.secret_access_key
@property
def aws_account_id(self) -> str | None:
@@ -4344,7 +4352,9 @@ class S3CompatibleIntegration:
f"Integration provided is not an S3-compatible integration (got kind='{integration.kind}')"
)
self.integration = integration
- self.aws_access_key_id, self.aws_secret_access_key = _read_s3_credentials(integration)
+ credentials = _read_s3_credentials(integration)
+ self.aws_access_key_id = credentials.access_key_id
+ self.aws_secret_access_key = credentials.secret_access_key
try:
self.endpoint_url = integration.config["endpoint_url"]
except KeyError:
diff --git a/posthog/models/person/sql.py b/posthog/models/person/sql.py
index d67ae5c758bd..fbd1d98ebb2a 100644
--- a/posthog/models/person/sql.py
+++ b/posthog/models/person/sql.py
@@ -742,7 +742,7 @@ def CREATE_PERSON_DISTINCT_ID_OVERRIDES_DICTIONARY():
This must be a function to ensure CLICKHOUSE_DATABASE is evaluated at runtime,
not at module import time (which causes issues in E2E tests where env vars aren't loaded yet).
"""
- clickhouse_user, clickhouse_password = get_clickhouse_creds(ClickHouseUser.DICT_READER)
+ dict_reader_creds = get_clickhouse_creds(ClickHouseUser.DICT_READER)
return """
CREATE OR REPLACE DICTIONARY {database}.person_distinct_id_overrides_dict ON CLUSTER {cluster} (
`team_id` Int64, -- team_id could be made hierarchical to save some space.
@@ -760,6 +760,6 @@ LIFETIME(MIN 3600 MAX 18000)
""".format(
cluster=settings.CLICKHOUSE_CLUSTER,
database=settings.CLICKHOUSE_DATABASE,
- clickhouse_user=clickhouse_user,
- clickhouse_password=clickhouse_password,
+ clickhouse_user=dict_reader_creds.user,
+ clickhouse_password=dict_reader_creds.password,
)
diff --git a/posthog/models/person_overrides/sql.py b/posthog/models/person_overrides/sql.py
index dd7ce9ab13f2..cdeb870cc28d 100644
--- a/posthog/models/person_overrides/sql.py
+++ b/posthog/models/person_overrides/sql.py
@@ -148,7 +148,9 @@ GROUP BY
"""
# ClickHouse dictionaries allow us to JOIN events with their new override_person_ids (if any).
-CLICKHOUSE_DICT_READER_USER, CLICKHOUSE_DICT_READER_PASSWORD = get_clickhouse_creds(ClickHouseUser.DICT_READER)
+_dict_reader_creds = get_clickhouse_creds(ClickHouseUser.DICT_READER)
+CLICKHOUSE_DICT_READER_USER = _dict_reader_creds.user
+CLICKHOUSE_DICT_READER_PASSWORD = _dict_reader_creds.password
PERSON_OVERRIDES_CREATE_DICTIONARY_SQL = f"""
CREATE DICTIONARY IF NOT EXISTS `{CLICKHOUSE_DATABASE}`.`person_overrides_dict`
{ON_CLUSTER_CLAUSE()} (
diff --git a/posthog/models/web_preaggregated/team_selection.py b/posthog/models/web_preaggregated/team_selection.py
index 4ae07514f377..3553cb548750 100644
--- a/posthog/models/web_preaggregated/team_selection.py
+++ b/posthog/models/web_preaggregated/team_selection.py
@@ -118,7 +118,9 @@ WHERE version > 0
""".replace("\n", " ").strip()
-CLICKHOUSE_DICT_READER_USER, CLICKHOUSE_DICT_READER_PASSWORD = get_clickhouse_creds(ClickHouseUser.DICT_READER)
+_dict_reader_creds = get_clickhouse_creds(ClickHouseUser.DICT_READER)
+CLICKHOUSE_DICT_READER_USER = _dict_reader_creds.user
+CLICKHOUSE_DICT_READER_PASSWORD = _dict_reader_creds.password
def WEB_PRE_AGGREGATED_TEAM_SELECTION_DICTIONARY_SQL(on_cluster=True):
diff --git a/posthog/test/test_credentials.py b/posthog/test/test_credentials.py
new file mode 100644
index 000000000000..6dd1e8f1844b
--- /dev/null
+++ b/posthog/test/test_credentials.py
@@ -0,0 +1,13 @@
+from django.test import SimpleTestCase
+
+from posthog.credentials import AWSKeyPair
+
+
+class TestAWSKeyPair(SimpleTestCase):
+ def test_secret_is_absent_from_repr_but_still_readable(self):
+ pair = AWSKeyPair.unsafe_from_strings("AKIAEXAMPLE", "the-secret")
+
+ # A traceback or log line that captures the object must not print the secret.
+ assert "the-secret" not in repr(pair)
+ assert "AKIAEXAMPLE" in repr(pair)
+ assert pair.secret_access_key == "the-secret"
diff --git a/products/batch_exports/backend/temporal/pipeline/internal_stage.py b/products/batch_exports/backend/temporal/pipeline/internal_stage.py
index 3fee07bae219..30940260d13d 100644
--- a/products/batch_exports/backend/temporal/pipeline/internal_stage.py
+++ b/products/batch_exports/backend/temporal/pipeline/internal_stage.py
@@ -18,6 +18,7 @@ from temporalio import activity
from posthog.clickhouse import query_tagging
from posthog.clickhouse.query_tagging import Product
+from posthog.credentials import AWSKeyPair
from products.batch_exports.backend.temporal.utils import make_retryable_with_exponential_backoff
@@ -100,20 +101,24 @@ def _get_s3_endpoint_url() -> str:
return settings.BATCH_EXPORT_OBJECT_STORAGE_ENDPOINT
-def _get_s3_credentials() -> tuple[str | None, str | None]:
- """Get the S3 credentials for S3 internal staging bucket.
+def _get_s3_credentials() -> AWSKeyPair | None:
+ """Get the S3 credentials for the internal staging bucket, or None to authenticate keylessly.
- If keyless S3 auth is enabled, we use no credentials as the IAM role will be used to authenticate.
- Otherwise, we use the credentials from the object storage settings.
+ Keyless S3 auth (IAM role) returns None. A partially configured environment counts as keyless
+ rather than yielding half a key pair.
"""
- use_keyless_s3_auth = not _uses_object_storage_endpoint()
- if use_keyless_s3_auth:
- aws_access_key_id = None
- aws_secret_access_key = None
- else:
- aws_access_key_id = settings.OBJECT_STORAGE_ACCESS_KEY_ID
- aws_secret_access_key = settings.OBJECT_STORAGE_SECRET_ACCESS_KEY
- return aws_access_key_id, aws_secret_access_key
+ if not _uses_object_storage_endpoint():
+ return None
+ access_key_id = settings.OBJECT_STORAGE_ACCESS_KEY_ID
+ secret_access_key = settings.OBJECT_STORAGE_SECRET_ACCESS_KEY
+ if access_key_id is None or secret_access_key is None:
+ if (access_key_id is None) != (secret_access_key is None):
+ LOGGER.warning(
+ "Only one of OBJECT_STORAGE_ACCESS_KEY_ID and OBJECT_STORAGE_SECRET_ACCESS_KEY is set, "
+ "falling back to keyless S3 auth"
+ )
+ return None
+ return AWSKeyPair.unsafe_from_strings(access_key_id, secret_access_key)
def socket_factory(addr_info):
@@ -151,12 +156,12 @@ class AIOHTTPSession(BaseAIOHTTPSession):
@asynccontextmanager
async def get_s3_client():
"""Async context manager for creating and managing an S3 client."""
- aws_access_key_id, aws_secret_access_key = _get_s3_credentials()
+ credentials = _get_s3_credentials()
session = aioboto3.Session()
async with session.client(
"s3",
- aws_access_key_id=aws_access_key_id,
- aws_secret_access_key=aws_secret_access_key,
+ aws_access_key_id=credentials.access_key_id if credentials else None,
+ aws_secret_access_key=credentials.secret_access_key if credentials else None,
endpoint_url=_get_s3_endpoint_url(),
region_name=settings.BATCH_EXPORT_OBJECT_STORAGE_REGION,
# aiobotocore defaults keepalive_timeout to 12 seconds, which can be low for
@@ -410,11 +415,9 @@ async def _get_query(
num_partitions = num_partitions or settings.BATCH_EXPORT_CLICKHOUSE_S3_PARTITIONS
assert num_partitions is not None # to satisfy mypy
- aws_access_key_id, aws_secret_access_key = _get_s3_credentials()
s3_function = get_s3_function_call(
s3_folder=s3_staging_folder_url,
- s3_key=aws_access_key_id,
- s3_secret=aws_secret_access_key,
+ credentials=_get_s3_credentials(),
num_partitions=num_partitions,
)
@@ -611,13 +614,11 @@ async def _write_batch_export_record_batches_to_internal_stage(
query_parameters["interval_end"] = interval_end.strftime("%Y-%m-%d %H:%M:%S.%f")
if isinstance(query_or_model, RecordBatchModel):
- aws_access_key_id, aws_secret_access_key = _get_s3_credentials()
query, query_parameters = await query_or_model.as_insert_into_s3_query_with_parameters(
data_interval_start=interval_start,
data_interval_end=interval_end,
s3_folder=s3_staging_folder_url,
- s3_key=aws_access_key_id,
- s3_secret=aws_secret_access_key,
+ credentials=_get_s3_credentials(),
num_partitions=num_partitions or settings.BATCH_EXPORT_CLICKHOUSE_S3_PARTITIONS,
)
query_settings = query_or_model.get_clickhouse_request_settings()
diff --git a/products/batch_exports/backend/temporal/record_batch_model.py b/products/batch_exports/backend/temporal/record_batch_model.py
index 8bc64cf2057a..8e02350eeb52 100644
--- a/products/batch_exports/backend/temporal/record_batch_model.py
+++ b/products/batch_exports/backend/temporal/record_batch_model.py
@@ -12,6 +12,7 @@ from posthog.hogql.visitor import clone_expr
from posthog.clickhouse import query_tagging
from posthog.clickhouse.query_tagging import Product
+from posthog.credentials import AWSKeyPair
from posthog.models import Team
from posthog.sync import database_sync_to_async
from posthog.temporal.common.clickhouse import get_client
@@ -133,13 +134,12 @@ class RecordBatchModel(abc.ABC):
data_interval_start: dt.datetime | None,
data_interval_end: dt.datetime,
s3_folder: str,
- s3_key: str | None,
- s3_secret: str | None,
+ credentials: AWSKeyPair | None,
num_partitions: int,
) -> tuple[Query, QueryParameters]:
"""Produce an `INSERT INTO FUNCTION s3(...)` query and its ClickHouse parameters."""
printed, parameters = await self._print_query(data_interval_start, data_interval_end, output_format=None)
- s3_function = sql.get_s3_function_call(s3_folder, s3_key, s3_secret, num_partitions)
+ s3_function = sql.get_s3_function_call(s3_folder, credentials, num_partitions)
insert_query = f"""
INSERT INTO FUNCTION {s3_function}
{printed}
diff --git a/products/batch_exports/backend/temporal/sql.py b/products/batch_exports/backend/temporal/sql.py
index 572b9d1da7f2..b8cb0160cfa8 100644
--- a/products/batch_exports/backend/temporal/sql.py
+++ b/products/batch_exports/backend/temporal/sql.py
@@ -4,8 +4,10 @@ from posthog.hogql import ast
from posthog.hogql.constants import HogQLQuerySettings
from posthog.hogql.parser import parse_expr
+from posthog.credentials import AWSKeyPair
-def get_s3_function_call(s3_folder: str, s3_key: str | None, s3_secret: str | None, num_partitions: int) -> str:
+
+def get_s3_function_call(s3_folder: str, credentials: AWSKeyPair | None, num_partitions: int) -> str:
"""Generate the s3() function call for ClickHouse INSERT queries.
When using keyless S3 auth (IAM roles), we omit credentials and ClickHouse uses the
@@ -15,10 +17,10 @@ def get_s3_function_call(s3_folder: str, s3_key: str | None, s3_secret: str | No
parameter substitution, so %% produces a literal % in the final query.
"""
s3_url = f"{s3_folder}/export_{{{{_partition_id}}}}.arrow"
- if s3_key is not None and s3_secret is not None:
+ if credentials is not None:
# Escape single quotes by doubling them (ClickHouse SQL escaping)
- escaped_key = s3_key.replace("'", "''")
- escaped_secret = s3_secret.replace("'", "''")
+ escaped_key = credentials.access_key_id.replace("'", "''")
+ escaped_secret = credentials.secret_access_key.replace("'", "''")
s3_call = f"s3('{s3_url}', '{escaped_key}', '{escaped_secret}', 'ArrowStream')"
else:
s3_call = f"s3('{s3_url}', 'ArrowStream')"
diff --git a/products/batch_exports/backend/tests/temporal/test_record_batch_model.py b/products/batch_exports/backend/tests/temporal/test_record_batch_model.py
index 28aa13f42444..71a9da6d98db 100644
--- a/products/batch_exports/backend/tests/temporal/test_record_batch_model.py
+++ b/products/batch_exports/backend/tests/temporal/test_record_batch_model.py
@@ -3,6 +3,7 @@ import pytest
from posthog.hogql.hogql import ast
from posthog.hogql.printer import prepare_ast_for_printing, print_prepared_ast
+from posthog.credentials import AWSKeyPair
from posthog.sync import database_sync_to_async
from products.batch_exports.backend.hogql_source import UnsupportedHogQLQueryError
@@ -103,8 +104,7 @@ class TestSessionsRecordBatchModel:
data_interval_start=data_interval_start,
data_interval_end=data_interval_end,
s3_folder="https://test-bucket.s3.amazonaws.com/test-prefix",
- s3_key="test-key",
- s3_secret="test-secret",
+ credentials=AWSKeyPair.unsafe_from_strings("test-key", "test-secret"),
num_partitions=5,
)
@@ -145,8 +145,7 @@ class TestSessionsRecordBatchModel:
data_interval_start=data_interval_start,
data_interval_end=data_interval_end,
s3_folder="https://test-bucket.s3.amazonaws.com/test-prefix",
- s3_key=None,
- s3_secret=None,
+ credentials=None,
num_partitions=5,
)
@@ -180,8 +179,7 @@ class TestHogQLQueryRecordBatchModel:
data_interval_start=data_interval_start,
data_interval_end=data_interval_end,
s3_folder="https://test-bucket.s3.amazonaws.com/test-prefix",
- s3_key="test-key",
- s3_secret="test-secret",
+ credentials=AWSKeyPair.unsafe_from_strings("test-key", "test-secret"),
num_partitions=5,
)
diff --git a/products/batch_exports/backend/tests/test_internal_stage_storage_config.py b/products/batch_exports/backend/tests/test_internal_stage_storage_config.py
index 2e11d9a9ccce..39b3a59b8286 100644
--- a/products/batch_exports/backend/tests/test_internal_stage_storage_config.py
+++ b/products/batch_exports/backend/tests/test_internal_stage_storage_config.py
@@ -2,6 +2,8 @@ import pytest
from django.test.utils import override_settings
+from posthog.credentials import AWSKeyPair
+
from products.batch_exports.backend.temporal.pipeline.internal_stage import (
_get_s3_credentials,
_get_s3_endpoint_url,
@@ -49,7 +51,33 @@ def test_internal_stage_uses_object_storage_endpoint_for_self_hosted_local_and_t
_get_test_s3_staging_folder_url()
== f"{OBJECT_STORAGE_ENDPOINT}/{OBJECT_STORAGE_BUCKET}/{EXPECTED_STAGE_FOLDER}"
)
- assert _get_s3_credentials() == (OBJECT_STORAGE_ACCESS_KEY_ID, OBJECT_STORAGE_SECRET_ACCESS_KEY)
+ assert _get_s3_credentials() == AWSKeyPair.unsafe_from_strings(
+ OBJECT_STORAGE_ACCESS_KEY_ID, OBJECT_STORAGE_SECRET_ACCESS_KEY
+ )
+
+
+ "access_key_id,secret_access_key",
+ [
+ (OBJECT_STORAGE_ACCESS_KEY_ID, None),
+ (None, OBJECT_STORAGE_SECRET_ACCESS_KEY),
+ (None, None),
+ ],
+)
+def test_partially_configured_object_storage_is_keyless(
+ access_key_id: str | None, secret_access_key: str | None
+) -> None:
+ # Half a pair would reach boto3 as partial credentials and raise, so it counts as keyless.
+ with override_settings(
+ CLOUD_DEPLOYMENT=None,
+ DEBUG=False,
+ TEST=False,
+ BATCH_EXPORT_OBJECT_STORAGE_ENDPOINT=OBJECT_STORAGE_ENDPOINT,
+ BATCH_EXPORT_INTERNAL_STAGING_BUCKET=OBJECT_STORAGE_BUCKET,
+ OBJECT_STORAGE_ACCESS_KEY_ID=access_key_id,
+ OBJECT_STORAGE_SECRET_ACCESS_KEY=secret_access_key,
+ ):
+ assert _get_s3_credentials() is None
@pytest.mark.parametrize("cloud_deployment", ["DEV", "US", "EU", "E2E"])
@@ -65,7 +93,7 @@ def test_internal_stage_uses_aws_s3_for_cloud(cloud_deployment: str) -> None:
_get_test_s3_staging_folder_url()
== f"https://{OBJECT_STORAGE_BUCKET}.s3.{OBJECT_STORAGE_REGION}.amazonaws.com/{EXPECTED_STAGE_FOLDER}"
)
- assert _get_s3_credentials() == (None, None)
+ assert _get_s3_credentials() is None
def test_s3_endpoint_url_self_hosted_uses_configured_endpoint_not_localhost() -> None:
diff --git a/products/mcp_store/backend/oauth.py b/products/mcp_store/backend/oauth.py
index 566705fca5b0..d4f22d0b8621 100644
--- a/products/mcp_store/backend/oauth.py
+++ b/products/mcp_store/backend/oauth.py
@@ -2,7 +2,9 @@ import time
import base64
import hashlib
import secrets
+import dataclasses
from collections.abc import Callable
+from dataclasses import dataclass
from urllib.parse import urlparse
import requests
@@ -301,12 +303,19 @@ def discover_oauth_metadata(server_url: str) -> dict:
return metadata
-def register_dcr_client(metadata: dict, redirect_uri: str) -> tuple[str, str | None, str]:
+@dataclass(frozen=True)
+class DcrClientRegistration:
+ client_id: str
+ client_secret: str | None = dataclasses.field(repr=False)
+ token_endpoint_auth_method: str
+
+
+def register_dcr_client(metadata: dict, redirect_uri: str) -> DcrClientRegistration:
"""Run RFC 7591 Dynamic Client Registration.
- Returns ``(client_id, client_secret, token_endpoint_auth_method)``. Some
- servers (e.g. Supabase) register a confidential client even when we ask for
- a public one, so the auth method is persisted with the minted client.
+ Some servers (e.g. Supabase) register a confidential client even when we
+ ask for a public one, so the auth method is persisted with the minted
+ client.
"""
registration_endpoint = metadata.get("registration_endpoint")
if not registration_endpoint:
@@ -355,14 +364,24 @@ def register_dcr_client(metadata: dict, redirect_uri: str) -> tuple[str, str | N
raise ValueError("DCR response registered a confidential client without client_secret")
client_secret = returned_secret if returned_secret and returned_auth_method != "none" else None
- return client_id, client_secret, returned_auth_method
+ return DcrClientRegistration(
+ client_id=client_id,
+ client_secret=client_secret,
+ token_endpoint_auth_method=returned_auth_method,
+ )
+
+
+@dataclass(frozen=True)
+class PkcePair:
+ code_verifier: str = dataclasses.field(repr=False)
+ code_challenge: str
-def generate_pkce() -> tuple[str, str]:
+def generate_pkce() -> PkcePair:
code_verifier = secrets.token_urlsafe(64)
digest = hashlib.sha256(code_verifier.encode("ascii")).digest()
code_challenge = base64.urlsafe_b64encode(digest).rstrip(b"=").decode("ascii")
- return code_verifier, code_challenge
+ return PkcePair(code_verifier=code_verifier, code_challenge=code_challenge)
def is_token_expiring(sensitive: dict) -> bool:
diff --git a/products/mcp_store/backend/presentation/views.py b/products/mcp_store/backend/presentation/views.py
index d3ec10149d46..3b317c47626a 100644
--- a/products/mcp_store/backend/presentation/views.py
+++ b/products/mcp_store/backend/presentation/views.py
@@ -43,6 +43,7 @@ from posthog.security.url_validation import is_url_allowed
from ..models import MCPOAuthState, MCPServerInstallation, MCPServerInstallationTool, MCPServerTemplate, SensitiveConfig
from ..oauth import (
+ DcrClientRegistration,
OAuthAuthorizeURLError,
OAuthTokenExchangeError,
discover_oauth_metadata,
@@ -575,7 +576,7 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet
def _register_dcr_client_or_raise(
self, metadata: dict, redirect_uri: str, *, server_url: str = ""
- ) -> tuple[str, str | None, str]:
+ ) -> DcrClientRegistration:
log_context = {"error": ""} if not server_url else {"server_url": server_url, "error": ""}
try:
return register_dcr_client(metadata, redirect_uri)
@@ -871,7 +872,7 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet
return Response({"detail": "OAuth discovery failed."}, status=status.HTTP_400_BAD_REQUEST)
try:
- client_id, dcr_client_secret, token_endpoint_auth_method = self._register_dcr_client_or_raise(
+ registration = self._register_dcr_client_or_raise(
metadata,
redirect_uri,
server_url=template.url,
@@ -887,6 +888,7 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet
if created:
installation.delete()
return Response({"detail": "OAuth registration failed."}, status=status.HTTP_400_BAD_REQUEST)
+ client_id = registration.client_id
# Cache the discovered metadata and minted per-user client on the
# installation so reconnect/refresh can reuse them. Nothing is
@@ -894,9 +896,9 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet
sensitive = dict(installation.sensitive_configuration or {})
sensitive["dcr_client_id"] = client_id
sensitive["dcr_is_user_provided"] = False
- sensitive["dcr_token_endpoint_auth_method"] = token_endpoint_auth_method
- if dcr_client_secret:
- sensitive["dcr_client_secret"] = dcr_client_secret
+ sensitive["dcr_token_endpoint_auth_method"] = registration.token_endpoint_auth_method
+ if registration.client_secret:
+ sensitive["dcr_client_secret"] = registration.client_secret
else:
sensitive.pop("dcr_client_secret", None)
installation.oauth_metadata = metadata
@@ -921,7 +923,7 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet
# _template_uses_dcr guarantees client_id is present here.
client_id = template.oauth_credentials["client_id"]
- code_verifier, code_challenge = generate_pkce()
+ pkce = generate_pkce()
token = secrets.token_urlsafe(32)
_create_oauth_state(
request,
@@ -929,7 +931,7 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet
token,
install_source,
posthog_code_callback_url,
- pkce_verifier=code_verifier,
+ pkce_verifier=pkce.code_verifier,
template=template,
)
@@ -939,7 +941,7 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet
client_id=client_id,
redirect_uri=redirect_uri,
state_token=token,
- code_challenge=code_challenge,
+ code_challenge=pkce.code_challenge,
)
except OAuthAuthorizeURLError as exc:
logger.warning(
@@ -1132,9 +1134,7 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet
)
else:
try:
- client_id, dcr_client_secret, token_endpoint_auth_method = self._register_dcr_client_or_raise(
- metadata, redirect_uri, server_url=mcp_url
- )
+ registration = self._register_dcr_client_or_raise(metadata, redirect_uri, server_url=mcp_url)
except DCRNotSupportedError:
if created:
installation.delete()
@@ -1146,6 +1146,9 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet
if created:
installation.delete()
return Response({"detail": "OAuth registration failed."}, status=status.HTTP_400_BAD_REQUEST)
+ client_id = registration.client_id
+ dcr_client_secret = registration.client_secret
+ token_endpoint_auth_method = registration.token_endpoint_auth_method
dcr_is_user_provided = False
# Cache the (non-secret) discovery metadata and the per-user creds on
@@ -1182,7 +1185,7 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet
]
)
- code_verifier, code_challenge = generate_pkce()
+ pkce = generate_pkce()
token = secrets.token_urlsafe(32)
_create_oauth_state(
request,
@@ -1190,7 +1193,7 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet
token,
install_source,
posthog_code_callback_url,
- pkce_verifier=code_verifier,
+ pkce_verifier=pkce.code_verifier,
template=None,
)
@@ -1200,7 +1203,7 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet
client_id=client_id,
redirect_uri=redirect_uri,
state_token=token,
- code_challenge=code_challenge,
+ code_challenge=pkce.code_challenge,
)
except OAuthAuthorizeURLError:
if created:
@@ -1316,7 +1319,7 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet
client_id = template.oauth_credentials["client_id"]
redirect_uri = _get_oauth_redirect_uri()
- code_verifier, code_challenge = generate_pkce()
+ pkce = generate_pkce()
token = secrets.token_urlsafe(32)
_create_oauth_state(
request,
@@ -1324,7 +1327,7 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet
token,
install_source,
posthog_code_callback_url,
- pkce_verifier=code_verifier,
+ pkce_verifier=pkce.code_verifier,
template=template,
)
try:
@@ -1333,7 +1336,7 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet
client_id=client_id,
redirect_uri=redirect_uri,
state_token=token,
- code_challenge=code_challenge,
+ code_challenge=pkce.code_challenge,
)
except OAuthAuthorizeURLError as exc:
logger.warning(
@@ -1399,7 +1402,7 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet
)
redirect_uri = _get_oauth_redirect_uri()
- code_verifier, code_challenge = generate_pkce()
+ pkce = generate_pkce()
token = secrets.token_urlsafe(32)
_create_oauth_state(
request,
@@ -1407,7 +1410,7 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet
token,
install_source,
posthog_code_callback_url,
- pkce_verifier=code_verifier,
+ pkce_verifier=pkce.code_verifier,
template=None,
)
try:
@@ -1416,7 +1419,7 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet
client_id=client_id,
redirect_uri=redirect_uri,
state_token=token,
- code_challenge=code_challenge,
+ code_challenge=pkce.code_challenge,
)
except OAuthAuthorizeURLError:
return Response({"detail": "Authorization endpoint must use HTTPS"}, status=status.HTTP_400_BAD_REQUEST)
diff --git a/products/mcp_store/backend/probe.py b/products/mcp_store/backend/probe.py
index bbc904ddf8e6..b6f044561e3a 100644
--- a/products/mcp_store/backend/probe.py
+++ b/products/mcp_store/backend/probe.py
@@ -234,7 +234,7 @@ def _register_probe_client(metadata: dict, result: ProbeResult) -> str | None:
if not metadata.get("registration_endpoint"):
return None
try:
- client_id, _client_secret, _auth_method = register_dcr_client(metadata, _probe_redirect_uri())
+ registration = register_dcr_client(metadata, _probe_redirect_uri())
except ValueError as exc:
# Mirrors views._register_dcr_client_or_raise: ValueError means DCR isn't supported.
result.errors.append(f"Dynamic Client Registration not supported: {exc}")
@@ -242,7 +242,7 @@ def _register_probe_client(metadata: dict, result: ProbeResult) -> str | None:
except Exception as exc:
result.errors.append(f"Dynamic Client Registration failed: {exc}")
return None
- return client_id
+ return registration.client_id
def _build_authorize_url(metadata: dict, client_id: str) -> str | None:
@@ -250,7 +250,7 @@ def _build_authorize_url(metadata: dict, client_id: str) -> str | None:
if not isinstance(authorization_endpoint, str) or not authorization_endpoint:
return None
- _code_verifier, code_challenge = generate_pkce()
+ code_challenge = generate_pkce().code_challenge
query_params = {
"client_id": client_id,
"redirect_uri": _probe_redirect_uri(),
diff --git a/products/mcp_store/backend/test/test_api.py b/products/mcp_store/backend/test/test_api.py
index bfddf79bdec4..a7d29727b934 100644
--- a/products/mcp_store/backend/test/test_api.py
+++ b/products/mcp_store/backend/test/test_api.py
@@ -16,6 +16,7 @@ from rest_framework.test import APIClient
from posthog.models.oauth import OAuthAccessToken, OAuthApplication
from products.mcp_store.backend.models import MCPOAuthState, MCPServerInstallation, MCPServerTemplate
+from products.mcp_store.backend.oauth import DcrClientRegistration
from products.mcp_store.backend.presentation.views import _is_valid_posthog_code_callback_url
ALLOW_URL = patch("products.mcp_store.backend.presentation.views.is_url_allowed", return_value=(True, None))
@@ -844,7 +845,9 @@ class TestOAuthCallback(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
@patch("products.mcp_store.backend.presentation.views.discover_oauth_metadata")
@patch(
"products.mcp_store.backend.presentation.views.register_dcr_client",
- return_value=("dcr-client-id", None, "none"),
+ return_value=DcrClientRegistration(
+ client_id="dcr-client-id", client_secret=None, token_endpoint_auth_method="none"
+ ),
)
def test_install_custom_populates_created_by(self, _mock_dcr, mock_discover, _allow):
"""install_custom path must stamp created_by on the MCPOAuthState row."""
@@ -916,7 +919,9 @@ class TestOAuthIssuerSpoofingProtection(ClickhouseTestMixin, APIBaseTest, QueryM
"token_endpoint": "https://auth.legit.com/token",
"registration_endpoint": "https://auth.legit.com/register",
}
- mock_dcr.return_value = ("per-user-dcr-client", None, "none")
+ mock_dcr.return_value = DcrClientRegistration(
+ client_id="per-user-dcr-client", client_secret=None, token_endpoint_auth_method="none"
+ )
response = self.client.post(
f"/api/environments/{self.team.id}/mcp_server_installations/install_custom/",
@@ -950,7 +955,11 @@ class TestOAuthIssuerSpoofingProtection(ClickhouseTestMixin, APIBaseTest, QueryM
"token_endpoint": "https://auth.legit.com/token",
"registration_endpoint": "https://auth.legit.com/register",
}
- mock_dcr.return_value = ("dcr-minted-client", "dcr-minted-secret", "client_secret_post")
+ mock_dcr.return_value = DcrClientRegistration(
+ client_id="dcr-minted-client",
+ client_secret="dcr-minted-secret",
+ token_endpoint_auth_method="client_secret_post",
+ )
response = self.client.post(
f"/api/environments/{self.team.id}/mcp_server_installations/install_custom/",
@@ -1049,7 +1058,9 @@ class TestOAuthIssuerSpoofingProtection(ClickhouseTestMixin, APIBaseTest, QueryM
"token_endpoint": "https://auth.legit.com/token",
"registration_endpoint": "https://auth.legit.com/register",
}
- mock_dcr.return_value = ("dcr-minted-client", None, "none")
+ mock_dcr.return_value = DcrClientRegistration(
+ client_id="dcr-minted-client", client_secret=None, token_endpoint_auth_method="none"
+ )
response = self.client.post(
f"/api/environments/{self.team.id}/mcp_server_installations/install_custom/",
@@ -1074,7 +1085,9 @@ class TestOAuthIssuerSpoofingProtection(ClickhouseTestMixin, APIBaseTest, QueryM
@ALLOW_URL
@patch(
"products.mcp_store.backend.presentation.views.register_dcr_client",
- return_value=("new-dcr-client", None, "none"),
+ return_value=DcrClientRegistration(
+ client_id="new-dcr-client", client_secret=None, token_endpoint_auth_method="none"
+ ),
)
@patch("products.mcp_store.backend.presentation.views.discover_oauth_metadata")
def test_reinstall_clears_stale_tokens_and_flags_reauth(self, mock_discover, _mock_dcr, _allow):
@@ -1383,7 +1396,9 @@ class TestInstallTemplateAPI(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest
@patch(
"products.mcp_store.backend.presentation.views.register_dcr_client",
- return_value=("minted-per-user-client", None, "none"),
+ return_value=DcrClientRegistration(
+ client_id="minted-per-user-client", client_secret=None, token_endpoint_auth_method="none"
+ ),
)
@patch(
"products.mcp_store.backend.presentation.views.discover_oauth_metadata",
diff --git a/products/mcp_store/backend/test/test_oauth.py b/products/mcp_store/backend/test/test_oauth.py
index 69ab6840461e..f37ca75aa39a 100644
--- a/products/mcp_store/backend/test/test_oauth.py
+++ b/products/mcp_store/backend/test/test_oauth.py
@@ -11,6 +11,7 @@ from parameterized import parameterized
from products.mcp_store.backend.models import MCPServerInstallation, MCPServerTemplate
from products.mcp_store.backend.oauth import (
TIMEOUT,
+ DcrClientRegistration,
OAuthTokenExchangeError,
SSRFBlockedError,
TokenRefreshError,
@@ -942,12 +943,12 @@ class TestRegisterDCRClient(SimpleTestCase):
(
"drops_secret_when_server_honors_public_client",
{"client_id": "abc", "token_endpoint_auth_method": "none"},
- ("abc", None, "none"),
+ DcrClientRegistration(client_id="abc", client_secret=None, token_endpoint_auth_method="none"),
),
(
"drops_secret_when_server_omits_it",
{"client_id": "abc", "token_endpoint_auth_method": "none", "client_secret": ""},
- ("abc", None, "none"),
+ DcrClientRegistration(client_id="abc", client_secret=None, token_endpoint_auth_method="none"),
),
(
"keeps_secret_when_server_registered_confidential_client_post",
@@ -956,7 +957,9 @@ class TestRegisterDCRClient(SimpleTestCase):
"client_secret": "minted-secret",
"token_endpoint_auth_method": "client_secret_post",
},
- ("abc", "minted-secret", "client_secret_post"),
+ DcrClientRegistration(
+ client_id="abc", client_secret="minted-secret", token_endpoint_auth_method="client_secret_post"
+ ),
),
(
"keeps_secret_when_server_registered_confidential_client_basic",
@@ -965,12 +968,16 @@ class TestRegisterDCRClient(SimpleTestCase):
"client_secret": "minted-secret",
"token_endpoint_auth_method": "client_secret_basic",
},
- ("abc", "minted-secret", "client_secret_basic"),
+ DcrClientRegistration(
+ client_id="abc", client_secret="minted-secret", token_endpoint_auth_method="client_secret_basic"
+ ),
),
(
"keeps_secret_with_basic_auth_when_auth_method_unspecified",
{"client_id": "abc", "client_secret": "minted-secret"},
- ("abc", "minted-secret", "client_secret_basic"),
+ DcrClientRegistration(
+ client_id="abc", client_secret="minted-secret", token_endpoint_auth_method="client_secret_basic"
+ ),
),
]
)
@@ -1015,7 +1022,9 @@ class TestRegisterDCRClient(SimpleTestCase):
"https://app.posthog.com/callback",
)
- assert result == ("abc", "minted-secret", "client_secret_post")
+ assert result == DcrClientRegistration(
+ client_id="abc", client_secret="minted-secret", token_endpoint_auth_method="client_secret_post"
+ )
payload = mock_post.call_args.kwargs["json"]
assert payload["grant_types"] == ["authorization_code", "refresh_token"]
assert payload["token_endpoint_auth_method"] == "client_secret_post"
@@ -1043,7 +1052,9 @@ class TestRegisterDCRClient(SimpleTestCase):
"https://app.posthog.com/callback",
)
- assert result == ("abc", "minted-secret", "client_secret_basic")
+ assert result == DcrClientRegistration(
+ client_id="abc", client_secret="minted-secret", token_endpoint_auth_method="client_secret_basic"
+ )
assert mock_post.call_args.kwargs["json"]["token_endpoint_auth_method"] == "client_secret_basic"
def test_scope_selection_prefers_protected_resource_scopes(self):
diff --git a/products/slack_app/backend/api.py b/products/slack_app/backend/api.py
index 79d45d441fed..3ce5f2883bda 100644
--- a/products/slack_app/backend/api.py
+++ b/products/slack_app/backend/api.py
@@ -651,7 +651,7 @@ def does_other_region_claim_workspace(*, slack_team_id: str, kinds: list[str], i
body = json.dumps({"slack_team_id": slack_team_id, "kinds": kinds}).encode("utf-8")
signing_secret = SlackIntegration.slack_config()["SLACK_APP_SIGNING_SECRET"]
- signature, ts = sign_slack_request(body, signing_secret)
+ signed = sign_slack_request(body, signing_secret)
try:
response = requests.post(
@@ -659,8 +659,8 @@ def does_other_region_claim_workspace(*, slack_team_id: str, kinds: list[str], i
data=body,
headers={
"Content-Type": "application/json",
- "X-Slack-Signature": signature,
- "X-Slack-Request-Timestamp": ts,
+ "X-Slack-Signature": signed.signature,
+ "X-Slack-Request-Timestamp": signed.timestamp,
REGION_PROXY_HEADER: "1",
},
timeout=WORKSPACE_CLAIMS_TIMEOUT_SECONDS,
diff --git a/products/slack_app/backend/tests/test_channel_approval_interactivity.py b/products/slack_app/backend/tests/test_channel_approval_interactivity.py
index 2a8c8030af54..37b4f684aa7b 100644
--- a/products/slack_app/backend/tests/test_channel_approval_interactivity.py
+++ b/products/slack_app/backend/tests/test_channel_approval_interactivity.py
@@ -71,12 +71,12 @@ class _ChannelApprovalTestBase(TestCase):
payload = {"team": {"id": self.slack_team_id}, **payload}
body_str = f"payload={json.dumps(payload)}"
body = body_str.encode()
- signature, ts = sign_slack_request(body, self.signing_secret)
+ signed = sign_slack_request(body, self.signing_secret)
return self.client.post(
"/slack/interactivity-callback/",
data=body_str,
content_type="application/x-www-form-urlencoded",
- headers={"x-slack-signature": signature, "x-slack-request-timestamp": ts},
+ headers={"x-slack-signature": signed.signature, "x-slack-request-timestamp": signed.timestamp},
)
def _approve_payload(self, slack_user_id: str) -> dict[str, Any]:
diff --git a/products/slack_app/backend/tests/test_posthog_code_event_handler.py b/products/slack_app/backend/tests/test_posthog_code_event_handler.py
index f47f51ab9dd0..547f7d39a190 100644
--- a/products/slack_app/backend/tests/test_posthog_code_event_handler.py
+++ b/products/slack_app/backend/tests/test_posthog_code_event_handler.py
@@ -27,13 +27,13 @@ class TestPostHogCodeEventHandler(SimpleTestCase):
def _post_event(self, payload: dict, **extra_headers) -> Any:
body = json.dumps(payload).encode()
- signature, ts = sign_slack_request(body, self.signing_secret)
+ signed = sign_slack_request(body, self.signing_secret)
return self.client.post(
"/slack/event-callback/",
data=body,
content_type="application/json",
- HTTP_X_SLACK_SIGNATURE=signature,
- HTTP_X_SLACK_REQUEST_TIMESTAMP=ts,
+ HTTP_X_SLACK_SIGNATURE=signed.signature,
+ HTTP_X_SLACK_REQUEST_TIMESTAMP=signed.timestamp,
**extra_headers,
)
@@ -54,12 +54,16 @@ class TestPostHogCodeEventHandler(SimpleTestCase):
def test_retry_returns_200(self, mock_config):
mock_config.return_value = {"SLACK_APP_SIGNING_SECRET": self.signing_secret}
body = json.dumps({"type": "event_callback", "event": {"type": "app_mention"}}).encode()
- signature, ts = sign_slack_request(body, self.signing_secret)
+ signed = sign_slack_request(body, self.signing_secret)
response = self.client.post(
"/slack/event-callback/",
data=body,
content_type="application/json",
- headers={"x-slack-signature": signature, "x-slack-request-timestamp": ts, "x-slack-retry-num": "1"},
+ headers={
+ "x-slack-signature": signed.signature,
+ "x-slack-request-timestamp": signed.timestamp,
+ "x-slack-retry-num": "1",
+ },
)
assert response.status_code == 200
@@ -1136,13 +1140,13 @@ class TestChannelApprovalGate(TestCase):
"event": {"type": "app_mention", "channel": "C_EXT", "user": "U123", "ts": "1.0"},
}
body = json.dumps(envelope).encode()
- signature, ts = sign_slack_request(body, "secret")
+ signed = sign_slack_request(body, "secret")
APIClient().post(
"/slack/event-callback/",
data=body,
content_type="application/json",
- HTTP_X_SLACK_SIGNATURE=signature,
- HTTP_X_SLACK_REQUEST_TIMESTAMP=ts,
+ HTTP_X_SLACK_SIGNATURE=signed.signature,
+ HTTP_X_SLACK_REQUEST_TIMESTAMP=signed.timestamp,
)
mock_route.assert_called_once()
diff --git a/products/slack_app/backend/tests/test_posthog_code_interactivity.py b/products/slack_app/backend/tests/test_posthog_code_interactivity.py
index 0b8209cd7f70..8168fc01123d 100644
--- a/products/slack_app/backend/tests/test_posthog_code_interactivity.py
+++ b/products/slack_app/backend/tests/test_posthog_code_interactivity.py
@@ -51,13 +51,13 @@ class TestPostHogCodeInteractivityHandler(TestCase):
payload = {"team": {"id": "T12345"}, **payload}
body_str = f"payload={json.dumps(payload)}"
body = body_str.encode()
- signature, ts = sign_slack_request(body, self.signing_secret)
+ signed = sign_slack_request(body, self.signing_secret)
return self.client.post(
"/slack/interactivity-callback/",
data=body_str,
content_type="application/x-www-form-urlencoded",
- HTTP_X_SLACK_SIGNATURE=signature,
- HTTP_X_SLACK_REQUEST_TIMESTAMP=ts,
+ HTTP_X_SLACK_SIGNATURE=signed.signature,
+ HTTP_X_SLACK_REQUEST_TIMESTAMP=signed.timestamp,
**extra_headers,
)
@@ -112,12 +112,12 @@ class TestRepoPickerOptions(TestCase):
payload = {"team": {"id": "T12345"}, **payload}
body_str = f"payload={json.dumps(payload)}"
body = body_str.encode()
- signature, ts = sign_slack_request(body, self.signing_secret)
+ signed = sign_slack_request(body, self.signing_secret)
return self.client.post(
"/slack/interactivity-callback/",
data=body_str,
content_type="application/x-www-form-urlencoded",
- headers={"x-slack-signature": signature, "x-slack-request-timestamp": ts},
+ headers={"x-slack-signature": signed.signature, "x-slack-request-timestamp": signed.timestamp},
)
@patch("products.slack_app.backend.api._get_full_repo_names")
@@ -658,14 +658,14 @@ class TestInteractivityRegionRouting(TestCase):
payload = {"team": {"id": "T12345"}, **payload}
body_str = f"payload={json.dumps(payload)}"
body = body_str.encode()
- signature, ts = sign_slack_request(body, self.signing_secret)
+ signed = sign_slack_request(body, self.signing_secret)
return self.client.post(
"/slack/interactivity-callback/",
data=body_str,
content_type="application/x-www-form-urlencoded",
HTTP_HOST=host,
- HTTP_X_SLACK_SIGNATURE=signature,
- HTTP_X_SLACK_REQUEST_TIMESTAMP=ts,
+ HTTP_X_SLACK_SIGNATURE=signed.signature,
+ HTTP_X_SLACK_REQUEST_TIMESTAMP=signed.timestamp,
**extra_headers,
)
@@ -918,13 +918,13 @@ class TestSignalsDismissReport(TestCase):
def _post_interactivity(self, payload: dict) -> Any:
body_str = f"payload={json.dumps(payload)}"
- signature, ts = sign_slack_request(body_str.encode(), self.signing_secret)
+ signed = sign_slack_request(body_str.encode(), self.signing_secret)
return self.client.post(
"/slack/interactivity-callback/",
data=body_str,
content_type="application/x-www-form-urlencoded",
- HTTP_X_SLACK_SIGNATURE=signature,
- HTTP_X_SLACK_REQUEST_TIMESTAMP=ts,
+ HTTP_X_SLACK_SIGNATURE=signed.signature,
+ HTTP_X_SLACK_REQUEST_TIMESTAMP=signed.timestamp,
)
@patch("products.slack_app.backend.api._is_org_member")
@@ -1047,13 +1047,13 @@ class TestInsightAlertSnooze(TestCase):
def _post_interactivity(self, payload: dict) -> Any:
body_str = f"payload={json.dumps(payload)}"
- signature, ts = sign_slack_request(body_str.encode(), self.signing_secret)
+ signed = sign_slack_request(body_str.encode(), self.signing_secret)
return self.client.post(
"/slack/interactivity-callback/",
data=body_str,
content_type="application/x-www-form-urlencoded",
- HTTP_X_SLACK_SIGNATURE=signature,
- HTTP_X_SLACK_REQUEST_TIMESTAMP=ts,
+ HTTP_X_SLACK_SIGNATURE=signed.signature,
+ HTTP_X_SLACK_REQUEST_TIMESTAMP=signed.timestamp,
)
@parameterized.expand(["1h", "6h", "1d", "1w"])
diff --git a/products/slack_app/backend/tests/test_workspace_claims.py b/products/slack_app/backend/tests/test_workspace_claims.py
index 0a0210954e18..42d9e239ada0 100644
--- a/products/slack_app/backend/tests/test_workspace_claims.py
+++ b/products/slack_app/backend/tests/test_workspace_claims.py
@@ -32,13 +32,13 @@ class TestSlackWorkspaceClaimsView(TestCase):
def _post(self, payload: dict, signing_secret: str | None = None) -> Any:
body = json.dumps(payload).encode()
- signature, ts = sign_slack_request(body, signing_secret or self.signing_secret)
+ signed = sign_slack_request(body, signing_secret or self.signing_secret)
return self.client.post(
"/slack/workspace/claims/",
data=body,
content_type="application/json",
- HTTP_X_SLACK_SIGNATURE=signature,
- HTTP_X_SLACK_REQUEST_TIMESTAMP=ts,
+ HTTP_X_SLACK_SIGNATURE=signed.signature,
+ HTTP_X_SLACK_REQUEST_TIMESTAMP=signed.timestamp,
)
def test_method_not_allowed(self):
diff --git a/products/slack_app/backend/tests/views/test_slack_command.py b/products/slack_app/backend/tests/views/test_slack_command.py
index 44d9e66f620a..3bef4ef54767 100644
--- a/products/slack_app/backend/tests/views/test_slack_command.py
+++ b/products/slack_app/backend/tests/views/test_slack_command.py
@@ -72,13 +72,13 @@ class _SlashCommandTestBase(TestCase):
def _post_slash_command(self, payload: dict[str, str]) -> Any:
body = urlencode(payload).encode()
- signature, ts = sign_slack_request(body, SIGNING_SECRET)
+ signed = sign_slack_request(body, SIGNING_SECRET)
return self.client.post(
SLASH_COMMAND_PATH,
data=body,
content_type="application/x-www-form-urlencoded",
- HTTP_X_SLACK_SIGNATURE=signature,
- HTTP_X_SLACK_REQUEST_TIMESTAMP=ts,
+ HTTP_X_SLACK_SIGNATURE=signed.signature,
+ HTTP_X_SLACK_REQUEST_TIMESTAMP=signed.timestamp,
)
def _default_payload(self, **overrides: str) -> dict[str, str]:
diff --git a/products/web_analytics/backend/hogql_queries/external/test/test_summary_query_runner.py b/products/web_analytics/backend/hogql_queries/external/test/test_summary_query_runner.py
index 75455779845e..3a9a7acb4f5d 100644
--- a/products/web_analytics/backend/hogql_queries/external/test/test_summary_query_runner.py
+++ b/products/web_analytics/backend/hogql_queries/external/test/test_summary_query_runner.py
@@ -213,18 +213,18 @@ class TestWebAnalyticsExternalSummaryQueryRunner(APIBaseTest):
def test_credential_helper_function_behavior(self):
with patch("posthog.hogql.database.schema.web_analytics_s3.DEBUG", False):
- access_key, access_secret = _get_s3_credentials()
- assert access_key is None
- assert access_secret is None
+ creds = _get_s3_credentials()
+ assert creds.access_key is None
+ assert creds.access_secret is None
with patch("posthog.hogql.database.schema.web_analytics_s3.DEBUG", True):
with patch("posthog.hogql.database.schema.web_analytics_s3.OBJECT_STORAGE_ACCESS_KEY_ID", "debug_key"):
with patch(
"posthog.hogql.database.schema.web_analytics_s3.OBJECT_STORAGE_SECRET_ACCESS_KEY", "debug_secret"
):
- access_key, access_secret = _get_s3_credentials()
- assert access_key == "debug_key"
- assert access_secret == "debug_secret"
+ creds = _get_s3_credentials()
+ assert creds.access_key == "debug_key"
+ assert creds.access_secret == "debug_secret"
def test_s3_table_creation_integration(self):
with patch("posthog.hogql.database.schema.web_analytics_s3.DEBUG", False):