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
5 changes: 5 additions & 0 deletions changelog.d/1409.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
### Fixed

- Removed the synthetic `"devops-cli"` identity fallback in `_get_session_login` (`src/devops_cli/roadmap/run.py`), allowing GitHub login lookup failures to raise typed `GitHubOperationError` exceptions directly and fail closed (#1409).
- Ensured job clone setup and change filtering fail closed when the session login lookup fails, preventing git identity configuration with `"devops-cli"` and avoiding self-triggering loop failures against unauthenticated sessions.
- Switched `GitHubSession.login` to use the session REST transport (`GET /user`) rather than shelling out to the `gh` CLI subprocess edge, tested against `GitHubApiFake`.
37 changes: 37 additions & 0 deletions docs/agent/tasks/task-1409-fail-closed-session-login.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
# Task: Fail-Closed Job Clone and Change Filter on Session Login Failure (#1409)

**Issue**: [#1409](https://github.com/dan-petty/devops-cli/issues/1409)
**Scope**: scope/github
**Feasibility**: Verified against the GitHub session fake (`GitHubApiFake`) and git clone / change filtering flows in `src/devops_cli/roadmap/run.py`. Verified that when `GET /user` fails (e.g. 401 unauthenticated or transport error), `_get_session_login()` raises without fallback to `"devops-cli"`, clone rows fail with the login error without writing `"devops-cli"` to the repository config, and the change filter fails the round when the store has no actor.

## Description

Previously, `_get_session_login()` in `src/devops_cli/roadmap/run.py` caught all exceptions from `get_github_session().login` and returned a fallback identity string `"devops-cli"`. This violated the fail-closed engineering principle:
1. `ensure_checkout` wrote `"devops-cli"` into `user.name` and `user.email` in the job clone's git configuration, allowing release cuts and automation jobs to commit with a fictitious identity.
2. `_current_actor` used `"devops-cli"` as the filter actor when `store.actor` / `store._actor` was absent, which stopped the filter from matching the actual actor and caused the Service to react to its own writes.
3. `session.login` in `src/devops_cli/github/session.py` previously executed `gh api user --jq .login` via `subprocess.run` rather than utilizing the session's native REST transport (`GET /user`) introduced in #983.

Remediation applied:
- Switched `session.login` in `src/devops_cli/github/session.py` to `self.rest("GET", "/user")`, returning `str(user["login"])`.
- Removed the exception catching and fallback to `"devops-cli"` in `_get_session_login()`, allowing errors to propagate directly to callers.
- In `ensure_checkout`, failed login lookups raise `GitHubOperationError` (such as `GitHubUnauthenticatedError`), aborting configuration before any `user.name` is written to the clone.
- In `_fetch_filtered_changes` and `run_due_jobs`, failed login lookups fail closed and abort the round rather than continuing with a fake identity.
- Added comprehensive unit and integration tests in `tests/test_github_session.py` and `tests/test_roadmap_run.py` testing through `GitHubApiFake`.

## Acceptance Criteria

- [x] `_get_session_login` lets a failed login lookup raise, with no fallback.
- [x] Clone rows fail closed when login lookup fails, and `user.name` is never written as `"devops-cli"`.
- [x] `_current_actor` caller (`run_due_jobs` / `_fetch_filtered_changes`) fails the round when the actor is absent and login lookup fails.
- [x] Tested through the GitHub session fake (`github_api` / `GitHubApiFake`) refusing `GET /user`.
- [x] Each test call phase stays under 1 s, and `uv run devops ci` passes.
- [x] Changelog fragment `changelog.d/1409.md` records the change.

## Deliverables

- [x] Updated `src/devops_cli/github/session.py` to route `login` through `self.rest("GET", "/user")`.
- [x] Updated `src/devops_cli/roadmap/run.py` to remove fallback in `_get_session_login()`.
- [x] Updated `tests/test_github_session.py` to verify `session.login` caching and error propagation with `GitHubApiFake`.
- [x] Updated `tests/test_roadmap_run.py` to test fail-closed behavior of clone rows and change filtering.
- [x] Added `docs/agent/tasks/task-1409-fail-closed-session-login.md`.
- [x] Added `changelog.d/1409.md`.
7 changes: 3 additions & 4 deletions src/devops_cli/github/session.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,10 @@
from functools import cached_property
from typing import TYPE_CHECKING, Any

from devops_cli.config.constants import CONST_GH_CLI
from devops_cli.config.defaults import DEFAULT_GH_MAX_PAGINATED_PAGES
from devops_cli.core.process import github_token, reset_github_token
from devops_cli.github.error_classifier import listing_past_page_cap
from devops_cli.github.rate_limiter import resolve_identity_cache_dir, run_gh
from devops_cli.github.rate_limiter import resolve_identity_cache_dir

if TYPE_CHECKING:
from collections.abc import Iterator
Expand Down Expand Up @@ -58,8 +57,8 @@ def cache_dir(self) -> Path:
@cached_property
def login(self) -> str:
"""The account the token belongs to, from `GET /user` the first time it is read."""
proc = run_gh([CONST_GH_CLI, "api", "user", "--jq", ".login"], check=True, quiet=True)
return proc.stdout.strip()
user = self.rest("GET", "/user")
return str(user["login"])

@cached_property
def client(self) -> GitHubClient:
Expand Down
7 changes: 2 additions & 5 deletions src/devops_cli/roadmap/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -234,12 +234,9 @@ def _write_intake_record(path: Path, record: IntakeRecord) -> None:

def _get_session_login() -> str:
"""Account login of the process GitHub identity."""
try:
from devops_cli.github.session import get_github_session
from devops_cli.github.session import get_github_session

return get_github_session().login
except Exception:
return "devops-cli"
return get_github_session().login


def _current_actor(store: RoadmapStore) -> str | None:
Expand Down
2 changes: 1 addition & 1 deletion tests/fixtures/swallowed_failures_ceilings.json
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@
"src/devops_cli/review/fingerprint.py": 1,
"src/devops_cli/roadmap/intake.py": 1,
"src/devops_cli/roadmap/refine.py": 2,
"src/devops_cli/roadmap/run.py": 6,
"src/devops_cli/roadmap/run.py": 5,
"src/devops_cli/sandbox/engine.py": 2,
"src/devops_cli/sandbox/host.py": 2,
"src/devops_cli/sandbox/logs.py": 1,
Expand Down
23 changes: 14 additions & 9 deletions tests/test_github_session.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,21 +86,26 @@ def test_the_session_never_shows_its_token(pin_github_session: str) -> None:
assert pin_github_session not in f"{session!r} {session.cache_dir}"


def test_login_is_read_once_from_get_user() -> None:
def test_login_is_read_once_from_get_user(github_api: GitHubApiFake) -> None:
"""`session.login` asks `GET /user` the first time it is read, then keeps the answer."""
get_github_rate_limiter().update_quota(
"core", remaining=5000, limit=5000, reset_epoch=time.time() + 60.0
)
github_api.route("GET", "/user", github_json({"login": "octocat"}))
session = get_github_session()
with patch("subprocess.run", return_value=_gh_answers("octocat\n")) as run:
logins = (session.login, session.login)
gh_calls = [call.args[0] for call in run.call_args_list if call.args[0][0] == CONST_GH_CLI]
assert (logins, gh_calls) == (
logins = (session.login, session.login)
assert (logins, len(github_api.sent)) == (
("octocat", "octocat"),
[[CONST_GH_CLI, "api", "user", "--jq", ".login"]],
1,
)


def test_login_raises_when_get_user_fails(github_api: GitHubApiFake) -> None:
"""`session.login` raises when `GET /user` fails, with no fallback."""
github_api.route("GET", "/user", github_json({"message": "Bad credentials"}, status=401))
session = get_github_session()
with pytest.raises(GitHubUnauthenticatedError) as raised:
_ = session.login
assert raised.value.error_code == "GITHUB_UNAUTHENTICATED"


def test_without_a_token_the_session_raises_the_unauthenticated_error(
no_github_identity: None,
) -> None:
Expand Down
84 changes: 73 additions & 11 deletions tests/test_roadmap_run.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,11 @@
from devops_cli.config.defaults import DEFAULT_ROADMAP_METRICS_INTERVAL_MINUTES
from devops_cli.config.settings import ServiceConfig
from devops_cli.exceptions import GitOperationError, RoadmapRunError
from devops_cli.exceptions.git import GitHubOperationError, GitHubRateLimitError
from devops_cli.exceptions.git import (
GitHubOperationError,
GitHubRateLimitError,
GitHubUnauthenticatedError,
)
from devops_cli.github.check_verdict import CheckBucket, CheckVerdictSummary, PRCheckItem
from devops_cli.github.rate_limiter import get_github_rate_limiter
from devops_cli.roadmap import store as roadmap_store_module
Expand Down Expand Up @@ -93,15 +97,14 @@
from devops_cli.server.service import ServiceManager, TriggerBatch
from devops_cli.telemetry.instruments import PROJECT_RELEASES_TOTAL
from devops_cli.telemetry.metrics import GLOBAL_METRICS
from tests.github_session_fakes import API, RunnerSession
from tests.github_session_fakes import API, GitHubApiFake, RunnerSession, github_json
from tests.roadmap_board_fake import GitHubFake
from tests.roadmap_faults import Fault, StoppingStore
from tests.web_fakes import StubWeb

REPO = "example/roadmap"
RELEASE = "v0.2.26"
RELEASE_BRANCH = f"release/{RELEASE}"
SESSION_LOGIN_ARGV = [CONST_GH_CLI, "api", "user", "--jq", ".login"]
COMMIT_IDENTITY = ("-c", "user.name=Test", "-c", "user.email=test@example.com")
# GitHub's `release` `published` webhook, a ship's hint (#1360).
SHIP_HINT = CONST_ROADMAP_REPRIORITIZE_BATCH_KEYS[1]
Expand Down Expand Up @@ -205,13 +208,15 @@ def dangling_head_remote(release_remote: Path) -> Path:


@pytest.fixture
def child_argvs(monkeypatch: pytest.MonkeyPatch) -> Iterator[list[list[str]]]:
"""Run git for real and answer the session's login lookup at the process edge.
def child_argvs(
monkeypatch: pytest.MonkeyPatch, github_api: GitHubApiFake
) -> Iterator[list[list[str]]]:
"""Run git for real and answer the session's login lookup through the session fake.

Every child's argv is recorded. `gh api user --jq .login` prints `test-bot`, and any other gh
command fails the test instead of reaching GitHub. The core quota is seeded, so the lookup sends
no `gh api rate_limit` first, and a lookup that failed would show as the `devops-cli` fallback.
Every child's argv is recorded. `GET /user` returns `test-bot`, and any gh command fails
the test instead of reaching GitHub.
"""
github_api.route("GET", "/user", github_json({"login": "test-bot"}))
get_github_rate_limiter().update_quota(
"core", remaining=5000, limit=5000, reset_epoch=time.time() + 60.0
)
Expand All @@ -222,9 +227,7 @@ def run(argv: Sequence[str], *args: Any, **kwargs: Any) -> subprocess.CompletedP
argvs.append(list(argv))
if argv[0] != CONST_GH_CLI:
return real_run(argv, *args, **kwargs)
if list(argv) != SESSION_LOGIN_ARGV:
raise AssertionError(f"A clone test ran {argv}, which would reach GitHub")
return subprocess.CompletedProcess(argv, 0, stdout="test-bot\n", stderr="")
raise AssertionError(f"A clone test ran {argv}, which would reach GitHub")

monkeypatch.setattr(subprocess, "run", run)
yield argvs
Expand Down Expand Up @@ -1004,6 +1007,60 @@ def test_checkout_raises_when_origin_head_names_no_branch(
) == (True, True)


def test_clone_and_change_filter_fail_closed_when_login_lookup_fails(
seeded_store: InMemoryRoadmapStore,
tmp_path: Path,
release_remote: Path,
github_api: GitHubApiFake,
) -> None:
"""When `GET /user` fails, the clone rows and the change filter fail closed without fallback.

`ensure_checkout` fails before configuring `user.name`, so no `devops-cli` identity is
written. The clone row fails in `run_due_jobs`, and a store with no actor fails the round
during change filtering rather than filtering with `devops-cli` (#1409).
"""
github_api.route("GET", "/user", github_json({"message": "Bad credentials"}, status=401))
cur = _current_release(seeded_store)
data_dir = tmp_path / "data"

with pytest.raises(GitHubUnauthenticatedError):
ensure_checkout(REPO, data_dir, remote_url=str(release_remote), current_rel=cur)

clone_dir = data_dir / "roadmap" / REPO / CONST_ROADMAP_RUN_CLONE_DIRNAME
if (clone_dir / ".git").exists():
proc = subprocess.run(
["git", "-C", str(clone_dir), "config", "user.name"],
capture_output=True,
text=True,
check=False,
)
assert proc.stdout.strip() != "devops-cli"

table = build_stub_table({"refine": lambda **_: JobOutcome()}, needs_clone=True)
with pytest.raises(RoadmapRunError) as exc_info:
run_due_jobs(
REPO,
seeded_store,
table=table,
data_dir=data_dir,
remote_url=str(release_remote),
batch={CONST_ROADMAP_INTAKE_BATCH_KEYS[0]: 1},
)
assert "refine" in exc_info.value.failed_jobs

store_without_actor = seeded_store.as_actor("")
store_without_actor._actor = None # type: ignore[assignment]
with pytest.raises(GitHubUnauthenticatedError):
run_due_jobs(
REPO,
store_without_actor,
table=table,
data_dir=data_dir,
remote_url=str(release_remote),
batch={("poll", "", ""): 1},
)


def test_a_round_after_a_ship_runs_its_clone_jobs_on_the_default_branch(
seeded_store: InMemoryRoadmapStore,
tmp_path: Path,
Expand Down Expand Up @@ -1278,6 +1335,11 @@ def test_the_metrics_job_walks_the_release_tags_of_its_own_clone(
monkeypatch.setattr(subprocess, "run", github.process(subprocess.run))
for url in (CONST_URL_GITHUB_STATUS_SUMMARY, CONST_URL_CLOUDFLARE_STATUS_SUMMARY):
stub_web.page(url, json.dumps(STATUS_PAGE))
stub_web.page(
f"{API}/user",
json.dumps({"login": "test-bot"}),
headers={"content-type": "application/json"},
)
GLOBAL_METRICS.clear_metric(PROJECT_RELEASES_TOTAL.name)
data_dir = tmp_path / "data"
with caplog.at_level(logging.WARNING):
Expand Down
Loading
Loading