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.

fix(workflows): keep sandbox and production APNs credentials apart (#100858)

Daniel Marchuk0ca57fa73deb
diff --git a/posthog/api/test/test_integration.py b/posthog/api/test/test_integration.py
index 24117fbd0d3e..4cb3f5d64a18 100644
--- a/posthog/api/test/test_integration.py
+++ b/posthog/api/test/test_integration.py
@@ -6539,6 +6539,35 @@ class TestIntegrationRequestAccessAPI(APIBaseTest):
mock_report.assert_not_called()
+class TestApplePushIntegrationAPI(APIBaseTest):
+ @parameterized.expand(
+ [
+ ("numeric_team_id", "team_id_apple", 12345),
+ ("object_signing_key", "signing_key", {"pem": "-----BEGIN PRIVATE KEY-----"}),
+ ]
+ )
+ def test_rejects_a_config_field_that_is_not_a_string(self, _name, field, value):
+ # `config` is a JSON field, so nothing types what a client posts into it. A wrong type has
+ # to read as a validation error, not as a server error.
+ response = self.client.post(
+ f"/api/environments/{self.team.pk}/integrations",
+ {
+ "kind": "apns",
+ "config": {
+ "signing_key": "-----BEGIN PRIVATE KEY-----\nfake\n-----END PRIVATE KEY-----",
+ "key_id": "KEY1",
+ "team_id_apple": "TEAM123",
+ "bundle_id": "com.example.app",
+ field: value,
+ },
+ },
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content
+ assert not Integration.objects.filter(team=self.team, kind="apns").exists()
+
+
class TestPushIdentityVerificationAPI(APIBaseTest):
def setUp(self):
super().setUp()
diff --git a/posthog/management/commands/normalize_apns_integrations.py b/posthog/management/commands/normalize_apns_integrations.py
new file mode 100644
index 000000000000..584a444ef409
--- /dev/null
+++ b/posthog/management/commands/normalize_apns_integrations.py
@@ -0,0 +1,207 @@
+from collections.abc import Iterator
+from typing import Any
+
+from django.core.management.base import BaseCommand
+
+import structlog
+
+from posthog.dataclasses import frozen
+from posthog.models.integration import Integration
+from posthog.models.integration.push import apns_integration_id
+
+logger = structlog.get_logger(__name__)
+
+
+@frozen
+class ApnsRowChange:
+ """What one APNs credential row needs, or why it was left alone."""
+
+ team_id: int
+ integration_id: str
+ new_integration_id: str | None = None
+ strips_config: bool = False
+ strips_signing_key: bool = False
+ blocked_by_existing_row: bool = False
+ unreadable: bool = False
+
+ @property
+ def changes_anything(self) -> bool:
+ return bool(self.new_integration_id) or self.strips_config or self.strips_signing_key
+
+
+def apns_environment(integration: Integration) -> str | None:
+ config = integration.config
+ return config.get("environment") if isinstance(config, dict) else None
+
+
+def sorted_apns_integrations() -> list[Integration]:
+ # Sandbox rows move first. A production row that only needs whitespace stripped can be waiting
+ # for the bare id a sandbox row still holds, and it would keep the whitespace if it were read
+ # first.
+ return sorted(
+ Integration.objects.filter(kind="apns"),
+ key=lambda integration: apns_environment(integration) != "sandbox",
+ )
+
+
+def normalize_one_apns_integration(
+ integration: Integration, occupied: dict[tuple[int, str], int], *, dry_run: bool
+) -> ApnsRowChange | None:
+ config: dict[str, Any] = dict(integration.config or {})
+ team_id_apple = config.get("team_id")
+ bundle_id = config.get("bundle_id")
+ key_id = config.get("key_id")
+
+ # The create path took any truthy JSON value for these until now, so a stored value is not
+ # always a string. A row holding a number or a list has no id to compute, so it keeps the row
+ # it has and this names the team.
+ if not isinstance(team_id_apple, str) or not isinstance(bundle_id, str):
+ return ApnsRowChange(
+ team_id=integration.team_id,
+ integration_id=integration.integration_id,
+ unreadable=True,
+ )
+
+ team_id_apple = team_id_apple.strip()
+ bundle_id = bundle_id.strip()
+ if isinstance(key_id, str):
+ key_id = key_id.strip()
+ if not team_id_apple or not bundle_id:
+ return ApnsRowChange(
+ team_id=integration.team_id,
+ integration_id=integration.integration_id,
+ unreadable=True,
+ )
+
+ update_fields = []
+
+ # A leading space breaks ES256 signing outright, so a credential stored with one has never
+ # been able to send. Trailing whitespace is tolerated by the signer but is stripped with it.
+ #
+ # `sensitive_config` sets `ignore_decrypt_errors`, so a row written under a key we no longer
+ # hold reads back as the raw ciphertext string, not a dict. Such a row keeps the key it has:
+ # the value is unreadable, it carries no whitespace to strip, and saving it would add a
+ # second layer of encryption over the first.
+ stored_sensitive_config = integration.sensitive_config
+ signing_key = stored_sensitive_config.get("signing_key") if isinstance(stored_sensitive_config, dict) else None
+ strips_signing_key = False
+ if isinstance(signing_key, str) and signing_key != signing_key.strip():
+ strips_signing_key = True
+ integration.sensitive_config = {**stored_sensitive_config, "signing_key": signing_key.strip()}
+ update_fields.append("sensitive_config")
+
+ strips_config = (config.get("team_id"), config.get("bundle_id"), config.get("key_id")) != (
+ team_id_apple,
+ bundle_id,
+ key_id,
+ )
+ if strips_config:
+ config.update({"team_id": team_id_apple, "bundle_id": bundle_id, "key_id": key_id})
+ integration.config = config
+ update_fields.append("config")
+
+ wanted_id = apns_integration_id(team_id_apple, bundle_id, config.get("environment") or "")
+ # `occupied` tracks the ids this run has already moved, so a dry run reports the same result as
+ # a real one. Reading the database instead would still see a row at the id a sandbox row is
+ # about to give up, and call the production row blocked.
+ holder = occupied.get((integration.team_id, wanted_id))
+ taken = holder is not None and holder != integration.pk
+ new_integration_id = None
+ if integration.integration_id != wanted_id and not taken:
+ new_integration_id = wanted_id
+ occupied.pop((integration.team_id, integration.integration_id), None)
+ occupied[(integration.team_id, wanted_id)] = integration.pk
+ integration.integration_id = wanted_id
+ update_fields.append("integration_id")
+
+ change = ApnsRowChange(
+ team_id=integration.team_id,
+ integration_id=integration.integration_id if new_integration_id is None else wanted_id,
+ new_integration_id=new_integration_id,
+ strips_config=strips_config,
+ strips_signing_key=strips_signing_key,
+ # Two rows of one environment whose ids differ only by whitespace. Deleting either one
+ # drops a credential a team may still send with, so both stay and this names the team.
+ blocked_by_existing_row=taken and integration.integration_id != wanted_id,
+ )
+ if not update_fields:
+ return change if change.blocked_by_existing_row else None
+
+ if not dry_run:
+ integration.save(update_fields=update_fields)
+ return change
+
+
+def normalize_apns_integrations(*, dry_run: bool = False) -> Iterator[ApnsRowChange]:
+ """Give each sandbox APNs credential its own row identity, and drop copied whitespace.
+
+ The identity used to be the Apple team id and bundle id alone, so connecting a sandbox
+ credential overwrote the production one for the same app. Sandbox rows move to the suffixed id
+ the code now writes, which frees the bare id for the production credential.
+ """
+ integrations = sorted_apns_integrations()
+ occupied = {(integration.team_id, integration.integration_id): integration.pk for integration in integrations}
+
+ for integration in integrations:
+ # `config` and `sensitive_config` are JSON columns that held whatever the create path was
+ # given, so a row can hold a shape this code does not expect. One such row must not stop
+ # the run.
+ try:
+ change = normalize_one_apns_integration(integration, occupied, dry_run=dry_run)
+ except Exception:
+ logger.warning(
+ "apns_integration_not_normalized",
+ team_id=integration.team_id,
+ integration_id=integration.integration_id,
+ exc_info=True,
+ )
+ yield ApnsRowChange(
+ team_id=integration.team_id,
+ integration_id=integration.integration_id,
+ unreadable=True,
+ )
+ continue
+ if change is not None:
+ yield change
+
+
+class Command(BaseCommand):
+ help = "Move APNs sandbox credentials to their own row identity and strip stored whitespace"
+
+ def add_arguments(self, parser: Any) -> None:
+ parser.add_argument("--dry-run", action="store_true", help="Report what would change and write nothing")
+
+ def handle(self, *args: Any, **options: Any) -> None:
+ dry_run = options["dry_run"]
+ if dry_run:
+ self.stdout.write(self.style.WARNING("Dry run: nothing is written."))
+
+ counts = {"reidentified": 0, "stripped": 0, "blocked": 0, "unreadable": 0}
+ for change in normalize_apns_integrations(dry_run=dry_run):
+ if change.unreadable:
+ counts["unreadable"] += 1
+ self.stdout.write(f"team {change.team_id}: cannot read {change.integration_id}, left alone")
+ continue
+ if change.blocked_by_existing_row:
+ counts["blocked"] += 1
+ self.stdout.write(
+ self.style.WARNING(f"team {change.team_id}: {change.integration_id} is taken, left alone")
+ )
+ if change.new_integration_id:
+ counts["reidentified"] += 1
+ self.stdout.write(f"team {change.team_id}: id becomes {change.new_integration_id}")
+ if change.strips_config or change.strips_signing_key:
+ counts["stripped"] += 1
+ stripped = ", ".join(
+ name
+ for name, changed in (("config", change.strips_config), ("signing key", change.strips_signing_key))
+ if changed
+ )
+ self.stdout.write(f"team {change.team_id}: whitespace stripped from {stripped}")
+
+ self.stdout.write(
+ self.style.SUCCESS(
+ f"Done. {counts['reidentified']} reidentified, {counts['stripped']} stripped, "
+ f"{counts['blocked']} blocked, {counts['unreadable']} unreadable."
+ )
+ )
diff --git a/posthog/management/commands/test/test_normalize_apns_integrations.py b/posthog/management/commands/test/test_normalize_apns_integrations.py
new file mode 100644
index 000000000000..02be066ea659
--- /dev/null
+++ b/posthog/management/commands/test/test_normalize_apns_integrations.py
@@ -0,0 +1,208 @@
+import base64
+from io import StringIO
+
+from posthog.test.base import BaseTest
+
+from django.core.management import call_command
+from django.db import connection
+
+from cryptography.fernet import Fernet
+from cryptography.hazmat.primitives import serialization
+from cryptography.hazmat.primitives.asymmetric import ec
+from parameterized import parameterized
+
+from posthog.models import Team
+from posthog.models.integration import Integration
+
+
+def a_signing_key() -> str:
+ key = ec.generate_private_key(ec.SECP256R1())
+ return key.private_bytes(
+ encoding=serialization.Encoding.PEM,
+ format=serialization.PrivateFormat.PKCS8,
+ encryption_algorithm=serialization.NoEncryption(),
+ ).decode()
+
+
+def stored_ciphertext(pk: int) -> str:
+ with connection.cursor() as cursor:
+ cursor.execute("SELECT sensitive_config FROM posthog_integration WHERE id = %s", [pk])
+ return cursor.fetchone()[0]
+
+
+class TestNormalizeApnsIntegrations(BaseTest):
+ def run_command(self, *, dry_run: bool = False) -> None:
+ call_command("normalize_apns_integrations", *(["--dry-run"] if dry_run else []))
+
+ def an_integration(
+ self, *, environment, bundle_id="com.example.app", team_id="TEAMID1234", signing_key=None, integration_id=None
+ ):
+ return Integration.objects.create(
+ team=self.team,
+ kind="apns",
+ integration_id=integration_id or f"{team_id.strip()}.{bundle_id.strip()}",
+ config={
+ "team_id": team_id,
+ "bundle_id": bundle_id,
+ "key_id": "KEYID12345",
+ "environment": environment,
+ },
+ sensitive_config={"signing_key": signing_key if signing_key is not None else a_signing_key().strip()},
+ )
+
+ def test_a_dry_run_reports_the_changes_and_writes_nothing(self):
+ key = a_signing_key().strip()
+ sandbox = self.an_integration(environment="sandbox", signing_key=f" {key}")
+ ciphertext_before = stored_ciphertext(sandbox.pk)
+ output = StringIO()
+
+ call_command("normalize_apns_integrations", "--dry-run", stdout=output)
+ sandbox.refresh_from_db()
+
+ assert sandbox.integration_id == "TEAMID1234.com.example.app"
+ assert sandbox.sensitive_config["signing_key"] == f" {key}"
+ assert stored_ciphertext(sandbox.pk) == ciphertext_before
+ reported = output.getvalue()
+ assert "TEAMID1234.com.example.app:sandbox" in reported
+ assert "signing key" in reported
+
+ def test_a_dry_run_reports_what_the_real_run_does(self):
+ # The sandbox row gives up the bare id and the padded production row takes it. Reading the
+ # database for that id during a dry run would call the production row blocked.
+ self.an_integration(environment="sandbox")
+ self.an_integration(
+ environment="production", team_id=" TEAMID1234", integration_id=" TEAMID1234.com.example.app"
+ )
+ dry, real = StringIO(), StringIO()
+
+ call_command("normalize_apns_integrations", "--dry-run", stdout=dry)
+ call_command("normalize_apns_integrations", stdout=real)
+
+ assert dry.getvalue().count("id becomes") == real.getvalue().count("id becomes") == 2
+ assert "blocked" not in dry.getvalue().replace("0 blocked", "")
+
+ def test_a_sandbox_row_frees_the_bare_id_for_the_production_row(self):
+ sandbox = self.an_integration(environment="sandbox")
+ production = self.an_integration(environment="production", bundle_id="com.example.other")
+
+ self.run_command()
+ sandbox.refresh_from_db()
+ production.refresh_from_db()
+
+ assert sandbox.integration_id == "TEAMID1234.com.example.app:sandbox"
+ assert production.integration_id == "TEAMID1234.com.example.other"
+
+ def test_a_whitespace_row_takes_the_bare_id_the_sandbox_row_gave_up(self):
+ sandbox = self.an_integration(environment="sandbox")
+ padded = self.an_integration(
+ environment="production", team_id=" TEAMID1234", integration_id=" TEAMID1234.com.example.app"
+ )
+
+ self.run_command()
+ sandbox.refresh_from_db()
+ padded.refresh_from_db()
+
+ assert sandbox.integration_id == "TEAMID1234.com.example.app:sandbox"
+ assert padded.integration_id == "TEAMID1234.com.example.app"
+ assert padded.config["team_id"] == "TEAMID1234"
+
+ def test_a_row_the_current_keys_cannot_decrypt_does_not_stop_the_migration(self):
+ unreadable = Fernet(base64.urlsafe_b64encode(b"x" * 32)).encrypt(b'{"signing_key": "k"}').decode()
+ stranded = self.an_integration(environment="sandbox")
+ with connection.cursor() as cursor:
+ cursor.execute(
+ "UPDATE posthog_integration SET sensitive_config = to_jsonb(%s::text) WHERE id = %s",
+ [unreadable, stranded.pk],
+ )
+ before = stored_ciphertext(stranded.pk)
+
+ self.run_command()
+ stranded.refresh_from_db()
+
+ assert stranded.integration_id == "TEAMID1234.com.example.app:sandbox"
+ assert stored_ciphertext(stranded.pk) == before
+
+ def test_a_key_that_needs_no_strip_keeps_its_stored_ciphertext(self):
+ integration = self.an_integration(environment="sandbox")
+ before = stored_ciphertext(integration.pk)
+
+ self.run_command()
+ integration.refresh_from_db()
+
+ assert integration.integration_id.endswith(":sandbox")
+ assert stored_ciphertext(integration.pk) == before
+
+ def test_a_padded_key_is_stripped_and_stays_usable(self):
+ key = a_signing_key().strip()
+ integration = self.an_integration(environment="production", signing_key=f" {key} ")
+
+ self.run_command()
+ integration.refresh_from_db()
+
+ assert integration.sensitive_config["signing_key"] == key
+ serialization.load_pem_private_key(integration.sensitive_config["signing_key"].encode(), password=None)
+
+ def test_a_config_value_that_is_not_a_string_is_skipped(self):
+ integration = self.an_integration(environment="production")
+ integration.config = {**integration.config, "bundle_id": 12345}
+ integration.save(update_fields=["config"])
+
+ self.run_command()
+ integration.refresh_from_db()
+
+ assert integration.integration_id == "TEAMID1234.com.example.app"
+
+ def test_two_rows_that_differ_only_by_whitespace_both_survive(self):
+ first = self.an_integration(environment="production")
+ second = self.an_integration(
+ environment="production", team_id="TEAMID1234 ", integration_id="TEAMID1234.com.example.app "
+ )
+
+ self.run_command()
+ first.refresh_from_db()
+ second.refresh_from_db()
+
+ assert first.integration_id == "TEAMID1234.com.example.app"
+ assert second.integration_id == "TEAMID1234.com.example.app "
+ assert Integration.objects.filter(kind="apns").count() == 2
+
+ @parameterized.expand(
+ [
+ ("a list", "[1, 2, 3]"),
+ ("a string", '"not a mapping"'),
+ ("null", "null"),
+ ("a number", "42"),
+ ]
+ )
+ def test_a_config_that_is_not_a_mapping_does_not_stop_the_migration(self, _name, raw_config):
+ healthy = self.an_integration(environment="sandbox")
+ with connection.cursor() as cursor:
+ cursor.execute(
+ "INSERT INTO posthog_integration "
+ "(team_id, kind, integration_id, config, sensitive_config, repository_cache, created_at, errors) "
+ "VALUES (%s, 'apns', 'odd-shape', %s::jsonb, '{}'::jsonb, '{}'::jsonb, now(), '')",
+ [self.team.id, raw_config],
+ )
+
+ self.run_command()
+ healthy.refresh_from_db()
+
+ assert healthy.integration_id == "TEAMID1234.com.example.app:sandbox"
+
+ def test_a_second_team_keeps_its_own_row_for_the_same_bundle(self):
+ mine = self.an_integration(environment="sandbox")
+ other_team = Team.objects.create(organization=self.organization, name="other")
+ theirs = Integration.objects.create(
+ team=other_team,
+ kind="apns",
+ integration_id="TEAMID1234.com.example.app",
+ config={"team_id": "TEAMID1234", "bundle_id": "com.example.app", "environment": "sandbox"},
+ sensitive_config={"signing_key": a_signing_key().strip()},
+ )
+
+ self.run_command()
+ mine.refresh_from_db()
+ theirs.refresh_from_db()
+
+ assert mine.integration_id == "TEAMID1234.com.example.app:sandbox"
+ assert theirs.integration_id == "TEAMID1234.com.example.app:sandbox"
diff --git a/posthog/models/integration/model.py b/posthog/models/integration/model.py
index 12ec04ab44d5..e48f49f6b986 100644
--- a/posthog/models/integration/model.py
+++ b/posthog/models/integration/model.py
@@ -281,7 +281,8 @@ class Integration(models.Model):
if self.kind == "email":
return self.config.get("email", self.integration_id)
if self.kind == "apns":
- return self.config.get("bundle_id", self.integration_id)
+ name = self.config.get("bundle_id", self.integration_id)
+ return f"{name} (sandbox)" if self.config.get("environment") == "sandbox" else name
if self.kind == Integration.IntegrationKind.POSTGRESQL:
# The derived id reads as "1-db.example.com-5432-postgres", so prefer a name the
# user chose. Falls back to host and user, which still beats the raw id.
diff --git a/posthog/models/integration/push.py b/posthog/models/integration/push.py
index 9797da3638bb..f71febaabd23 100644
--- a/posthog/models/integration/push.py
+++ b/posthog/models/integration/push.py
@@ -215,6 +215,37 @@ class FirebaseIntegration:
return self.integration.sensitive_config.get("access_token", "")
+APNS_ENVIRONMENTS = ("production", "sandbox")
+
+BUNDLE_ID_EXTRA_CHARACTERS = (".", "-")
+
+
+# Apple team ids are alphanumeric, and bundle ids add only hyphens and periods. A colon appears in
+# neither, which is what lets the environment suffix below never collide with a real bundle id.
+# The team id holds no period either, so the first period in an id always ends the team id.
+def is_apns_team_id(value: str) -> bool:
+ return value.isascii() and value.isalnum()
+
+
+def is_apns_bundle_id(value: str) -> bool:
+ return (
+ bool(value)
+ and value.isascii()
+ and all(character.isalnum() or character in BUNDLE_ID_EXTRA_CHARACTERS for character in value)
+ )
+
+
+def apns_integration_id(team_id_apple: str, bundle_id: str, environment: str) -> str:
+ """The row identity of an APNs credential, which the environment is part of.
+
+ A sandbox credential and a production one are separate credentials for the same app, and both
+ have to be connectable at once. Only the sandbox id carries the suffix, so credentials connected
+ before the environment was part of the identity keep the id they already have.
+ """
+ base = f"{team_id_apple}.{bundle_id}"
+ return f"{base}:sandbox" if environment == "sandbox" else base
+
+
class ApplePushIntegration:
"""
Integration for Apple Push Notification Service (APNS).
@@ -249,13 +280,32 @@ class ApplePushIntegration:
push_identity_verification: str | None = None,
push_identity_public_keys: list[str] | None = None,
) -> "model.Integration":
+ # The posted config is untyped JSON, so a field can arrive as any type. Stripping a number
+ # below raises, which the endpoint answers with a server error rather than a validation one.
+ if not all(
+ value is None or isinstance(value, str) for value in (signing_key, key_id, team_id_apple, bundle_id)
+ ):
+ raise ValidationError("All APNS fields must be strings: signing_key, key_id, team_id_apple, bundle_id")
+
+ # A space copied out of the developer portal corrupts the signed JWT and the apns-topic.
+ signing_key = (signing_key or "").strip()
+ key_id = (key_id or "").strip()
+ team_id_apple = (team_id_apple or "").strip()
+ bundle_id = (bundle_id or "").strip()
+
if not all([signing_key, key_id, team_id_apple, bundle_id]):
raise ValidationError("All APNS fields are required: signing_key, key_id, team_id_apple, bundle_id")
- if environment not in ("production", "sandbox"):
+ if not is_apns_team_id(team_id_apple):
+ raise ValidationError("APNS team_id_apple accepts letters and digits only")
+
+ if not is_apns_bundle_id(bundle_id):
+ raise ValidationError("APNS bundle_id accepts letters, digits, hyphens and periods only")
+
+ if environment not in APNS_ENVIRONMENTS:
raise ValidationError("APNS environment must be 'production' or 'sandbox'")
- integration_id = f"{team_id_apple}.{bundle_id}"
+ integration_id = apns_integration_id(team_id_apple, bundle_id, environment)
# Atomic so `preserved_push_config`'s row lock is held through the upsert that follows it.
with transaction.atomic():
integration, created = model.Integration.objects.update_or_create(
diff --git a/posthog/models/test/test_apple_push_integration.py b/posthog/models/test/test_apple_push_integration.py
index 1b86442f7475..4ef63ffdb98a 100644
--- a/posthog/models/test/test_apple_push_integration.py
+++ b/posthog/models/test/test_apple_push_integration.py
@@ -1,8 +1,12 @@
+from typing import Any
+
from posthog.test.base import BaseTest
+from parameterized import parameterized
from rest_framework.exceptions import ValidationError
from posthog.models.integration import ApplePushIntegration, Integration
+from posthog.models.integration.push import is_apns_bundle_id, is_apns_team_id
class TestApplePushIntegration(BaseTest):
@@ -12,6 +16,7 @@ class TestApplePushIntegration(BaseTest):
key_id: str = "ABC123KEY",
team_id_apple: str = "TEAM123",
bundle_id: str = "com.example.app",
+ environment: str = "production",
push_identity_verification: str | None = None,
) -> Integration:
return ApplePushIntegration.integration_from_key(
@@ -20,6 +25,7 @@ class TestApplePushIntegration(BaseTest):
team_id_apple=team_id_apple,
bundle_id=bundle_id,
team_id=self.team.id,
+ environment=environment,
push_identity_verification=push_identity_verification,
)
@@ -59,18 +65,104 @@ class TestApplePushIntegration(BaseTest):
assert first.id != second.id
- def test_validates_required_fields(self):
+ @parameterized.expand(
+ [
+ (f"{field}_{'blank' if not value else 'whitespace'}", field, value)
+ for field in ("signing_key", "key_id", "team_id_apple", "bundle_id")
+ for value in ("", " ")
+ ]
+ )
+ def test_validates_required_fields(self, _name, field, value):
with self.assertRaises(ValidationError):
- self._create_apple_push_integration(signing_key="")
+ self._create_apple_push_integration(**{field: value})
- with self.assertRaises(ValidationError):
- self._create_apple_push_integration(key_id="")
+ @parameterized.expand(["signing_key", "key_id", "team_id_apple", "bundle_id"])
+ def test_rejects_a_field_that_is_not_a_string(self, field):
+ # The API hands these through from request JSON, so any type can arrive here.
+ non_string: Any = 12345
with self.assertRaises(ValidationError):
- self._create_apple_push_integration(team_id_apple="")
+ self._create_apple_push_integration(**{field: non_string})
+
+ def test_strips_whitespace_around_the_signing_key(self):
+ # A leading space makes the key unusable for ES256, so the credential could never send.
+ integration = self._create_apple_push_integration(
+ signing_key=" -----BEGIN PRIVATE KEY-----\nfake-key\n-----END PRIVATE KEY----- "
+ )
+
+ assert integration.sensitive_config["signing_key"] == (
+ "-----BEGIN PRIVATE KEY-----\nfake-key\n-----END PRIVATE KEY-----"
+ )
+ def test_strips_whitespace_around_the_identifiers(self):
+ integration = self._create_apple_push_integration()
+ spaced = self._create_apple_push_integration(
+ team_id_apple=" TEAM123", bundle_id="com.example.app\n", key_id="ABC123KEY "
+ )
+
+ assert spaced.id == integration.id
+ assert spaced.integration_id == "TEAM123.com.example.app"
+ assert spaced.config["team_id"] == "TEAM123"
+ assert spaced.config["bundle_id"] == "com.example.app"
+ assert spaced.config["key_id"] == "ABC123KEY"
+
+ def test_sandbox_and_production_credentials_coexist(self):
+ production = self._create_apple_push_integration()
+ sandbox = self._create_apple_push_integration(environment="sandbox")
+
+ assert production.id != sandbox.id
+ assert production.integration_id == "TEAM123.com.example.app"
+ assert sandbox.integration_id == "TEAM123.com.example.app:sandbox"
+ production.refresh_from_db()
+ assert production.config["environment"] == "production"
+ assert sandbox.config["environment"] == "sandbox"
+
+ def test_a_bundle_id_cannot_impersonate_a_sandbox_credential(self):
+ sandbox = self._create_apple_push_integration(environment="sandbox")
+ lookalike = self._create_apple_push_integration(bundle_id="com.example.app.sandbox")
+
+ assert sandbox.id != lookalike.id
+
+ @parameterized.expand(
+ [
+ ("colon_in_team_id", {"team_id_apple": "TEAM:123"}),
+ ("colon_in_bundle_id", {"bundle_id": "com.example.app:sandbox"}),
+ # "TEAM.123" + "com.example.app" would read as "TEAM" + "123.com.example.app".
+ ("period_in_team_id", {"team_id_apple": "TEAM.123"}),
+ ]
+ )
+ def test_rejects_an_identifier_that_could_forge_another_identity(self, _name, kwargs):
with self.assertRaises(ValidationError):
- self._create_apple_push_integration(bundle_id="")
+ self._create_apple_push_integration(**kwargs)
+
+ @parameterized.expand(
+ [
+ ("empty", "", False),
+ ("plain", "TEAM1234", True),
+ ("trailing newline", "TEAM1234\n", False),
+ ("leading newline", "\nTEAM1234", False),
+ ("trailing space", "TEAM1234 ", False),
+ ("period", "TEAM.1234", False),
+ ("colon", "TEAM:1234", False),
+ ("non ascii digit", "TEAM١234", False),
+ ]
+ )
+ def test_team_id_accepts_ascii_letters_and_digits_only(self, _name, value, expected):
+ assert is_apns_team_id(value) is expected
+
+ @parameterized.expand(
+ [
+ ("empty", "", False),
+ ("plain", "com.example.app", True),
+ ("hyphen", "com.example.my-app", True),
+ ("trailing newline", "com.example.app\n", False),
+ ("colon", "com.example.app:sandbox", False),
+ ("space", "com.example app", False),
+ ("non ascii letter", "com.example.appé", False),
+ ]
+ )
+ def test_bundle_id_accepts_ascii_letters_digits_periods_and_hyphens_only(self, _name, value, expected):
+ assert is_apns_bundle_id(value) is expected
def test_wrapper_properties(self):
integration = self._create_apple_push_integration()
@@ -92,9 +184,15 @@ class TestApplePushIntegration(BaseTest):
with self.assertRaisesMessage(Exception, "ApplePushIntegration init called with Integration with wrong 'kind'"):
ApplePushIntegration(integration)
- def test_display_name(self):
- integration = self._create_apple_push_integration()
- assert integration.display_name == "com.example.app"
+ @parameterized.expand(
+ [
+ ("production", "com.example.app"),
+ ("sandbox", "com.example.app (sandbox)"),
+ ]
+ )
+ def test_display_name(self, environment, expected):
+ integration = self._create_apple_push_integration(environment=environment)
+ assert integration.display_name == expected
def test_clears_errors_on_upsert(self):
integration = self._create_apple_push_integration()