Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions changelog.d/1124.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
### Fixed
- **Release pushes reach the person's credential helper (`devops release pr`, `devops release prepare --create-pr`, `devops release tag --push`)**:
- The cut branch push, the release tag push and the cut's fetch of the release branch now run git with the person's whole environment, as their own `git push` does. The devcontainer's helper in `GIT_CONFIG_*`, VS Code's helper socket, the keyring's session bus and an SSH agent reach git. Before, the sanitized subprocess environment dropped them, and git failed with "could not read Username" (#1124).
- Git still gets only the session's GitHub token (#767). It no longer asks for a username on the terminal, though an askpass program the person configured, such as VS Code's, still runs (#1124).
- A failed push or fetch stops the command with git's reason, credentials masked and its text shown as written, so `[remote rejected]` keeps its brackets. A failed fetch of the release branch no longer lets the cut go on from a stale `origin/release/v<version>` (#1124).
- `release tag --push` pushes the release tag alone (`refs/tags/v<version>`), not every local tag (#1124).
- From an agent's shell, `release pr` and `release tag --push` now authenticate. `release prepare --create-pr` and the automatic cut push a new commit to `release/v<version>`. GitHub's ruleset still refuses that push (GH013) until #1280 (#1124).
49 changes: 49 additions & 0 deletions docs/agent/tasks/task-1124-release-push-person-environment.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
# Task: Release pushes run git with the person's environment, so the configured credential helper answers instead of "could not read Username" (#1124)

**Issue**: [#1124](https://github.com/dan-petty/devops-cli/issues/1124)
**Status**: Done
**Milestone**: v0.2.29
**Priority**: priority/p1-high
**Scope**: type/bug, scope/release, priority/p1-high

## Description
`devops release pr`, `devops release prepare --create-pr` and `devops release tag --push` ran their pushes through `run_subprocess`'s sanitized environment. It drops everything a credential helper needs: the devcontainer's `!gh auth git-credential` helper, set in `GIT_CONFIG_COUNT` and `GIT_CONFIG_KEY_<n>`/`GIT_CONFIG_VALUE_<n>`; VS Code's helper socket (`REMOTE_CONTAINERS_IPC`); the keyring's session bus; and an SSH agent. #767's pinned `GH_TOKEN` reached git, but in the devcontainer no helper was left to read it, so git asked for a username on a terminal it did not have and failed with "could not read Username".

The git calls in `src/devops_cli/commands/release.py` that reach origin now go through `_run_remote_git_or_exit`: the cut branch push, the release tag push, and the cut's fetch of `origin/release/v<version>`. It calls `run_subprocess(..., isolate_env=False, env=CONST_GIT_NO_TERMINAL_PROMPT_ENV)`. Git gets the person's whole environment, as their own `git push` does. `_pin_github_token` still gives it the session's token as `GH_TOKEN` and no `GITHUB_TOKEN`, or no token at all when gh has no login (#767). `GIT_TERMINAL_PROMPT=0` stops git from asking on the terminal. An askpass program the person configured (`GIT_ASKPASS`, `core.askPass` or `SSH_ASKPASS`, such as VS Code's) still runs, and when none answers, git fails with "terminal prompts disabled". When git fails, `_run_remote_git_or_exit` prints git's reason with credentials masked (`mask_secrets`) and its text shown as written, and exits 1. A failed push opens no pull request, and a failed fetch cuts nothing from a stale `origin/release/v<version>`. `release tag --push` now pushes `refs/tags/v<version>` alone instead of every local tag. Every other git call keeps the sanitized environment.

## Acceptance Criteria
- [x] The cut branch push (`_commit_and_push_cut_branch`), the tag push (`_push_git_tag`) and the release-branch fetch (`_fetch_remote_release_tip`) run `run_subprocess` with `isolate_env=False` and `GIT_TERMINAL_PROMPT=0`. No other git call does (`test_release_pr_command`, `test_release_notes_tag_and_check_extended`).
- [x] Environment test with real git on `tmp_path`, a local bare `origin` and no network (`test_release_pr_pushes_in_the_persons_git_environment`). The clone's `pre-push` hook, run by `devops release pr`, writes only the variables the test checks, and sees:
- `!fake-helper` from `git config --get-all credential.https://example.com.helper`;
- `GIT_CONFIG_COUNT`, `GIT_CONFIG_KEY_0`, `GIT_CONFIG_VALUE_0`, `DBUS_SESSION_BUS_ADDRESS`, `REMOTE_CONTAINERS_IPC` and `SSH_AUTH_SOCK` as the test set them;
- `GIT_TERMINAL_PROMPT=0`, `GH_TOKEN` equal to the session's pinned token, and no `GITHUB_TOKEN`, although the environment set both to other values;
- with no gh login (`fail_the_github_lookup`), neither `GH_TOKEN` nor `GITHUB_TOKEN`.

On the previous code the hook saw none of the person's variables and no prompt setting.
- [x] A rejected push exits 1 and never calls `gh`. The error names `release/v0.2.26` and carries git's reason as written, with the token in it masked (`test_release_cut_rejected_push_stops_before_gh`):
- `release prepare --create-pr`, refused by the bare remote's `pre-receive` hook. The error keeps git's `[remote rejected]`.
- `release pr`, whose push repeats the remote tip, refused by the clone's `pre-push` hook, which git runs even for an up-to-date push.
- [x] A failed fetch stops the cut (`test_release_cut_stops_when_the_release_branch_fetch_fails`). The remote has deleted `release/v0.2.26` and the clone still holds `origin/release/v0.2.26`. `release pr` exits 1 with "Failed to fetch origin/release/v0.2.26" and git's reason, creates no cut branch, leaves the checkout on its branch, and never calls `gh`. A fetch that succeeds but writes no `origin/release/v<version>` still stops with "does not exist" (`test_release_cut_stops_when_the_fetch_writes_no_tracking_ref`).
- [x] `release tag --push` pushes `git push origin refs/tags/v<version>` and nothing else (`test_release_notes_tag_and_check_extended`). A refused tag push exits 1 with git's reason, the token in it masked, and closes no Release. A `[/bold]` in the reason is printed as text instead of raising `MarkupError` (`test_release_tag_push_and_errors`).
- [x] `src/devops_cli/core/process.py` and `src/devops_cli/git/operations.py` do not change, and `tests/test_subprocess_env_boundary.py` passes unchanged.
- [x] The new cases use local bare remotes, run no real helper and open no socket. Each takes well under 1 s. `uv run devops ci` passes.
- Pending a person: in the devcontainer, on a local branch `try/push-check` (`git switch -c try/push-check`), run `setsid -w uv run python -c "from pathlib import Path; from devops_cli.commands.release import _commit_and_push_cut_branch; _commit_and_push_cut_branch(Path('.'), 'try/push-check', '', commit=False)" < /dev/null`. The push runs this repository's pre-commit `pre-push` stage: when `try/push-check` carries commits origin does not have yet, that stage runs `uv run devops ci`, and the push takes several minutes. The push succeeds without a prompt, and `git ls-remote origin try/push-check` shows `git rev-parse HEAD`. Then run `git push origin --delete try/push-check`, `git switch -` and `git branch -D try/push-check`.

## Decisions and deviations
- **`run_subprocess(isolate_env=False)` instead of GitPython push functions.** The issue proposed `push_branch` and `push_tags` on GitPython's `Remote.push` with `Git.custom_environment`. `custom_environment(NAME=None)` only drops GitPython's own override and never removes an inherited variable. Checked with GitPython 3.2.0: with `GITHUB_TOKEN=other` in the environment, `custom_environment(GITHUB_TOKEN=None)` still handed the child `GITHUB_TOKEN=other`. So that route could not keep #767's rule: `GH_TOKEN` pinned, no `GITHUB_TOKEN`, and no token when the lookup fails. `run_subprocess` already applies that rule to a copy of the environment. It also keeps the subprocess span, metric and timeout, and the existing `run_subprocess` patches in the tests keep any push off the network. No new function was added to `git/operations.py` or `core/process.py`.
- **Not `CONST_GIT_NONINTERACTIVE_ENV`.** Its `GIT_SSH_COMMAND=ssh -o BatchMode=yes` would override a person's own `core.sshCommand`. `CONST_GIT_NO_TERMINAL_PROMPT_ENV` sets `GIT_TERMINAL_PROMPT=0` only, so an askpass program the person configured still answers.
- **The fetch is included, and fails closed.** `_fetch_remote_release_tip`'s `git fetch origin release/v<version>` has the same root cause for a private repository: under the sanitized environment it failed silently, and the cut trusted a stale or missing `origin/release/v<version>`. Its exit status is now read, and a failed fetch stops the cut with git's reason before `rev-parse` or any checkout. This is what #1366's "The cut's branch check fails closed" criterion asks for. #1366 keeps the Service clone's checkout rule.
- **Git's text is shown as written.** The error is printed with `safe=True`, as `_close_release_milestone_safe` prints its warning, so Rich does not read git's or a hook's text as markup. `! [remote rejected]` keeps its brackets, and a `[/bold]` in a remote message cannot raise `MarkupError`.
- **Narrower tag push.** `refs/tags/v<version>` replaces `--tags`, so a release no longer publishes stray local tags or fails on one, and an error concerns exactly one ref.
- **What the inherited environment means.** Every variable of the person's environment reaches git, the helpers they configured, and their own hooks (this repository installs pre-commit's `pre-push` stage). Their own `git push` runs the same programs with the same environment. Scanners, linters and other tools that run on trees devops-cli does not trust keep the sanitized environment. One limit follows: git's own location variables are inherited too. An exported `GIT_DIR` or `GIT_WORK_TREE` (git exports `GIT_DIR` to the hooks it runs in a linked worktree) points the push and the fetch at that repository, while the cut's other git calls, in the sanitized environment, use `--root`. `devops ci` runs its checks in the sanitized environment, so its tests are not affected. The limit is left to #1397.
- **Timeout unchanged.** As before, a push that overruns `DEFAULT_SUBPROCESS_TIMEOUT_SECONDS` stops only git itself (`subprocess.run`), not a helper or hook it started. That is true of every `run_subprocess` call and is not changed here.
- **What works after this item.** From an agent's shell, `release pr` and `release tag --push` authenticate. `release pr`'s push repeats the remote release branch unchanged. This repository's tags come from `.github/workflows/release.yml` when the release merges, not from `release tag --push`. `release prepare --create-pr` and the automatic cut push a new commit to `release/v<version>`. The repository's `release*` ruleset refuses that push, so they now stop with GitHub's GH013 refusal instead of "could not read Username", until #1280 moves the cut's push target. #1280 should push through `_run_remote_git_or_exit`.

## Deliverables
- [x] `src/devops_cli/commands/release.py`: `_run_remote_git_or_exit`; the cut push, the tag push and the release-branch fetch go through it.
- [x] `src/devops_cli/config/constants.py`: `CONST_GIT_NO_TERMINAL_PROMPT_ENV`.
- [x] `tests/test_release.py`:
- added `test_release_pr_pushes_in_the_persons_git_environment`, `test_release_cut_stops_when_the_release_branch_fetch_fails` and `test_release_cut_stops_when_the_fetch_writes_no_tracking_ref`;
- `test_release_pr_pre_receive_hook_rejection` became `test_release_cut_rejected_push_stops_before_gh`, which covers `release pr` as well;
- extended `test_release_tag_push_and_errors`, `test_release_pr_command` and `test_release_notes_tag_and_check_extended`.
- [x] Changelog fragment: `changelog.d/1124.md`.
67 changes: 45 additions & 22 deletions src/devops_cli/commands/release.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,9 @@
CONST_CONVENTIONAL_COMMIT_CATEGORY_ORDER,
CONST_DOCS_DIR_NAME,
CONST_GH_CLI,
CONST_GIT_CLI,
CONST_GIT_MAIN_BRANCH,
CONST_GIT_NO_TERMINAL_PROMPT_ENV,
CONST_GITHUB_HTTPS_PREFIX,
CONST_GITHUB_PULL_REQUEST_BODY_MAX_CHARS,
CONST_GITHUB_RELEASE_BODY_MAX_CHARS,
Expand Down Expand Up @@ -1094,15 +1096,36 @@ def _verify_clean_tree(root: Path) -> None:
raise typer.Exit(1)


def _fetch_remote_release_tip(root: Path, release_branch: str) -> None:
"""Fetch remote release branch from origin and verify its existence."""
remote_ref = f"origin/{release_branch}"
_get("run_subprocess")(
["git", "fetch", "origin", release_branch],
def _run_remote_git_or_exit(root: Path, failure: str, *git_args: str) -> None:
"""Run a git command that reaches origin in the person's own environment, or exit 1 (#1124).

The sanitized environment drops what credential helpers need: a helper set in `GIT_CONFIG_*`,
VS Code's IPC socket, the keyring's session bus, an SSH agent. Git gets the whole
environment instead, as the person's own `git push` does, with the session's GitHub token
pinned (#767) and no terminal prompt. When git fails, `failure` is printed with git's reason,
credentials masked and its text shown as written, and the command exits 1.
"""
from devops_cli.security.sanitizer import mask_secrets

proc = _get("run_subprocess")(
[CONST_GIT_CLI, *git_args],
cwd=root,
capture_output=True,
check=False,
quiet=True,
isolate_env=False,
env=CONST_GIT_NO_TERMINAL_PROMPT_ENV,
)
if proc.returncode != 0:
reason = str(proc.stderr).strip() or str(proc.stdout).strip()
_get("print_error")(f"{failure}: {mask_secrets(reason)}", prefix=False, safe=True)
raise typer.Exit(1)


def _fetch_remote_release_tip(root: Path, release_branch: str) -> None:
"""Fetch remote release branch from origin and verify its existence."""
remote_ref = f"origin/{release_branch}"
_run_remote_git_or_exit(
root, f"Failed to fetch {remote_ref}", "fetch", "origin", release_branch
)
rev_proc = _get("run_subprocess")(
["git", "rev-parse", "--verify", "--quiet", remote_ref],
Expand Down Expand Up @@ -1186,16 +1209,15 @@ def _commit_and_push_cut_branch(
)
raise typer.Exit(1)

push_proc = _get("run_subprocess")(
["git", "push", "--force-with-lease", "-u", "origin", cut_branch],
cwd=root,
capture_output=True,
check=False,
_run_remote_git_or_exit(
root,
f"Failed to push {cut_branch} to origin",
"push",
"--force-with-lease",
"-u",
"origin",
cut_branch,
)
if push_proc.returncode != 0:
err = str(push_proc.stderr).strip() or str(push_proc.stdout).strip()
_get("print_error")(f"Failed to push {cut_branch} to origin: {err}", prefix=False)
raise typer.Exit(1)


def milestone_issues_args(milestone_tag: str) -> list[str]:
Expand Down Expand Up @@ -1970,13 +1992,14 @@ def _commit_release_tag_changes(repo_root: Path, release_title: str) -> None:


def _push_git_tag(repo_root: Path, tag_name: str, target_ver: str) -> None:
"""Push annotated tag to origin and close release milestone."""
push_proc = _get("run_subprocess")(["git", "push", "origin", "--tags"], cwd=repo_root)
if push_proc.returncode != 0:
_get("print_error")(
f"Failed to push tag {tag_name} to origin: {push_proc.stderr}", prefix=False
)
raise typer.Exit(1)
"""Push the annotated release tag, and no other, to origin and close release milestone."""
_run_remote_git_or_exit(
repo_root,
f"Failed to push tag {tag_name} to origin",
"push",
"origin",
f"refs/tags/{tag_name}",
)
_get("print_success")(MESSAGES.release.tag_pushed.format(tag=tag_name), prefix=False)
_close_release_milestone_safe(repo_root, target_ver)

Expand Down
8 changes: 8 additions & 0 deletions src/devops_cli/config/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -707,6 +707,14 @@
"GIT_SSH_COMMAND": "ssh -o BatchMode=yes",
}
"""Environment that makes git fail instead of prompting for credentials or a passphrase."""
CONST_GIT_NO_TERMINAL_PROMPT_ENV: Final[dict[str, str]] = {"GIT_TERMINAL_PROMPT": "0"}
"""Environment that stops git from asking for a username or password on the terminal.

An askpass program the person configured (`GIT_ASKPASS`, `core.askPass` or `SSH_ASKPASS`, such as
VS Code's) still runs. Only when none is set, or it answers nothing, does git fail with "terminal
prompts disabled". It leaves ssh alone, unlike `CONST_GIT_NONINTERACTIVE_ENV`, so a person's own
`core.sshCommand` still applies to the git devops-cli runs against their remote (#1124).
"""
CONST_K8S_TEMPLATE_EXTENSIONS: Final[tuple[str, ...]] = (".yaml", ".yml")
# Where each workload kind keeps its pod spec: Pod; PodTemplate; Deployment, ReplicaSet,
# StatefulSet, DaemonSet, Job and ReplicationController; CronJob.
Expand Down
Loading
Loading