Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(managed-warehouse): store a separate trino password (#105355)

Eric Duong02b2a51c6c3f
diff --git a/docs/internal/hogql-trino-compiler.md b/docs/internal/hogql-trino-compiler.md
index 5340c24bc281..6aa56e802886 100644
--- a/docs/internal/hogql-trino-compiler.md
+++ b/docs/internal/hogql-trino-compiler.md
@@ -72,7 +72,7 @@ The integration does not provision catalogs, alter deployments, or make source-o
## Managed Trino connections
-Call `resolve_managed_warehouse_trino_connection(...)` through the managed-warehouse client facade when a backend job needs a live Trino target. The resolver accepts a target only when the control plane reports the organization as enabled and ready. It reads the catalog plus non-secret host, port, and username from `status.connection`, then combines them with the root password already stored for the managed warehouse. The connection contract redacts that password from its representation.
+Call `resolve_managed_warehouse_trino_connection(...)` through the managed-warehouse client facade when a backend job needs a live Trino target. The resolver accepts a target only when the control plane reports the organization as enabled and ready. It reads the catalog plus non-secret host, port, and username from `status.connection`, then uses the encrypted `DuckgresServer.trino_password` when one is configured. Existing rows fall back to the stored Duckgres password until a Trino password is set. Staff can set or replace the Trino password in the Duckgres server Django admin form; the saved value is never displayed there. The connection contract redacts that password from its representation.
Call `connect_managed_warehouse_trino(...)` to open the Python Trino client with basic authentication, HTTPS, certificate verification, and a bounded request timeout. The connector has no Duckgres fallback. A disabled target, non-ready state, organization mismatch, malformed endpoint, or missing stored credential fails before opening a socket.
diff --git a/products/managed_warehouse/backend/admin/duckgres_server_admin.py b/products/managed_warehouse/backend/admin/duckgres_server_admin.py
index 083cf55238b6..be73e1515673 100644
--- a/products/managed_warehouse/backend/admin/duckgres_server_admin.py
+++ b/products/managed_warehouse/backend/admin/duckgres_server_admin.py
@@ -1,5 +1,6 @@
from typing import cast
+from django import forms
from django.contrib import admin, messages
from django.core.exceptions import PermissionDenied, ValidationError
from django.http import Http404, HttpRequest, HttpResponse, HttpResponseNotAllowed
@@ -15,8 +16,31 @@ from products.managed_warehouse.backend.models import DuckgresServer
logger = structlog.get_logger(__name__)
+class DuckgresServerAdminForm(forms.ModelForm):
+ new_trino_password = forms.CharField(
+ label="New Trino password",
+ help_text="Leave blank to keep the current Trino password.",
+ widget=forms.PasswordInput(render_value=False),
+ required=False,
+ strip=False,
+ )
+
+ class Meta:
+ model = DuckgresServer
+ exclude = ("trino_password",)
+
+ def save(self, commit: bool = True) -> DuckgresServer:
+ server = super().save(commit=False)
+ if password := self.cleaned_data.get("new_trino_password"):
+ server.trino_password = password
+ if commit:
+ server.save()
+ return server
+
+
@admin.register(DuckgresServer)
class DuckgresServerAdmin(admin.ModelAdmin):
+ form = DuckgresServerAdminForm
list_display = (
"id",
"organization_id",
@@ -32,7 +56,7 @@ class DuckgresServerAdmin(admin.ModelAdmin):
# bucket / bucket_region are control-plane-owned: provisioning persists them
# and status_for() self-heals them on every read, so a manual admin edit
# would just be overwritten. Show them, but read-only.
- readonly_fields = ("id", "created_at", "updated_at", "bucket", "bucket_region")
+ readonly_fields = ("id", "created_at", "updated_at", "bucket", "bucket_region", "trino_password_configured")
raw_id_fields = ("organization",)
# Custom templates add the provision / enable-backfill / deprovision buttons.
@@ -58,6 +82,12 @@ class DuckgresServerAdmin(admin.ModelAdmin):
"fields": ("catalog_host", "catalog_port", "catalog_database", "catalog_username"),
},
),
+ (
+ "Trino connection",
+ {
+ "fields": ("trino_password_configured", "new_trino_password"),
+ },
+ ),
(
"Storage",
{
@@ -94,6 +124,12 @@ class DuckgresServerAdmin(admin.ModelAdmin):
"fields": ("catalog_host", "catalog_port", "catalog_database", "catalog_username", "catalog_password"),
},
),
+ (
+ "Trino connection",
+ {
+ "fields": ("new_trino_password",),
+ },
+ ),
(
"Storage",
{
@@ -102,6 +138,10 @@ class DuckgresServerAdmin(admin.ModelAdmin):
),
)
+ @admin.display(boolean=True, description="Trino password configured")
+ def trino_password_configured(self, obj: DuckgresServer) -> bool:
+ return bool(obj.trino_password)
+
def get_urls(self):
custom_urls = [
path(
diff --git a/products/managed_warehouse/backend/common.py b/products/managed_warehouse/backend/common.py
index 8f7415db3764..ca30c27b141c 100644
--- a/products/managed_warehouse/backend/common.py
+++ b/products/managed_warehouse/backend/common.py
@@ -204,6 +204,16 @@ def get_duckgres_config_for_org(organization_id: str) -> dict[str, str]:
raise ValueError(f"No DuckgresServer configured for organization {organization_id}")
+def get_trino_password_for_org(organization_id: str) -> str:
+ if is_dev_mode():
+ return _duckgres_dev_config()["DUCKGRES_PASSWORD"]
+
+ server = get_duckgres_server_for_organization(organization_id)
+ if server is None:
+ raise ValueError(f"No DuckgresServer configured for organization {organization_id}")
+ return server.trino_password or server.password
+
+
def get_duckgres_server_for_organization(organization_id: str) -> DuckgresServer | None:
"""Look up DuckgresServer for an organization."""
if is_dev_mode():
diff --git a/products/managed_warehouse/backend/facade/api.py b/products/managed_warehouse/backend/facade/api.py
index fe66ca4dd5af..4d315e1eb410 100644
--- a/products/managed_warehouse/backend/facade/api.py
+++ b/products/managed_warehouse/backend/facade/api.py
@@ -47,6 +47,7 @@ __all__ = [
"get_catalog_connection_config",
"get_control_plane_bucket",
"get_duckgres_query_server_config",
+ "get_managed_warehouse_trino_password",
"get_org_id_for_team",
"get_team_deletion_block_reason",
"get_stored_bucket_config",
@@ -159,6 +160,10 @@ def get_duckgres_query_server_config(organization_id: str) -> DuckgresQueryServe
)
+def get_managed_warehouse_trino_password(organization_id: str) -> str:
+ return common.get_trino_password_for_org(organization_id)
+
+
def get_catalog_connection_config(organization_id: str) -> DuckLakeCatalogConnectionConfig | None:
stored = get_stored_warehouse_config(organization_id)
return stored.catalog if stored is not None else None
diff --git a/products/managed_warehouse/backend/migrations/0008_duckgresserver_trino_password.py b/products/managed_warehouse/backend/migrations/0008_duckgresserver_trino_password.py
new file mode 100644
index 000000000000..08128702a85e
--- /dev/null
+++ b/products/managed_warehouse/backend/migrations/0008_duckgresserver_trino_password.py
@@ -0,0 +1,17 @@
+from django.db import migrations
+
+from posthog.helpers.encrypted_fields import EncryptedTextField
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("managed_warehouse", "0007_drop_orphaned_duckgresserver_team_fk"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="duckgresserver",
+ name="trino_password",
+ field=EncryptedTextField(blank=True, max_length=500, null=True),
+ ),
+ ]
diff --git a/products/managed_warehouse/backend/migrations/max_migration.txt b/products/managed_warehouse/backend/migrations/max_migration.txt
index 6bc11bbdfe54..3b677cfcdfb8 100644
--- a/products/managed_warehouse/backend/migrations/max_migration.txt
+++ b/products/managed_warehouse/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0007_drop_orphaned_duckgresserver_team_fk
+0008_duckgresserver_trino_password
diff --git a/products/managed_warehouse/backend/models.py b/products/managed_warehouse/backend/models.py
index bd23b2689387..13d96c510368 100644
--- a/products/managed_warehouse/backend/models.py
+++ b/products/managed_warehouse/backend/models.py
@@ -37,6 +37,7 @@ class DuckgresServer(CreatedMetaFields, UpdatedMetaFields, UUIDModel):
database = models.CharField(max_length=255, default="ducklake")
username = models.CharField(max_length=255)
password = EncryptedTextField(max_length=500)
+ trino_password = EncryptedTextField(max_length=500, null=True, blank=True)
# DuckLake catalog Postgres connection — a separate metadata store from the
# query server above. Nullable: an org may have a provisioned server before its
diff --git a/products/managed_warehouse/backend/tests/test_admin.py b/products/managed_warehouse/backend/tests/test_admin.py
index a0c4194370d7..a949e8828d25 100644
--- a/products/managed_warehouse/backend/tests/test_admin.py
+++ b/products/managed_warehouse/backend/tests/test_admin.py
@@ -5,6 +5,8 @@ from django.contrib.admin.sites import AdminSite
from django.contrib.auth.models import Permission
from django.contrib.messages import get_messages
from django.contrib.messages.storage.fallback import FallbackStorage
+from django.db import connection
+from django.forms.models import model_to_dict
from django.http import Http404, HttpRequest
from django.test import RequestFactory
from django.urls import reverse
@@ -195,6 +197,36 @@ class TestDuckgresServerAdminProvision(BaseTest):
assert "username" in field_names
assert "password" not in field_names
+ assert "trino_password" not in field_names
+ assert "new_trino_password" in field_names
+
+ def test_change_form_sets_encrypted_trino_password_without_revealing_or_erasing_it(self) -> None:
+ server = self._server()
+ request = self._get("/admin/posthog/duckgresserver/")
+ form_class = self.admin.get_form(request, server)
+ assert "trino_password" not in form_class.base_fields
+ assert "password" not in form_class.base_fields
+
+ data = model_to_dict(server)
+ data["new_trino_password"] = "trino-test-secret"
+ form = form_class(data=data, instance=server)
+ assert form.is_valid(), form.errors
+ form.save()
+
+ server.refresh_from_db()
+ assert server.trino_password == "trino-test-secret"
+ with connection.cursor() as cursor:
+ cursor.execute("SELECT trino_password FROM posthog_duckgresserver WHERE id = %s", [str(server.id)])
+ stored = cursor.fetchone()[0]
+ assert stored != "trino-test-secret"
+ assert stored.startswith("gAAAAA")
+ assert "trino-test-secret" not in form_class(instance=server).as_p()
+
+ form = form_class(data=model_to_dict(server), instance=server)
+ assert form.is_valid(), form.errors
+ form.save()
+ server.refresh_from_db()
+ assert server.trino_password == "trino-test-secret"
def test_provision_post_calls_managed_warehouse_bypassing_flag(self) -> None:
request = self._post(
diff --git a/products/managed_warehouse/backend/tests/test_common.py b/products/managed_warehouse/backend/tests/test_common.py
index fb230998e3b2..354c8b9d3e73 100644
--- a/products/managed_warehouse/backend/tests/test_common.py
+++ b/products/managed_warehouse/backend/tests/test_common.py
@@ -11,6 +11,7 @@ from posthog.models import Organization
from products.managed_warehouse.backend.common import (
default_bucket_region,
duckgres_data_imports_table_name,
+ get_trino_password_for_org,
initialize_ducklake,
is_version_mismatch,
reset_ducklake_catalog,
@@ -40,6 +41,18 @@ class TestUpsertDuckgresServerForOrg:
assert updated.port == 6543
assert updated.password == "pw2"
+ def test_trino_password_overrides_duckgres_password_when_configured(self):
+ org = Organization.objects.create(name="Test Org")
+ server = DuckgresServer.objects.create(
+ organization=org, host="warehouse.example.com", username="root", password="duckgres-secret"
+ )
+
+ with patch("products.managed_warehouse.backend.common.is_dev_mode", return_value=False):
+ assert get_trino_password_for_org(str(org.id)) == "duckgres-secret"
+ server.trino_password = "trino-secret"
+ server.save(update_fields=["trino_password"])
+ assert get_trino_password_for_org(str(org.id)) == "trino-secret"
+
class TestDefaultBucketRegion:
@parameterized.expand(
diff --git a/products/managed_warehouse/backend/tests/test_trino_connection.py b/products/managed_warehouse/backend/tests/test_trino_connection.py
index f1bccc6a75d3..b32128b5ba0e 100644
--- a/products/managed_warehouse/backend/tests/test_trino_connection.py
+++ b/products/managed_warehouse/backend/tests/test_trino_connection.py
@@ -6,10 +6,7 @@ from unittest import mock
import requests
from rest_framework.response import Response
-from products.managed_warehouse.backend.facade.contracts import (
- DuckgresQueryServerConfig,
- ManagedWarehouseTrinoConnectionUnavailable,
-)
+from products.managed_warehouse.backend.facade.contracts import ManagedWarehouseTrinoConnectionUnavailable
from products.managed_warehouse.backend.trino_connection import (
connect_managed_warehouse_trino,
resolve_managed_warehouse_trino_connection,
@@ -36,27 +33,16 @@ def _ready_response(**connection_overrides: object) -> Response:
)
-def _root_connection(password: str = "root-secret") -> DuckgresQueryServerConfig:
- return DuckgresQueryServerConfig(
- host="duckgres.postwh.com",
- port=5432,
- flight_port=8815,
- database="ducklake",
- username="root",
- password=password,
- )
-
-
class TestResolveManagedWarehouseTrinoConnection:
- def test_combines_the_control_plane_target_with_the_existing_root_secret(self) -> None:
+ def test_combines_the_control_plane_target_with_the_stored_trino_secret(self) -> None:
with (
mock.patch(
"products.managed_warehouse.backend.presentation.views._request",
return_value=_ready_response(),
) as request,
mock.patch(
- "products.managed_warehouse.backend.trino_connection.get_duckgres_query_server_config",
- return_value=_root_connection(),
+ "products.managed_warehouse.backend.trino_connection.get_managed_warehouse_trino_password",
+ return_value="trino-secret",
),
):
connection = resolve_managed_warehouse_trino_connection("org-1")
@@ -65,8 +51,8 @@ class TestResolveManagedWarehouseTrinoConnection:
assert connection.port == 8443
assert connection.catalog == "org_catalog"
assert connection.username == "org_database"
- assert connection.password == "root-secret"
- assert "root-secret" not in repr(connection)
+ assert connection.password == "trino-secret"
+ assert "trino-secret" not in repr(connection)
request.assert_called_once_with("GET", "org-1", "/trino", require_enabled=False)
@pytest.mark.parametrize(
@@ -107,15 +93,15 @@ class TestResolveManagedWarehouseTrinoConnection:
with pytest.raises(ManagedWarehouseTrinoConnectionUnavailable, match="ready managed Trino connection"):
resolve_managed_warehouse_trino_connection("org-1")
- def test_rejects_a_missing_stored_root_secret(self) -> None:
+ def test_rejects_a_missing_stored_trino_secret(self) -> None:
with (
mock.patch(
"products.managed_warehouse.backend.presentation.views._request",
return_value=_ready_response(),
),
mock.patch(
- "products.managed_warehouse.backend.trino_connection.get_duckgres_query_server_config",
- return_value=_root_connection(password=""),
+ "products.managed_warehouse.backend.trino_connection.get_managed_warehouse_trino_password",
+ return_value="",
),
):
with pytest.raises(ManagedWarehouseTrinoConnectionUnavailable, match="stored managed warehouse credential"):
@@ -178,8 +164,8 @@ def test_managed_trino_requests_bypass_environment_proxies_only_for_known_hosts(
return_value=_ready_response(host=host, port=port),
),
mock.patch(
- "products.managed_warehouse.backend.trino_connection.get_duckgres_query_server_config",
- return_value=_root_connection(),
+ "products.managed_warehouse.backend.trino_connection.get_managed_warehouse_trino_password",
+ return_value="root-secret",
),
mock.patch("requests.adapters.HTTPAdapter.send", side_effect=RuntimeError("network boundary")) as send,
):
diff --git a/products/managed_warehouse/backend/trino_connection.py b/products/managed_warehouse/backend/trino_connection.py
index 05e1de0ca06d..ed15a808f579 100644
--- a/products/managed_warehouse/backend/trino_connection.py
+++ b/products/managed_warehouse/backend/trino_connection.py
@@ -6,7 +6,7 @@ from typing import TYPE_CHECKING
import requests
-from products.managed_warehouse.backend.facade.api import get_duckgres_query_server_config
+from products.managed_warehouse.backend.facade.api import get_managed_warehouse_trino_password
from products.managed_warehouse.backend.facade.contracts import (
ManagedWarehouseTrinoConnection,
ManagedWarehouseTrinoConnectionUnavailable,
@@ -26,12 +26,12 @@ def resolve_managed_warehouse_trino_connection(organization_id: str) -> ManagedW
)
try:
- root_connection = get_duckgres_query_server_config(organization_id)
+ password = get_managed_warehouse_trino_password(organization_id)
except ValueError as error:
raise ManagedWarehouseTrinoConnectionUnavailable(
"The organization does not have a stored managed warehouse credential"
) from error
- if not root_connection.password:
+ if not password:
raise ManagedWarehouseTrinoConnectionUnavailable(
"The organization does not have a stored managed warehouse credential"
)
@@ -41,7 +41,7 @@ def resolve_managed_warehouse_trino_connection(organization_id: str) -> ManagedW
port=target.port,
catalog=target.catalog,
username=target.username,
- password=root_connection.password,
+ password=password,
)