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.

revert(cdp): remove the masked-secret scan tooling (#88239)

Meikel Ratze39e7327db39
diff --git a/posthog/templates/admin/cdp/hogfunction/change_list.html b/posthog/templates/admin/cdp/hogfunction/change_list.html
index 89aae9737563..cf29e2c5a56a 100644
--- a/posthog/templates/admin/cdp/hogfunction/change_list.html
+++ b/posthog/templates/admin/cdp/hogfunction/change_list.html
@@ -7,10 +7,5 @@
<a href="{% url 'admin:rerun-google-ads-failed-invocations' %}">Rerun Google Ads failed invocations</a>
</li>
{% endif %}
- {% if show_masked_secrets_button %}
- <li>
- <a href="{% url 'admin:hog-function-masked-secrets' %}">Find masked secrets</a>
- </li>
- {% endif %}
{{ block.super }}
{% endblock %}
diff --git a/posthog/templates/admin/cdp/hogfunction/masked_secrets.html b/posthog/templates/admin/cdp/hogfunction/masked_secrets.html
deleted file mode 100644
index 7298a376e2d8..000000000000
--- a/posthog/templates/admin/cdp/hogfunction/masked_secrets.html
+++ /dev/null
@@ -1,152 +0,0 @@
-{% extends "admin/base_site.html" %}
-{% load i18n admin_urls %}
-
-{% block content %}
-<div id="content-main">
- <p>
- Finds hog functions whose stored secret is the read-back mask
- (<code>********</code>) instead of a real credential, and workflows whose stored secret
- is the persisted <code>{"secret": true}</code> read-back marker. Both fail
- authentication against the third party on every send.
- </p>
- <p>
- The original credential is gone, so the fix is to ask each owner to re-enter it. Use the
- organization summary below to work out who to contact. The scan is read-only and changes
- nothing.
- </p>
- <form method="post">
- {% csrf_token %}
- <fieldset class="module aligned">
- {% for field in form %}
- <div class="form-row">
- {{ field.errors }}
- {{ field.label_tag }} {{ field }}
- {% if field.help_text %}
- <div class="help">{{ field.help_text }}</div>
- {% endif %}
- </div>
- {% endfor %}
- </fieldset>
- <div class="submit-row">
- <input type="submit" value="Scan" class="default" name="_scan">
- </div>
- </form>
-
- {% if scan %}
- <h2>Summary</h2>
- <p>
- Scanned {{ scan.scanned_count }} hog function{{ scan.scanned_count|pluralize }} and
- {{ flow_scan.scanned_count }} workflow{{ flow_scan.scanned_count|pluralize }} with stored
- secrets. Found {{ scan.findings|length }} hog function{{ scan.findings|length|pluralize }} and
- {{ flow_scan.findings|length }} workflow{{ flow_scan.findings|length|pluralize }} storing the
- mask across {{ organizations|length }} organization{{ organizations|pluralize }}.
- </p>
-
- {% if organizations %}
- <h2>Affected organizations</h2>
- <table>
- <thead>
- <tr>
- <th>Organization</th>
- <th>ID</th>
- <th>Teams</th>
- <th>Affected</th>
- <th>Enabled</th>
- </tr>
- </thead>
- <tbody>
- {% for organization in organizations %}
- <tr>
- <td>{{ organization.organization_name }}</td>
- <td><code>{{ organization.organization_id }}</code></td>
- <td>{{ organization.team_ids|join:", " }}</td>
- <td>{{ organization.finding_count }}</td>
- <td>{{ organization.enabled_count }}</td>
- </tr>
- {% endfor %}
- </tbody>
- </table>
- {% endif %}
-
- {% if scan.findings %}
- <h2>Hog functions</h2>
- <table>
- <thead>
- <tr>
- <th>Team</th>
- <th>Name</th>
- <th>Type</th>
- <th>Template</th>
- <th>Enabled</th>
- <th>Last updated</th>
- <th>Masked inputs</th>
- </tr>
- </thead>
- <tbody>
- {% for finding in scan.findings %}
- <tr>
- <td>{{ finding.team_name }} ({{ finding.team_id }})</td>
- <td>
- <a href="{% url 'admin:cdp_hogfunction_change' finding.hog_function_id %}">
- {{ finding.hog_function_name|default:finding.hog_function_id }}
- </a>
- <div class="help">
- <a href="{{ finding.configuration_url }}">Open in app</a>
- </div>
- </td>
- <td>{{ finding.hog_function_type }}</td>
- <td><code>{{ finding.template_id }}</code></td>
- <td>{{ finding.enabled|yesno:"yes,no" }}</td>
- <td>{{ finding.updated_at|date:"Y-m-d H:i" }}</td>
- <td>
- {{ finding.masked_live_inputs|join:", " }}
- {% if finding.masked_draft_inputs %}
- <div class="help">draft: {{ finding.masked_draft_inputs|join:", " }}</div>
- {% endif %}
- </td>
- </tr>
- {% endfor %}
- </tbody>
- </table>
- {% endif %}
-
- {% if flow_scan.findings %}
- <h2>Workflows</h2>
- <table>
- <thead>
- <tr>
- <th>Team</th>
- <th>Name</th>
- <th>Status</th>
- <th>Last updated</th>
- <th>Masked inputs (action.key)</th>
- </tr>
- </thead>
- <tbody>
- {% for finding in flow_scan.findings %}
- <tr>
- <td>{{ finding.team_name }} ({{ finding.team_id }})</td>
- <td>
- <a href="{% url 'admin:workflows_hogflow_change' finding.hog_flow_id %}">
- {{ finding.hog_flow_name|default:finding.hog_flow_id }}
- </a>
- <div class="help">
- <a href="{{ finding.configuration_url }}">Open in app</a>
- </div>
- </td>
- <td>{{ finding.status }}</td>
- <td>{{ finding.updated_at|date:"Y-m-d H:i" }}</td>
- <td>
- {{ finding.masked_live_inputs|join:", " }}
- {% if finding.masked_draft_inputs %}
- <div class="help">draft: {{ finding.masked_draft_inputs|join:", " }}</div>
- {% endif %}
- </td>
- </tr>
- {% endfor %}
- </tbody>
- </table>
- {% endif %}
- {% endif %}
-</div>
-{% endblock %}
diff --git a/products/cdp/backend/admin/hog_function_admin.py b/products/cdp/backend/admin/hog_function_admin.py
index 98cfceaf3007..3b0a80eb7210 100644
--- a/products/cdp/backend/admin/hog_function_admin.py
+++ b/products/cdp/backend/admin/hog_function_admin.py
@@ -11,13 +11,6 @@ from django.utils.html import format_html
from posthog.management.commands.rerun_google_ads_failed_invocations import MAX_WINDOW_DAYS
from products.cdp.backend.models.hog_functions.hog_function import HogFunction, HogFunctionState
-from products.cdp.backend.services.masked_secrets import (
- DEFAULT_MAX_RESULTS,
- DEFAULT_MAX_SCANNED,
- scan_for_masked_secrets,
- scan_hog_flows_for_masked_secrets,
- summarize_by_organization,
-)
class HogFunctionAdminForm(forms.ModelForm):
@@ -95,44 +88,6 @@ class RerunGoogleAdsFailedInvocationsForm(forms.Form):
return cleaned
-class MaskedSecretsForm(forms.Form):
- """Admin-facing wrapper around the `find_masked_hog_function_secrets` command.
-
- Mirrors its flags so an operator who needs the full list can rerun the same scope from the
- shell without re-deriving the arguments.
- """
-
- team_ids = forms.CharField(
- required=False,
- help_text="Optional comma-separated team IDs. Leave blank to scan every team.",
- )
- include_deleted = forms.BooleanField(
- required=False,
- initial=False,
- help_text="Include soft-deleted hog functions. They send nothing, so they are off by default.",
- )
- include_archived = forms.BooleanField(
- required=False,
- initial=False,
- help_text="Include archived workflows. They send nothing, so they are off by default.",
- )
- max_results = forms.IntegerField(
- initial=DEFAULT_MAX_RESULTS,
- min_value=1,
- max_value=10000,
- help_text="Cap on reported hog functions and on reported workflows. You are told when the scan stops at the cap.",
- )
-
- def clean_team_ids(self) -> list[int]:
- raw = self.cleaned_data.get("team_ids", "") or ""
- if not raw.strip():
- return []
- try:
- return [int(part.strip()) for part in raw.split(",") if part.strip()]
- except ValueError:
- raise forms.ValidationError("Team IDs must be a comma-separated list of integers.")
-
-
@admin.register(HogFunction)
class HogFunctionAdmin(admin.ModelAdmin):
form = HogFunctionAdminForm
@@ -195,75 +150,14 @@ class HogFunctionAdmin(admin.ModelAdmin):
self.admin_site.admin_view(self.rerun_google_ads_view),
name="rerun-google-ads-failed-invocations",
),
- path(
- "masked-secrets/",
- self.admin_site.admin_view(self.masked_secrets_view),
- name="hog-function-masked-secrets",
- ),
]
return custom_urls + super().get_urls()
def changelist_view(self, request, extra_context=None):
extra_context = extra_context or {}
extra_context["show_rerun_google_ads_button"] = True
- extra_context["show_masked_secrets_button"] = True
return super().changelist_view(request, extra_context=extra_context)
- def masked_secrets_view(self, request):
- scan = None
- flow_scan = None
- organizations: list = []
- if request.method == "POST":
- form = MaskedSecretsForm(request.POST)
- if form.is_valid():
- team_ids = form.cleaned_data["team_ids"] or None
- max_results = form.cleaned_data["max_results"]
- scan = scan_for_masked_secrets(
- team_ids=team_ids,
- include_deleted=form.cleaned_data["include_deleted"],
- max_results=max_results,
- max_scanned=DEFAULT_MAX_SCANNED,
- )
- flow_scan = scan_hog_flows_for_masked_secrets(
- team_ids=team_ids,
- include_archived=form.cleaned_data["include_archived"],
- max_results=max_results,
- max_scanned=DEFAULT_MAX_SCANNED,
- )
- organizations = summarize_by_organization([*scan.findings, *flow_scan.findings])
- if scan.truncated or flow_scan.truncated:
- capped = " and ".join(
- name
- for name, capped_scan in (("hog functions", scan), ("workflows", flow_scan))
- if capped_scan.truncated
- )
- messages.warning(
- request,
- f"The {capped} scan stopped before covering every row, so more may be affected than "
- "this shows. Scan a narrower set of teams, or run the "
- "find_masked_hog_function_secrets management command for the full sweep.",
- )
- elif not scan.findings and not flow_scan.findings:
- messages.success(
- request,
- f"Scanned {scan.scanned_count} hog function(s) and {flow_scan.scanned_count} workflow(s) "
- "with stored secrets. None store the mask.",
- )
- else:
- form = MaskedSecretsForm()
-
- return render(
- request,
- "admin/cdp/hogfunction/masked_secrets.html",
- {
- "form": form,
- "scan": scan,
- "flow_scan": flow_scan,
- "organizations": organizations,
- "title": "Hog functions and workflows storing the secret mask",
- },
- )
-
def rerun_google_ads_view(self, request):
output: str | None = None
if request.method == "POST":
diff --git a/products/cdp/backend/management/commands/find_masked_hog_function_secrets.py b/products/cdp/backend/management/commands/find_masked_hog_function_secrets.py
deleted file mode 100644
index 83ce966750f6..000000000000
--- a/products/cdp/backend/management/commands/find_masked_hog_function_secrets.py
+++ /dev/null
@@ -1,127 +0,0 @@
-"""Report hog functions and workflows whose stored secret is a read-back marker, not a credential.
-
-Read-only. It names the affected organizations so operators can ask each owner to re-enter the
-credential, which is the only way back: the original value was overwritten, not archived.
-
-Use `--max-results 0` to lift the cap when the run is a full audit rather than a spot check.
-"""
-
-from typing import Any
-
-from django.core.management.base import BaseCommand, CommandError
-
-from products.cdp.backend.services.masked_secrets import (
- DEFAULT_BATCH_SIZE,
- DEFAULT_MAX_RESULTS,
- scan_for_masked_secrets,
- scan_hog_flows_for_masked_secrets,
- summarize_by_organization,
-)
-
-
-class Command(BaseCommand):
- help = (
- "Find hog functions and workflows storing a secret read-back marker instead of a real "
- "credential, and report the organizations to contact. Read-only."
- )
-
- def add_arguments(self, parser: Any) -> None:
- parser.add_argument(
- "--team-ids",
- nargs="+",
- type=int,
- default=None,
- help="Restrict to specific teams. Default: every team.",
- )
- parser.add_argument(
- "--include-deleted",
- action="store_true",
- help="Include soft-deleted hog functions. They send nothing, so they are off by default.",
- )
- parser.add_argument(
- "--include-archived",
- action="store_true",
- help="Include archived workflows. They send nothing, so they are off by default.",
- )
- parser.add_argument(
- "--batch-size",
- type=int,
- default=DEFAULT_BATCH_SIZE,
- help=f"Rows fetched per database round trip (default {DEFAULT_BATCH_SIZE}).",
- )
- parser.add_argument(
- "--max-results",
- type=int,
- default=DEFAULT_MAX_RESULTS,
- help=f"Cap on reported hog functions (default {DEFAULT_MAX_RESULTS}). Pass 0 for no cap.",
- )
-
- def handle(self, *args: Any, **options: Any) -> None:
- batch_size = options["batch_size"]
- if batch_size < 1:
- raise CommandError("--batch-size must be at least 1")
- max_results = options["max_results"]
- if max_results < 0:
- raise CommandError("--max-results must be 0 or more")
-
- scan = scan_for_masked_secrets(
- team_ids=options["team_ids"],
- include_deleted=options["include_deleted"],
- batch_size=batch_size,
- max_results=max_results or None,
- )
- flow_scan = scan_hog_flows_for_masked_secrets(
- team_ids=options["team_ids"],
- include_archived=options["include_archived"],
- batch_size=batch_size,
- max_results=max_results or None,
- )
-
- self._write_text_report(scan.findings, flow_scan.findings)
-
- self.stdout.write(
- f"Scanned {scan.scanned_count} hog function(s) and {flow_scan.scanned_count} workflow(s) with stored "
- f"secrets. Found {len(scan.findings)} hog function(s) and {len(flow_scan.findings)} workflow(s) "
- "storing the mask."
- )
- for name, capped_scan in (("hog functions", scan), ("workflows", flow_scan)):
- if capped_scan.truncated:
- self.stdout.write(
- self.style.WARNING(
- f"The {name} scan stopped at the --max-results cap of {max_results}. There are more "
- "affected than this run reported. Raise the cap or narrow with --team-ids."
- )
- )
-
- def _write_text_report(self, findings: tuple[Any, ...], flow_findings: tuple[Any, ...]) -> None:
- for finding in findings:
- inputs = ", ".join(finding.masked_live_inputs) or "-"
- drafts = ", ".join(finding.masked_draft_inputs)
- draft_note = f" draft_inputs=[{drafts}]" if drafts else ""
- self.stdout.write(
- f"team={finding.team_id} org={finding.organization_id} "
- f"function={finding.hog_function_id} template={finding.template_id or '-'} "
- f"enabled={finding.enabled} inputs=[{inputs}]{draft_note}"
- )
- for finding in flow_findings:
- inputs = ", ".join(finding.masked_live_inputs) or "-"
- drafts = ", ".join(finding.masked_draft_inputs)
- draft_note = f" draft_inputs=[{drafts}]" if drafts else ""
- self.stdout.write(
- f"team={finding.team_id} org={finding.organization_id} "
- f"workflow={finding.hog_flow_id} status={finding.status} "
- f"inputs=[{inputs}]{draft_note}"
- )
-
- summaries = summarize_by_organization([*findings, *flow_findings])
- if not summaries:
- return
-
- self.stdout.write("")
- self.stdout.write(f"Affected organizations ({len(summaries)}):")
- for summary in summaries:
- self.stdout.write(
- f" {summary.organization_id} {summary.organization_name} "
- f"teams={list(summary.team_ids)} affected={summary.finding_count} "
- f"enabled={summary.enabled_count}"
- )
diff --git a/products/cdp/backend/services/masked_secrets.py b/products/cdp/backend/services/masked_secrets.py
deleted file mode 100644
index f317b885747c..000000000000
--- a/products/cdp/backend/services/masked_secrets.py
+++ /dev/null
@@ -1,322 +0,0 @@
-"""Find hog functions and hog flows whose stored secret is a read-back marker, not a credential.
-
-The UI shows a saved secret as `MASKED_SECRET_VALUE` and sends that mask back on a re-save to
-mean "keep the stored value". When the two sides of that contract disagree, the mask is what
-gets encrypted, the destination starts failing auth against the third party, and the real
-credential is gone. Only the owner can restore it, so operators need the list of who to tell.
-
-Hog flows read secrets back as a `{"secret": true}` marker instead of the mask string. Their
-save path recovers the stored value, but a marker persisted before that guard shipped is the
-same failure: the worker uses the marker object as the credential.
-
-The match cannot be a SQL predicate. `encrypted_inputs` is Fernet-encrypted, and Fernet embeds a
-timestamp and a random IV, so the same plaintext produces different ciphertext on every write.
-Every candidate row has to be decrypted in Python and inspected.
-"""
-
-from collections.abc import Iterable, Iterator, Sequence
-from datetime import datetime
-from typing import TypeVar
-from uuid import UUID
-
-from django.db.models import Model, Q, QuerySet
-
-from posthog.cdp.validation import MASKED_SECRET_VALUE, masked_secret_input_keys
-from posthog.dataclasses import frozen
-from posthog.utils import absolute_uri
-
-from products.cdp.backend.models.hog_functions.hog_function import HogFunction
-from products.workflows.backend.models.hog_flow.hog_flow import HogFlow
-
-DEFAULT_BATCH_SIZE = 500
-
-# Bounds a fleet-wide sweep so an admin request cannot run unbounded. Callers are told when it
-# bites rather than being handed a silently short list.
-DEFAULT_MAX_RESULTS = 1000
-
-# Bounds the rows one admin request walks. max_results caps findings only, so a sparse sweep
-# would otherwise scan both tables end to end inside the web request and outlive the proxy
-# timeout. The management command passes no ceiling — a shell has nothing to time out.
-DEFAULT_MAX_SCANNED = 50_000
-
-
-@frozen
-class MaskedSecretFinding:
- organization_id: UUID
- organization_name: str
- team_id: int
- team_name: str
- hog_function_id: UUID
- hog_function_name: str
- hog_function_type: str
- template_id: str
- enabled: bool
- deleted: bool
- updated_at: datetime
- # Input keys only, never their values. The value is believed to be the mask, but a scan that
- # prints secret inputs would leak real credentials the moment that belief is wrong.
- masked_live_inputs: tuple[str, ...]
- masked_draft_inputs: tuple[str, ...]
- configuration_url: str
-
-
-@frozen
-class HogFlowMaskedSecretFinding:
- organization_id: UUID
- organization_name: str
- team_id: int
- team_name: str
- hog_flow_id: UUID
- hog_flow_name: str
- status: str
- enabled: bool
- updated_at: datetime
- # Action-qualified input keys only, never their values — same leak-protection reasoning as
- # MaskedSecretFinding.
- masked_live_inputs: tuple[str, ...]
- masked_draft_inputs: tuple[str, ...]
- configuration_url: str
-
-
-@frozen
-class AffectedOrganization:
- organization_id: UUID
- organization_name: str
- team_ids: tuple[int, ...]
- finding_count: int
- enabled_count: int
-
-
-@frozen
-class MaskedSecretScan:
- findings: tuple[MaskedSecretFinding, ...]
- scanned_count: int
- # True when max_results stopped the sweep before the queryset was exhausted, so there are
- # more affected hog functions than `findings` shows.
- truncated: bool
-
-
-@frozen
-class HogFlowMaskedSecretScan:
- findings: tuple[HogFlowMaskedSecretFinding, ...]
- scanned_count: int
- truncated: bool
-
-
-def _masked_input_keys(stored: object) -> tuple[str, ...]:
- """The shared mask predicate, as the tuple the frozen finding dataclasses require."""
- return tuple(masked_secret_input_keys(stored))
-
-
-def _flow_masked_input_keys(stored: object) -> tuple[str, ...]:
- """Action-qualified input keys whose stored entry is a persisted read-back marker.
-
- Hog flow secrets are keyed action id then input key. An entry is poisoned when it is the
- `{"secret": true}` read-back marker with no value — the save path should have swapped it for
- the stored secret — or when its value is the literal mask string. Same shape caveat as
- `masked_secret_input_keys`: an undecryptable row reads back as a raw string.
- """
- if not isinstance(stored, dict):
- return ()
- poisoned = []
- for action_id, inputs in stored.items():
- if not isinstance(inputs, dict):
- continue
- for key, entry in inputs.items():
- if not isinstance(entry, dict):
- continue
- if entry.get("value") == MASKED_SECRET_VALUE or (entry.get("secret") and "value" not in entry):
- poisoned.append(f"{action_id}.{key}")
- return tuple(sorted(poisoned))
-
-
-_M = TypeVar("_M", bound=Model)
-
-
-def _keyset_batches(queryset: QuerySet[_M], batch_size: int) -> Iterator[_M]:
- """Fetch id-ordered LIMIT batches, resuming after the last seen id.
-
- `.iterator()` would be simpler, but prod runs behind pgbouncer, which disables server-side
- cursors — Django then fetches the entire result set in one query. Keyset batches keep memory
- and per-query time bounded in every environment.
- """
- last_pk = None
- while True:
- batch_queryset = queryset.order_by("pk")
- if last_pk is not None:
- batch_queryset = batch_queryset.filter(pk__gt=last_pk)
- rows = list(batch_queryset[:batch_size])
- yield from rows
- if len(rows) < batch_size:
- return
- last_pk = rows[-1].pk
-
-
-def scan_for_masked_secrets(
- *,
- team_ids: Sequence[int] | None = None,
- include_deleted: bool = False,
- batch_size: int = DEFAULT_BATCH_SIZE,
- max_results: int | None = DEFAULT_MAX_RESULTS,
- max_scanned: int | None = None,
-) -> MaskedSecretScan:
- queryset = (
- HogFunction.objects.select_related("team", "team__organization")
- .filter(Q(encrypted_inputs__isnull=False) | Q(draft_encrypted_inputs__isnull=False))
- # The rows carry hog source, bytecode, and filters the scan never reads. Defer them so a
- # fleet-wide sweep doesn't drag them over the wire.
- .only(
- "id",
- "name",
- "type",
- "template_id",
- "enabled",
- "deleted",
- "updated_at",
- "encrypted_inputs",
- "draft_encrypted_inputs",
- "team__id",
- "team__name",
- "team__organization__id",
- "team__organization__name",
- )
- )
- if not include_deleted:
- queryset = queryset.filter(deleted=False)
- if team_ids:
- queryset = queryset.filter(team_id__in=team_ids)
-
- findings: list[MaskedSecretFinding] = []
- scanned_count = 0
- truncated = False
-
- for hog_function in _keyset_batches(queryset, batch_size):
- if max_scanned is not None and scanned_count >= max_scanned:
- truncated = True
- break
- scanned_count += 1
- masked_live_inputs = _masked_input_keys(hog_function.encrypted_inputs)
- masked_draft_inputs = _masked_input_keys(hog_function.draft_encrypted_inputs)
- if not masked_live_inputs and not masked_draft_inputs:
- continue
-
- if max_results is not None and len(findings) >= max_results:
- truncated = True
- break
-
- team = hog_function.team
- findings.append(
- MaskedSecretFinding(
- organization_id=team.organization_id,
- organization_name=team.organization.name,
- team_id=team.id,
- team_name=team.name,
- hog_function_id=hog_function.id,
- hog_function_name=hog_function.name or "",
- hog_function_type=hog_function.type or "",
- template_id=hog_function.template_id or "",
- enabled=hog_function.enabled,
- deleted=hog_function.deleted,
- updated_at=hog_function.updated_at,
- masked_live_inputs=masked_live_inputs,
- masked_draft_inputs=masked_draft_inputs,
- # Not `hog_function.url`: that hardcodes the destinations route, which is the
- # wrong page for transformations, site apps, and source webhooks.
- configuration_url=absolute_uri(f"/project/{team.id}/functions/{hog_function.id}"),
- )
- )
-
- return MaskedSecretScan(findings=tuple(findings), scanned_count=scanned_count, truncated=truncated)
-
-
-def scan_hog_flows_for_masked_secrets(
- *,
- team_ids: Sequence[int] | None = None,
- include_archived: bool = False,
- batch_size: int = DEFAULT_BATCH_SIZE,
- max_results: int | None = DEFAULT_MAX_RESULTS,
- max_scanned: int | None = None,
-) -> HogFlowMaskedSecretScan:
- queryset = (
- HogFlow.objects.select_related("team", "team__organization")
- .filter(Q(encrypted_inputs__isnull=False) | Q(draft_encrypted_inputs__isnull=False))
- # The rows carry the full action graph the scan never reads. Defer it so a fleet-wide
- # sweep doesn't drag it over the wire.
- .only(
- "id",
- "name",
- "status",
- "updated_at",
- "encrypted_inputs",
- "draft_encrypted_inputs",
- "team__id",
- "team__name",
- "team__organization__id",
- "team__organization__name",
- )
- )
- if not include_archived:
- queryset = queryset.exclude(status=HogFlow.State.ARCHIVED)
- if team_ids:
- queryset = queryset.filter(team_id__in=team_ids)
-
- findings: list[HogFlowMaskedSecretFinding] = []
- scanned_count = 0
- truncated = False
-
- for hog_flow in _keyset_batches(queryset, batch_size):
- if max_scanned is not None and scanned_count >= max_scanned:
- truncated = True
- break
- scanned_count += 1
- masked_live_inputs = _flow_masked_input_keys(hog_flow.encrypted_inputs)
- masked_draft_inputs = _flow_masked_input_keys(hog_flow.draft_encrypted_inputs)
- if not masked_live_inputs and not masked_draft_inputs:
- continue
-
- if max_results is not None and len(findings) >= max_results:
- truncated = True
- break
-
- team = hog_flow.team
- findings.append(
- HogFlowMaskedSecretFinding(
- organization_id=team.organization_id,
- organization_name=team.organization.name,
- team_id=team.id,
- team_name=team.name,
- hog_flow_id=hog_flow.id,
- hog_flow_name=hog_flow.name or "",
- status=hog_flow.status,
- enabled=hog_flow.status == HogFlow.State.ACTIVE,
- updated_at=hog_flow.updated_at,
- masked_live_inputs=masked_live_inputs,
- masked_draft_inputs=masked_draft_inputs,
- configuration_url=absolute_uri(f"/project/{team.id}/workflows/{hog_flow.id}/workflow"),
- )
- )
-
- return HogFlowMaskedSecretScan(findings=tuple(findings), scanned_count=scanned_count, truncated=truncated)
-
-
-def summarize_by_organization(
- findings: Iterable[MaskedSecretFinding | HogFlowMaskedSecretFinding],
-) -> list[AffectedOrganization]:
- grouped: dict[UUID, list[MaskedSecretFinding | HogFlowMaskedSecretFinding]] = {}
- for finding in findings:
- grouped.setdefault(finding.organization_id, []).append(finding)
-
- summaries = [
- AffectedOrganization(
- organization_id=organization_id,
- organization_name=organization_findings[0].organization_name,
- team_ids=tuple(sorted({finding.team_id for finding in organization_findings})),
- finding_count=len(organization_findings),
- enabled_count=sum(1 for finding in organization_findings if finding.enabled),
- )
- for organization_id, organization_findings in grouped.items()
- ]
- # Enabled destinations and active workflows are the ones actively failing against the third
- # party, so the organizations to contact first sort to the top.
- summaries.sort(key=lambda summary: (-summary.enabled_count, -summary.finding_count))
- return summaries
diff --git a/products/cdp/backend/test/test_masked_secrets.py b/products/cdp/backend/test/test_masked_secrets.py
deleted file mode 100644
index d9ce0d72ff4d..000000000000
--- a/products/cdp/backend/test/test_masked_secrets.py
+++ /dev/null
@@ -1,278 +0,0 @@
-from uuid import uuid4
-
-from posthog.test.base import BaseTest
-from unittest.mock import patch
-
-from django.test import SimpleTestCase
-from django.urls import reverse
-from django.utils import timezone
-
-from parameterized import parameterized
-
-from posthog.admin import register_all_admin
-from posthog.cdp.validation import MASKED_SECRET_VALUE
-
-from products.cdp.backend.models.hog_functions.hog_function import HogFunction
-from products.cdp.backend.services.masked_secrets import (
- MaskedSecretFinding,
- _flow_masked_input_keys,
- _masked_input_keys,
- scan_for_masked_secrets,
- scan_hog_flows_for_masked_secrets,
- summarize_by_organization,
-)
-from products.workflows.backend.models.hog_flow.hog_flow import HogFlow
-
-SECRET_SCHEMA = [{"key": "api_key", "type": "string", "secret": True}]
-
-# The workflows read-back marker: what the API sends for a set secret, and what must never end up
-# stored as the secret itself.
-FLOW_MARKER = {"secret": True}
-
-# `posthog/apps.py` installs the lazy admin registry only `if not settings.TEST`, and that wrapper
-# is the sole caller of `register_all_admin()` — so under tests nothing registers this admin and
-# its custom URLs cannot be reversed.
-register_all_admin()
-
-
-def _finding(*, organization_id, enabled: bool) -> MaskedSecretFinding:
- return MaskedSecretFinding(
- organization_id=organization_id,
- organization_name="Org",
- team_id=1,
- team_name="Team",
- hog_function_id=uuid4(),
- hog_function_name="Destination",
- hog_function_type="destination",
- template_id="template-customerio",
- enabled=enabled,
- deleted=False,
- updated_at=timezone.now(),
- masked_live_inputs=("api_key",),
- masked_draft_inputs=(),
- configuration_url="https://example.com/config",
- )
-
-
-class TestMaskedInputKeys(SimpleTestCase):
- @parameterized.expand(
- [
- ("mask", {"api_key": {"value": MASKED_SECRET_VALUE}}, ("api_key",)),
- ("real_secret", {"api_key": {"value": "sk-live-abc"}}, ()),
- ("mask_substring", {"api_key": {"value": f"{MASKED_SECRET_VALUE}abc"}}, ()),
- ("no_value_key", {"api_key": {"secret": True}}, ()),
- (
- "several_masked_keys",
- {"token": {"value": MASKED_SECRET_VALUE}, "api_key": {"value": MASKED_SECRET_VALUE}},
- ("api_key", "token"),
- ),
- # A row encrypted under a key we no longer hold reads back as the raw ciphertext
- # string, because the field swallows InvalidToken rather than raising.
- ("undecryptable_ciphertext", "gAAAAABm-not-a-dict", ()),
- ("none", None, ()),
- ("entry_is_not_a_dict", {"api_key": "plain"}, ()),
- ]
- )
- def test_masked_input_keys(self, _name: str, stored: object, expected: tuple[str, ...]) -> None:
- assert _masked_input_keys(stored) == expected
-
-
-class TestFlowMaskedInputKeys(SimpleTestCase):
- @parameterized.expand(
- [
- ("persisted_marker", {"a1": {"api_key": FLOW_MARKER}}, ("a1.api_key",)),
- (
- "marker_with_mask_value",
- {"a1": {"api_key": {"secret": True, "value": MASKED_SECRET_VALUE}}},
- ("a1.api_key",),
- ),
- ("literal_mask_value", {"a1": {"api_key": {"value": MASKED_SECRET_VALUE}}}, ("a1.api_key",)),
- ("real_secret", {"a1": {"api_key": {"value": "sk-live-abc"}}}, ()),
- ("marker_with_real_value", {"a1": {"api_key": {"secret": True, "value": "sk-live-abc"}}}, ()),
- (
- "several_actions_sorted",
- {"b2": {"token": FLOW_MARKER}, "a1": {"api_key": FLOW_MARKER}},
- ("a1.api_key", "b2.token"),
- ),
- ("undecryptable_ciphertext", "gAAAAABm-not-a-dict", ()),
- ("action_map_is_not_a_dict", {"a1": "plain"}, ()),
- ("entry_is_not_a_dict", {"a1": {"api_key": "plain"}}, ()),
- ]
- )
- def test_flow_masked_input_keys(self, _name: str, stored: object, expected: tuple[str, ...]) -> None:
- assert _flow_masked_input_keys(stored) == expected
-
-
-class TestSummarizeByOrganization(SimpleTestCase):
- def test_organizations_with_enabled_functions_sort_first(self) -> None:
- disabled_org, enabled_org = uuid4(), uuid4()
- findings = [
- _finding(organization_id=disabled_org, enabled=False),
- _finding(organization_id=disabled_org, enabled=False),
- _finding(organization_id=enabled_org, enabled=True),
- ]
-
- summaries = summarize_by_organization(findings)
-
- assert [summary.organization_id for summary in summaries] == [enabled_org, disabled_org]
- assert summaries[0].enabled_count == 1
- assert summaries[1].finding_count == 2
-
-
-class MaskedSecretsDatabaseTest(BaseTest):
- def setUp(self) -> None:
- super().setUp()
- for target in (
- "products.cdp.backend.models.hog_functions.hog_function.reload_hog_functions_on_workers",
- "products.workflows.backend.models.hog_flow.hog_flow.reload_hog_flows_on_workers",
- ):
- patcher = patch(target)
- patcher.start()
- self.addCleanup(patcher.stop)
-
- def _create_hog_function(
- self,
- *,
- secret_value: str | None = MASKED_SECRET_VALUE,
- draft_secret_value: str | None = None,
- deleted: bool = False,
- enabled: bool = True,
- ) -> HogFunction:
- hog_function = HogFunction.objects.create(
- team=self.team,
- name="Send events to a third party",
- type="destination",
- template_id="template-customerio",
- enabled=enabled,
- deleted=deleted,
- hog="return event",
- inputs_schema=SECRET_SCHEMA,
- inputs={"api_key": {"value": secret_value}} if secret_value is not None else {},
- )
- if draft_secret_value is not None:
- hog_function.draft_encrypted_inputs = {"api_key": {"value": draft_secret_value}}
- hog_function.save(update_fields=["draft_encrypted_inputs"])
- return hog_function
-
- def _create_hog_flow(
- self,
- *,
- encrypted: dict | None = None,
- draft_encrypted: dict | None = None,
- status: str = "active",
- ) -> HogFlow:
- return HogFlow.objects.create(
- team=self.team,
- name="Send emails to a third party",
- status=status,
- encrypted_inputs=encrypted,
- draft_encrypted_inputs=draft_encrypted,
- )
-
-
-class TestScanForMaskedSecrets(MaskedSecretsDatabaseTest):
- def test_reports_masked_live_secret_and_ignores_a_real_one(self) -> None:
- masked = self._create_hog_function(secret_value=MASKED_SECRET_VALUE)
- self._create_hog_function(secret_value="sk-live-abc")
-
- scan = scan_for_masked_secrets()
-
- assert [finding.hog_function_id for finding in scan.findings] == [masked.id]
- assert scan.findings[0].masked_live_inputs == ("api_key",)
- assert scan.findings[0].organization_id == self.organization.id
- assert scan.scanned_count == 2
-
- def test_reports_a_masked_draft_secret_on_a_healthy_function(self) -> None:
- hog_function = self._create_hog_function(secret_value="sk-live-abc", draft_secret_value=MASKED_SECRET_VALUE)
-
- scan = scan_for_masked_secrets()
-
- assert [finding.hog_function_id for finding in scan.findings] == [hog_function.id]
- assert scan.findings[0].masked_live_inputs == ()
- assert scan.findings[0].masked_draft_inputs == ("api_key",)
-
- @parameterized.expand([("excluded_by_default", False, 0), ("included_on_request", True, 1)])
- def test_deleted_hog_functions(self, _name: str, include_deleted: bool, expected_count: int) -> None:
- self._create_hog_function(deleted=True)
-
- scan = scan_for_masked_secrets(include_deleted=include_deleted)
-
- assert len(scan.findings) == expected_count
-
- def test_hitting_the_cap_is_reported_rather_than_silently_truncating(self) -> None:
- self._create_hog_function()
- self._create_hog_function()
-
- scan = scan_for_masked_secrets(max_results=1)
-
- assert len(scan.findings) == 1
- assert scan.truncated is True
-
- def test_batches_neither_skip_nor_repeat_rows(self) -> None:
- created = {self._create_hog_function().id for _ in range(3)}
-
- scan = scan_for_masked_secrets(batch_size=1)
-
- assert {finding.hog_function_id for finding in scan.findings} == created
- assert scan.scanned_count == 3
-
- def test_hitting_the_scan_ceiling_is_reported_rather_than_silently_truncating(self) -> None:
- self._create_hog_function(secret_value="sk-live-abc")
- self._create_hog_function(secret_value="sk-live-abc")
-
- scan = scan_for_masked_secrets(max_scanned=1)
-
- assert scan.scanned_count == 1
- assert scan.truncated is True
-
-
-class TestScanHogFlowsForMaskedSecrets(MaskedSecretsDatabaseTest):
- def test_reports_a_persisted_marker_and_ignores_a_real_secret(self) -> None:
- poisoned = self._create_hog_flow(encrypted={"action_1": {"api_key": FLOW_MARKER}})
- self._create_hog_flow(encrypted={"action_1": {"api_key": {"value": "sk-live-abc"}}})
-
- scan = scan_hog_flows_for_masked_secrets()
-
- assert [finding.hog_flow_id for finding in scan.findings] == [poisoned.id]
- assert scan.findings[0].masked_live_inputs == ("action_1.api_key",)
- assert scan.findings[0].organization_id == self.organization.id
- assert scan.scanned_count == 2
-
- def test_reports_a_marker_stored_only_on_the_draft(self) -> None:
- hog_flow = self._create_hog_flow(
- encrypted={"action_1": {"api_key": {"value": "sk-live-abc"}}},
- draft_encrypted={"action_1": {"api_key": FLOW_MARKER}},
- )
-
- scan = scan_hog_flows_for_masked_secrets()
-
- assert [finding.hog_flow_id for finding in scan.findings] == [hog_flow.id]
- assert scan.findings[0].masked_live_inputs == ()
- assert scan.findings[0].masked_draft_inputs == ("action_1.api_key",)
-
- @parameterized.expand([("excluded_by_default", False, 0), ("included_on_request", True, 1)])
- def test_archived_hog_flows(self, _name: str, include_archived: bool, expected_count: int) -> None:
- self._create_hog_flow(encrypted={"action_1": {"api_key": FLOW_MARKER}}, status="archived")
-
- scan = scan_hog_flows_for_masked_secrets(include_archived=include_archived)
-
- assert len(scan.findings) == expected_count
-
-
-class TestMaskedSecretsAdmin(MaskedSecretsDatabaseTest):
- def setUp(self) -> None:
- super().setUp()
- self.user.is_staff = True
- self.user.save()
- self.client.force_login(self.user)
-
- def test_the_page_renders_the_findings(self) -> None:
- hog_function = self._create_hog_function()
- hog_flow = self._create_hog_flow(encrypted={"action_1": {"api_key": FLOW_MARKER}})
-
- response = self.client.post(reverse("admin:hog-function-masked-secrets"), {"max_results": 100, "_scan": "Scan"})
-
- assert response.status_code == 200
- content = response.content.decode()
- assert str(hog_function.id) in content
- assert str(hog_flow.id) in content
diff --git a/tach.toml b/tach.toml
index c0bb5c8e619d..2f531539cdc1 100644
--- a/tach.toml
+++ b/tach.toml
@@ -201,7 +201,6 @@ depends_on = [
"posthog",
"products.actions",
"products.batch_exports",
- "products.workflows",
]
layer = "modules"