: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(hogli): gate secret-wrap on per-command needs_secrets flag (#59373)
Julian Bez40bc32ee6ddf
diff --git a/hogli.yaml b/hogli.yamlindex ed676437cacd..8245d5196efa 100644--- a/hogli.yaml+++ b/hogli.yaml@@ -291,6 +291,7 @@ start:start:bin_script: startdescription: Launch all dev services via phrocs (interactive TUI, or `-d` for detached mode)+ needs_secrets: trueservices:- phrocs- mprocs@@ -306,7 +307,7 @@ start:- clickhouse- temporalup:- bin_script: start+ extends: startdescription: Alias for `hogli start`; use `-d` for optional detached modewait:cmd: phrocs wait@@ -323,6 +324,9 @@ start:start:backend:bin_script: start-backenddescription: Run Django development server on port 8000 with auto-reload+ # Django runtime — Max / AI features / Stripe billing all read keys+ # from .env.local at request time.+ needs_secrets: trueservices:- django- postgresql@@ -331,6 +335,8 @@ start:start:celery:bin_script: start-celerydescription: Start Celery worker or beat scheduler with auto-reload+ # Celery jobs hit AI providers (session summaries, batch exports, ...).+ needs_secrets: trueservices:- celery- redis@@ -350,6 +356,9 @@ start:start:worker:bin_script: start-workerdescription: Launch all background workers (Celery worker, beat scheduler, nodejs, ingestion)+ # Workers run AI / billing / ingestion code paths that touch external+ # providers — they need the runtime keys resolved.+ needs_secrets: trueservices:- celery- nodejs@@ -361,10 +370,14 @@ start:start:rust-service:bin_script: start-rust-servicedescription: Build and run live Rust microservice with auto-restart on crash+ # Rust services include batch-import-worker etc. that talk to Stripe+ # and other external endpoints.+ needs_secrets: truehidden: truestart:go:service:bin_script: start-go-servicedescription: Build and run Go microservices with auto-restart on crash+ needs_secrets: truehidden: truedeploy:deploy:hobby:@@ -843,18 +856,22 @@ tools:start:llm:gateway:bin_script: start-llm-gatewaydescription: Start the LLM gateway service+ needs_secrets: truehidden: trueposthog:node:bin_script: posthog-nodedescription: Start the posthog-node service (old plugin-server)+ needs_secrets: truehidden: truestart:mcp:server:bin_script: start-mcp-serverdescription: Start the MCP server+ needs_secrets: truehidden: truestart:stripe:app:bin_script: start-stripe-appdescription: Start the Stripe app dev server (requires Stripe CLI)+ needs_secrets: truegenerate_personhog_proto:bin_script: generate_personhog_proto.shdescription: 'TODO: add description for generate_personhog_proto.sh'diff --git a/tools/hogli/AGENTS.md b/tools/hogli/AGENTS.mdindex af6e851fdaa4..39bc5632d766 100644--- a/tools/hogli/AGENTS.md+++ b/tools/hogli/AGENTS.md@@ -48,7 +48,9 @@ Even 1Password's own docs don't recommend a "task runner integration" — they j**In core (generic):**- `config.env.files: [...]` — list of dotenv files, loaded in order, first wins, shell env always wins.-- `config.env.secrets.{file, marker, wrap}` — optional generic wrapper hook. When the secrets file contains the marker substring AND the wrap binary is on PATH, hogli re-execs the whole invocation under the wrap command. When the binary isn't installed, hogli loads the file directly with marker-matching lines skipped (so literals don't leak as garbage strings). A `HOGLI_SECRETS_WRAPPED=1` sentinel prevents re-exec loops.+- `config.env.secrets.{file, marker, wrap}` — optional generic wrapper hook. Re-execs the invocation under `wrap` when (1) the invoked subcommand opts in via `needs_secrets: true`, (2) the file contains `marker`, and (3) `wrap[0]` is on PATH. Otherwise loads the file directly with marker-matching lines skipped, so literals don't leak as garbage strings.+- `HOGLI_SECRETS_WRAPPED=1` sentinel — set before the wrap re-exec, inherited by subprocesses so composite/steps chains don't re-prompt for auth on every step.+- Per-command `needs_secrets: true` — opt-in gate for the wrap. Without it the wrap never fires; the built-in `hogli run` is the one framework command that always opts in.**Not in core:**diff --git a/tools/hogli/README.md b/tools/hogli/README.mdindex c49318f665b9..20f939ab1dfc 100644--- a/tools/hogli/README.md+++ b/tools/hogli/README.md@@ -111,6 +111,7 @@ my:command:description: Short description for --helpdestructive: true # Prompts for confirmation before runninghidden: true # Hides from --help (still runnable)+ needs_secrets: true # Triggers the configured `env.secrets.wrap` (see below)```## Python Commands@@ -288,18 +289,40 @@ config:wrap: [op, run, --env-file, '{file}', --]```-What happens at startup:+Opt commands into the wrap with `needs_secrets: true` on the manifest entry:++```yaml+start:+ bin_script: start+ description: Launch the dev stack+ needs_secrets: true # this command needs runtime secrets resolved+```++Commands without the flag never trigger the wrap — important because some+wrap binaries (1Password's `op` on macOS, for example) prompt for biometric+auth on every invocation, and you don't want lint / format / typecheck /+pre-commit hooks pulling on that. The built-in `hogli run <cmd>` always+opts in, since its whole job is to forward the resolved env.++What happens at startup, for a command that opted in:1. If the secrets file exists AND contains `marker` AND `wrap[0]` is on `PATH`:hogli re-execs itself under `wrap` (with `{file}` substituted to theabsolute path of the secrets file). The wrap binary resolves secrets andre-runs hogli with them in the env. A `HOGLI_SECRETS_WRAPPED=1` sentinel- prevents infinite re-exec loops.+ is set in the wrap-child's env and is **inherited by any subprocesses it+ spawns** (so composite commands like `dev:reset` only prompt for auth+ once, not once per step).2. If the wrap binary is missing or the marker isn't present, hogli loads thefile directly with marker-matching lines skipped (so unresolved `op://...`strings don't leak as garbage env values that produce confusing 401sdownstream — only literal values get loaded).+For commands without `needs_secrets: true`, hogli skips the wrap entirely+and only loads literal values from the secrets file (marker-matching lines+are skipped). So `.env.local` stays useful for non-secret overrides+(`DEBUG=1` etc.) even when the wrap doesn't fire.+Precedence in either path (highest wins): shell env > secrets file > envfiles. So a literal override in `.env.local` always beats `.env.development`,matching what `op run` does when it's available.diff --git a/tools/hogli/src/hogli/cli.py b/tools/hogli/src/hogli/cli.pyindex c72c05a098eb..7886418b8e1f 100644--- a/tools/hogli/src/hogli/cli.py+++ b/tools/hogli/src/hogli/cli.py@@ -22,7 +22,14 @@ from hogli import telemetryfrom hogli.command_types import BinScriptCommand, CompositeCommand, DirectCommand, HogliCommandfrom hogli.hooks import post_command_hooks, telemetry_property_hooksfrom hogli.lazy_commands import add_commands_dir_to_path, add_repo_root_to_path, resolve_click_command-from hogli.manifest import REPO_ROOT, get_category_for_command, get_manifest, get_services_for_command, load_manifest+from hogli.manifest import (+ REPO_ROOT,+ Manifest,+ get_category_for_command,+ get_manifest,+ get_services_for_command,+ load_manifest,+)from hogli.validate import auto_update_manifest, find_missing_manifest_entries, find_orphan_manifest_entries_DEFAULT_HELP = "Developer CLI framework with YAML-based command definitions."@@ -175,7 +182,7 @@ def cli(ctx: click.Context) -> None:# Skip env loading during shell completion — completion fires this# callback for every Tab press and doesn't need the env populated.if not ctx.resilient_parsing:- _apply_env_config()+ _apply_env_config(ctx.invoked_subcommand)# Auto-update manifest on every invocation (but skip for meta:check and git hooks)# Skip during git hooks to prevent manifest modifications during lint-staged executionin_git_hook = os.environ.get("GIT_DIR") is not None or os.environ.get("HUSKY") is not None@@ -268,6 +275,10 @@ _SECRETS_WRAPPED_ENV = "HOGLI_SECRETS_WRAPPED"# argv. Kept as a constant so the README, AGENTS.md, and runtime stay in sync._WRAP_FILE_PLACEHOLDER = "{file}"+# Built-in commands whose contract is "forward the resolved env" (e.g.+# `hogli run`). Manifest commands opt in via `needs_secrets: true`.+_BUILTIN_COMMANDS_NEEDING_SECRETS = frozenset({"run"})+def _load_env_file(path: os.PathLike[str],@@ -303,29 +314,21 @@ def _load_env_file(os.environ[name] = value-def _apply_env_config() -> None:+def _apply_env_config(invoked_subcommand: str | None = None) -> None:"""Apply ``config.env`` from hogli.yaml: load files, optionally re-exec via wrap.- Behavior depends on what's declared in the manifest:-- - No ``config.env``: no-op. hogli stays a transparent CLI.- - ``config.env.files``: each file is loaded with only_if_unset=True. First- file in the list wins for duplicate keys; shell env always wins.- - ``config.env.secrets``: wrapper for a secrets file (e.g. one containing- 1Password ``op://`` refs).- * If the file exists, contains the marker, and the wrap binary is on- PATH: set the ``HOGLI_SECRETS_WRAPPED`` sentinel and ``execvp`` into- the wrap command, which re-runs hogli with secrets resolved. Files- are pre-loaded so wrap's child inherits them.- * If the wrap binary is missing or the marker doesn't hit, load the- file directly. Lines whose value contains the marker are skipped- (so unresolved refs don't leak as garbage env values).- * If the sentinel is already set we are the child of a wrap re-exec —- skip the wrap entirely and proceed to load the files normally.-- Precedence (in both wrap-resolved and fallback paths, highest wins):- shell env > secrets file > env files (earlier files in the list win for- duplicate keys).+ - No ``config.env``: no-op.+ - ``config.env.files``: each file loaded with only_if_unset=True; first+ listed wins for duplicate keys; shell env always wins.+ - ``config.env.secrets``: secrets file. Wrap re-exec is gated on+ ``_command_needs_secrets`` — when open, the file exists, the marker+ matches, and ``wrap[0]`` is on PATH, set the ``HOGLI_SECRETS_WRAPPED``+ sentinel and ``execvp`` into the wrap (which re-runs hogli with+ secrets resolved). Otherwise load the file directly with+ marker-matching lines skipped, so unresolved refs don't leak as+ literal env values.++ Precedence (highest wins): shell env > secrets file > env files."""manifest = get_manifest()try:@@ -335,24 +338,40 @@ def _apply_env_config() -> None:click.echo(f"⚠️ Invalid config.env in hogli.yaml: {e}", err=True)return- # Consume the sentinel — we're either the wrap-child (sentinel set) or- # the initial parent (sentinel unset). Pop so the sentinel never leaks- # to subprocesses or repeat in-process calls.- already_wrapped = os.environ.pop(_SECRETS_WRAPPED_ENV, None) is not None+ # Don't pop: subprocesses spawned by composite/steps commands need to+ # inherit this so they skip a redundant wrap re-exec. In-process callers+ # that want to retrigger the wrap must clear it themselves.+ already_wrapped = _SECRETS_WRAPPED_ENV in os.environif secrets is not None and not already_wrapped:- _maybe_reexec_via_wrap(secrets, env_files)+ if _command_needs_secrets(invoked_subcommand, manifest):+ _maybe_reexec_via_wrap(secrets, env_files)- # Reached here = no re-exec happened (no marker hit, file missing, or- # wrap binary missing). Load secrets BEFORE env_files so .env.local- # literals override .env.development / .env.services — matches the- # wrap-resolved path's precedence (where op layers .env.local on top).+ # Load secrets BEFORE env_files so .env.local literals override+ # .env.development / .env.services — matches the wrap-resolved+ # path's precedence (where op layers .env.local on top)._load_env_file(secrets["file"], only_if_unset=True, skip_pattern=secrets["marker"])for path in env_files:_load_env_file(path, only_if_unset=True)+def _command_needs_secrets(invoked_subcommand: str | None, manifest: Manifest) -> bool:+ """Whether the invoked command opts into the secret wrap.++ Two sources, in order: built-in framework commands+ (``_BUILTIN_COMMANDS_NEEDING_SECRETS``), then ``needs_secrets: true`` on+ the manifest entry. Default False — most commands don't need secrets and+ shouldn't pay the wrap cost.+ """+ if not invoked_subcommand:+ return False+ if invoked_subcommand in _BUILTIN_COMMANDS_NEEDING_SECRETS:+ return True+ cmd_config = manifest.get_command_config(invoked_subcommand) or {}+ return bool(cmd_config.get("needs_secrets"))++def _maybe_reexec_via_wrap(secrets: dict[str, Any], env_files: list[Path]) -> None:"""Re-exec hogli under the configured wrap command if the secrets file warrants it.diff --git a/tools/hogli/tests/test_cli.py b/tools/hogli/tests/test_cli.pyindex e35c2ec6fb1b..c8d1cd2648df 100644--- a/tools/hogli/tests/test_cli.py+++ b/tools/hogli/tests/test_cli.py@@ -291,10 +291,25 @@ class TestApplyEnvConfig:manifest also keeps existing PostHog tests in the same file unaffected."""- def _make_manifest(self, env_files=None, secrets_config=None) -> MagicMock:+ def _make_manifest(+ self,+ env_files=None,+ secrets_config=None,+ needs_secrets_commands: set[str] | None = None,+ ) -> MagicMock:+ """Build a fake Manifest. ``needs_secrets_commands`` is the set of+ invoked-subcommand names whose ``get_command_config`` lookup returns+ ``needs_secrets: true``. Any name not in the set returns an empty+ config (the realistic default for opted-out commands)."""m = MagicMock()m.env_files = env_files or []m.secrets_config = secrets_config+ opted_in = needs_secrets_commands or set()++ def get_command_config(name: str) -> dict:+ return {"needs_secrets": True} if name in opted_in else {}++ m.get_command_config.side_effect = get_command_configreturn mdef test_no_env_config_is_noop(self, monkeypatch: pytest.MonkeyPatch) -> None:@@ -308,7 +323,7 @@ class TestApplyEnvConfig:monkeypatch.delenv("UNRELATED_VAR", raising=False)before = dict(os.environ)- _apply_env_config()+ _apply_env_config("start")assert os.environ == before@@ -328,7 +343,7 @@ class TestApplyEnvConfig:for k in ("SHARED", "ONLY_FIRST", "ONLY_SECOND", "HOGLI_SECRETS_WRAPPED"):monkeypatch.delenv(k, raising=False)- _apply_env_config()+ _apply_env_config("anything")assert os.environ["SHARED"] == "from_first"assert os.environ["ONLY_FIRST"] == "1"@@ -348,7 +363,7 @@ class TestApplyEnvConfig:monkeypatch.setenv("OVERRIDE_ME", "from_shell")monkeypatch.delenv("HOGLI_SECRETS_WRAPPED", raising=False)- _apply_env_config()+ _apply_env_config("anything")assert os.environ["OVERRIDE_ME"] == "from_shell"@@ -368,13 +383,16 @@ class TestApplyEnvConfig:}monkeypatch.setattr("hogli.cli.get_manifest",- lambda: self._make_manifest(secrets_config=secrets),+ lambda: self._make_manifest(+ secrets_config=secrets,+ needs_secrets_commands={"start"},+ ),)monkeypatch.delenv("PLAIN_KEY", raising=False)monkeypatch.delenv("HOGLI_SECRETS_WRAPPED", raising=False)with patch("os.execvp") as mock_exec:- _apply_env_config()+ _apply_env_config("start")mock_exec.assert_not_called()assert os.environ["PLAIN_KEY"] == "plain_value"@@ -399,13 +417,17 @@ class TestApplyEnvConfig:}monkeypatch.setattr("hogli.cli.get_manifest",- lambda: self._make_manifest(env_files=[env_file], secrets_config=secrets),+ lambda: self._make_manifest(+ env_files=[env_file],+ secrets_config=secrets,+ needs_secrets_commands={"start"},+ ),)for k in ("SHARED_KEY", "DEV_ONLY", "HOGLI_SECRETS_WRAPPED"):monkeypatch.delenv(k, raising=False)with patch("os.execvp") as mock_exec:- _apply_env_config()+ _apply_env_config("start")mock_exec.assert_not_called()assert os.environ["SHARED_KEY"] == "local_wins"@@ -426,19 +448,24 @@ class TestApplyEnvConfig:}monkeypatch.setattr("hogli.cli.get_manifest",- lambda: self._make_manifest(env_files=[env_file], secrets_config=secrets),+ lambda: self._make_manifest(+ env_files=[env_file],+ secrets_config=secrets,+ needs_secrets_commands={"start"},+ ),)for k in ("DEV_ONLY", "HOGLI_SECRETS_WRAPPED"):monkeypatch.delenv(k, raising=False)with patch("os.execvp") as mock_exec:- _apply_env_config()+ _apply_env_config("start")mock_exec.assert_not_called()assert os.environ["DEV_ONLY"] == "ok"def test_marker_hit_with_wrap_binary_present_reexecs(self, tmp_path, monkeypatch: pytest.MonkeyPatch) -> None:- """When marker matches and wrap binary is on PATH, hogli re-execs under it.+ """When marker matches AND the invoked command opts into needs_secrets+ AND the wrap binary is on PATH, hogli re-execs under the wrap.Verifies the wrap command is built with `{file}` substituted, thesentinel is set so the child won't loop, and pre-existing env_files@@ -458,7 +485,11 @@ class TestApplyEnvConfig:}monkeypatch.setattr("hogli.cli.get_manifest",- lambda: self._make_manifest(env_files=[env_file], secrets_config=secrets),+ lambda: self._make_manifest(+ env_files=[env_file],+ secrets_config=secrets,+ needs_secrets_commands={"start"},+ ),)for k in ("PRELOADED", "HOGLI_SECRETS_WRAPPED"):monkeypatch.delenv(k, raising=False)@@ -467,7 +498,7 @@ class TestApplyEnvConfig:patch("shutil.which", return_value="/usr/local/bin/op"),patch("os.execvp") as mock_exec,):- _apply_env_config()+ _apply_env_config("start")mock_exec.assert_called_once()args, _kwargs = mock_exec.call_args@@ -504,7 +535,10 @@ class TestApplyEnvConfig:}monkeypatch.setattr("hogli.cli.get_manifest",- lambda: self._make_manifest(secrets_config=secrets),+ lambda: self._make_manifest(+ secrets_config=secrets,+ needs_secrets_commands={"start"},+ ),)for k in ("OPENAI_API_KEY", "LITERAL", "HOGLI_SECRETS_WRAPPED"):monkeypatch.delenv(k, raising=False)@@ -513,7 +547,7 @@ class TestApplyEnvConfig:patch("shutil.which", return_value=None),patch("os.execvp") as mock_exec,):- _apply_env_config()+ _apply_env_config("start")mock_exec.assert_not_called()assert "OPENAI_API_KEY" not in os.environ@@ -526,6 +560,11 @@ class TestApplyEnvConfig:"""After wrap re-execs hogli, the child sees HOGLI_SECRETS_WRAPPED and skips wrap.Without this, the wrap binary would re-exec hogli forever.++ Also verifies the sentinel PERSISTS in env after the wrap-child runs,+ so subprocesses spawned by composite/steps commands inherit it and+ also skip their own wrap (no cascading auth prompts on chained+ invocations like `dev:reset`)."""from hogli.cli import _apply_env_config@@ -539,7 +578,10 @@ class TestApplyEnvConfig:}monkeypatch.setattr("hogli.cli.get_manifest",- lambda: self._make_manifest(secrets_config=secrets),+ lambda: self._make_manifest(+ secrets_config=secrets,+ needs_secrets_commands={"start"},+ ),)# Simulate being the child of a wrap re-exec: sentinel set, wrap already# populated the env via op run (so OPENAI_API_KEY would be in env).@@ -547,10 +589,55 @@ class TestApplyEnvConfig:monkeypatch.setenv("API_KEY", "resolved_by_op")with patch("os.execvp") as mock_exec:- _apply_env_config()+ _apply_env_config("start")mock_exec.assert_not_called()# Wrap binary's resolved value wins; the file isn't sourced over itassert os.environ["API_KEY"] == "resolved_by_op"- # Sentinel is consumed so subsequent in-process calls behave normally- assert "HOGLI_SECRETS_WRAPPED" not in os.environ+ # Sentinel must STAY in env so subprocesses spawned by this wrap-child+ # inherit it and skip re-wrapping. Popping would re-trigger auth+ # prompts for every step in a composite chain.+ assert os.environ["HOGLI_SECRETS_WRAPPED"] == "1"++ @pytest.mark.parametrize(+ "invoked_subcommand,opted_in,expect_wrap",+ [+ (None, {"start"}, False),+ ("lint", {"start"}, False),+ ("run", set(), True),+ ],+ ids=["no-subcommand", "manifest-opted-out", "builtin-run"],+ )+ def test_gate_controls_wrap_reexec(+ self,+ tmp_path,+ monkeypatch: pytest.MonkeyPatch,+ invoked_subcommand: str | None,+ opted_in: set[str],+ expect_wrap: bool,+ ) -> None:+ from hogli.cli import _apply_env_config++ secrets_file = tmp_path / ".env.local"+ secrets_file.write_text("API_KEY=op://vault/item/credential\n")+ secrets = {+ "file": secrets_file,+ "marker": "op://",+ "wrap": ["op", "run", "--env-file", "{file}", "--"],+ }+ monkeypatch.setattr(+ "hogli.cli.get_manifest",+ lambda: self._make_manifest(secrets_config=secrets, needs_secrets_commands=opted_in),+ )+ monkeypatch.delenv("HOGLI_SECRETS_WRAPPED", raising=False)++ with (+ patch("shutil.which", return_value="/usr/local/bin/op"),+ patch("os.execvp") as mock_exec,+ ):+ _apply_env_config(invoked_subcommand)++ if expect_wrap:+ mock_exec.assert_called_once()+ else:+ mock_exec.assert_not_called()