mirror of
https://github.com/Sea-Haven-Industries/open-swe.git
synced 2026-09-30 10:23:14 +00:00
Some checks are pending
CI / Lint (push) Waiting to run
CI / Format check (push) Waiting to run
CI / Unit tests (push) Waiting to run
CI / Playwright E2E (push) Waiting to run
CI / Docker build smoke (push) Waiting to run
CI / Triage ledger up to date (push) Waiting to run
CI / ui bun.lock in sync (push) Waiting to run
* feat: port plan-review & workflow-approval UX (#135)
Port six upstream commits onto dev:
- c03a6be7 (already ported): keep plan guidance high-level
- 546042a4: add workflow approval UI with diff preview, approval URLs,
web review links, and polling for approval status during active runs
- 216cf181: remove workflow token elevation; approved pushes pass
through directly without proxy token rewriting
- 3dbc0282: preserve plan redirects after login by accepting relative
same-origin redirect_to values and rejecting blocked paths
- bb104d93: submit plan comments with cmd+enter
- 90cb6caa: terse Slack replies, shared content via save_plan outside
plan mode (PLAN_STATUS_SHARED), reject shared-content mutations
Refs: #135
* fix: restore login page render and clear CI lint/format
The plan-review port removed the authRedirectUrl import from login.tsx
but left its call site, crashing the login page at runtime (blank page,
no 'Sign in to open-swe'). Pass the relative path straight to loginUrl,
matching the plan route and the backend relative-redirect handling.
Also drop an unused os import in the guard test and reformat
workflow_push_guard.py to satisfy ruff.
* fix: carry workflows:write on the standing proxy token
Complete the half-ported upstream 216cf181 cascade. The port dropped
_run_with_workflow_token from the guard but missed the paired github_app
change, so an approved .github/workflows push ran with the base token
(no workflows:write) and GitHub 403'd it.
Add workflows:write to BASE_RUNTIME_PROXY_TOKEN_PERMISSIONS and delete the
now-orphaned WORKFLOW_RUNTIME_PROXY_TOKEN_PERMISSIONS constant; update the
github_app and proxy_auth tests to match. The HITL approval gate in
workflow_push_guard.py is unchanged — this only lets the standing token
push once a human approves.
* fix: restore transient workflow-token elevation (revert standing workflows:write)
The standing GitHub-App proxy token (BASE_RUNTIME_PROXY_TOKEN_PERMISSIONS) is
ALWAYS-ON, so carrying workflows:write on it made the fork's HITL workflow-push
guard the sole control over unapproved workflow pushes. The guard's git-push
parser has gaps (obfuscated-expansion push, `gh api` REST contents PUT,
fully-qualified cross-branch refspecs); with a permanently workflows-scoped
token those gaps become live unapproved-workflow-push exploits (1 critical, 2
high — security review BLOCK on #159).
Restore dev's transient-elevation model:
- Drop workflows:write from BASE_RUNTIME_PROXY_TOKEN_PERMISSIONS; re-add the
WORKFLOW_RUNTIME_PROXY_TOKEN_PERMISSIONS constant (base + workflows:write).
- Re-introduce _run_with_workflow_token in the guard: it mints the
workflows-scoped token via refresh_proxy_token around the approved,
guard-normalized fixed_command, then downscopes to RUNTIME then BASE in a
finally. Route the approval branch through it.
- Restore the dev token/elevation tests.
The standing token no longer carries workflows:write, so the three parser
bypasses hit GitHub 403 again; an approved push still succeeds because the
elevation grants workflows:write only around the normalized command. Keeps all
of #159's diff-preview / approval-URL / Slack-card guard additions.
* fix: reject protocol-relative path from sanitizeAuthRedirect (open redirect)
sanitizeAuthRedirect returned parsed.pathname+search+hash, which `new URL` can
resolve to a protocol-relative `//host` (e.g. input `/..//evil.com` normalizes
same-origin, passing the origin check, but yields a path starting with `//`).
ClientRedirect / login.tsx feed that path to window.location.replace, so it
navigates cross-origin — an open redirect. Reject any resolved path that is not
a single-leading-slash path (`^/[^/]`), falling back to the default. Adds
coverage for `/..//evil.com`, `/.//evil.com`, and `//evil.com`.
* fix: log SECURITY error when workflow-token downscope fails
The elevate->push->downscope finally block was silent on failure. If both
refresh_proxy_token calls fail, the sandbox retains workflows:write for the
rest of the run with no signal. Log a SECURITY error on the partial and full
downscope-failure paths so the retention is observable.
Addresses the GPT-4.1 cross-family review of the token-scope remediation.
---------
Co-authored-by: amoussa1229 <166072409+amoussa1229@users.noreply.github.com>
Co-authored-by: Adam Moussa <adam@seahavenind.com>
212 lines
7.6 KiB
Python
212 lines
7.6 KiB
Python
"""Workflow-file push approval state."""
|
|
|
|
from __future__ import annotations
|
|
|
|
from collections.abc import Mapping
|
|
from datetime import UTC, datetime
|
|
from typing import Any
|
|
|
|
from langgraph_sdk import get_client
|
|
|
|
WORKFLOW_PUSH_APPROVALS_KEY = "workflow_push_approvals"
|
|
WORKFLOW_APPROVAL_PENDING = "pending"
|
|
WORKFLOW_APPROVAL_APPROVED = "approved"
|
|
WORKFLOW_APPROVAL_REJECTED = "rejected"
|
|
_MAX_APPROVAL_RECORDS = 20
|
|
_TERMINAL_STATUSES = {WORKFLOW_APPROVAL_APPROVED, WORKFLOW_APPROVAL_REJECTED}
|
|
|
|
|
|
def _now() -> str:
|
|
return datetime.now(UTC).isoformat()
|
|
|
|
|
|
def _approvals_from_metadata(metadata: Mapping[str, Any] | None) -> dict[str, dict[str, Any]]:
|
|
raw = metadata.get(WORKFLOW_PUSH_APPROVALS_KEY) if metadata else None
|
|
if not isinstance(raw, dict):
|
|
return {}
|
|
approvals: dict[str, dict[str, Any]] = {}
|
|
for fingerprint, value in raw.items():
|
|
if isinstance(fingerprint, str) and fingerprint and isinstance(value, dict):
|
|
record = dict(value)
|
|
record.setdefault("fingerprint", fingerprint)
|
|
approvals[fingerprint] = record
|
|
return approvals
|
|
|
|
|
|
async def get_workflow_push_approvals(thread_id: str) -> dict[str, dict[str, Any]]:
|
|
client = get_client()
|
|
thread = await client.threads.get(thread_id)
|
|
metadata = thread.get("metadata") if isinstance(thread, dict) else None
|
|
return _approvals_from_metadata(metadata if isinstance(metadata, dict) else None)
|
|
|
|
|
|
async def workflow_push_approved(thread_id: str, fingerprint: str) -> bool:
|
|
approvals = await get_workflow_push_approvals(thread_id)
|
|
return approvals.get(fingerprint, {}).get("status") == WORKFLOW_APPROVAL_APPROVED
|
|
|
|
|
|
async def workflow_push_rejected(thread_id: str, fingerprint: str) -> bool:
|
|
approvals = await get_workflow_push_approvals(thread_id)
|
|
return approvals.get(fingerprint, {}).get("status") == WORKFLOW_APPROVAL_REJECTED
|
|
|
|
|
|
async def find_workflow_push_approval(
|
|
thread_id: str,
|
|
*,
|
|
repo: str,
|
|
branch: str,
|
|
files: list[str],
|
|
) -> dict[str, Any] | None:
|
|
"""Return the most recent approved record matching identity-level keys, if any."""
|
|
approvals = await get_workflow_push_approvals(thread_id)
|
|
identity = (repo, branch, tuple(sorted(files)))
|
|
matches = [
|
|
r
|
|
for r in approvals.values()
|
|
if r.get("status") == WORKFLOW_APPROVAL_APPROVED
|
|
and (r.get("repo"), r.get("branch"), tuple(sorted(r.get("files", [])))) == identity
|
|
]
|
|
if not matches:
|
|
return None
|
|
matches.sort(key=lambda r: str(r.get("decided_at", "")), reverse=True)
|
|
return matches[0]
|
|
|
|
|
|
async def ensure_workflow_push_pending(
|
|
thread_id: str,
|
|
*,
|
|
fingerprint: str,
|
|
repo: str,
|
|
branch: str,
|
|
base_sha: str,
|
|
head_sha: str,
|
|
files: list[str],
|
|
diff_stats: Mapping[str, Any] | None = None,
|
|
diff_preview: str | None = None,
|
|
diff_preview_truncated: bool = False,
|
|
approval_url: str | None = None,
|
|
) -> tuple[dict[str, Any], bool]:
|
|
"""Store a pending approval unless a terminal record already exists."""
|
|
approvals = await get_workflow_push_approvals(thread_id)
|
|
existing = approvals.get(fingerprint)
|
|
if existing and existing.get("status") in _TERMINAL_STATUSES:
|
|
return existing, False
|
|
|
|
review_fields = {
|
|
"repo": repo,
|
|
"branch": branch,
|
|
"base_sha": base_sha,
|
|
"head_sha": head_sha,
|
|
"files": list(files),
|
|
"diff_stats": _normalize_diff_stats(diff_stats, len(files)),
|
|
"diff_preview": diff_preview or "",
|
|
"diff_preview_truncated": diff_preview_truncated,
|
|
"approval_url": approval_url,
|
|
}
|
|
if existing and existing.get("status") == WORKFLOW_APPROVAL_PENDING:
|
|
record = {**existing, **review_fields}
|
|
approvals[fingerprint] = record
|
|
await _save_approvals(thread_id, approvals)
|
|
return record, False
|
|
|
|
record = {
|
|
"fingerprint": fingerprint,
|
|
"status": WORKFLOW_APPROVAL_PENDING,
|
|
**review_fields,
|
|
"requested_at": _now(),
|
|
"notified": False,
|
|
}
|
|
approvals[fingerprint] = record
|
|
await _save_approvals(thread_id, approvals)
|
|
return record, True
|
|
|
|
|
|
def _safe_int(value: Any, default: int = 0) -> int:
|
|
try:
|
|
return max(0, int(value))
|
|
except (TypeError, ValueError):
|
|
return default
|
|
|
|
|
|
def _normalize_diff_stats(value: Mapping[str, Any] | None, file_count: int) -> dict[str, int]:
|
|
if not isinstance(value, Mapping):
|
|
return {"files": file_count, "additions": 0, "deletions": 0}
|
|
return {
|
|
"files": _safe_int(value.get("files"), file_count),
|
|
"additions": _safe_int(value.get("additions")),
|
|
"deletions": _safe_int(value.get("deletions")),
|
|
}
|
|
|
|
|
|
def workflow_push_approval_response(record: Mapping[str, Any]) -> dict[str, Any]:
|
|
files = record.get("files")
|
|
diff_stats = record.get("diff_stats")
|
|
requested_at = record.get("requested_at")
|
|
decided_at = record.get("decided_at")
|
|
decided_by = record.get("decided_by")
|
|
approval_url = record.get("approval_url")
|
|
return {
|
|
"fingerprint": str(record.get("fingerprint") or ""),
|
|
"status": str(record.get("status") or WORKFLOW_APPROVAL_PENDING),
|
|
"repo": str(record.get("repo") or ""),
|
|
"branch": str(record.get("branch") or ""),
|
|
"baseSha": str(record.get("base_sha") or ""),
|
|
"headSha": str(record.get("head_sha") or ""),
|
|
"files": [str(path) for path in files] if isinstance(files, list) else [],
|
|
"diffStats": _normalize_diff_stats(
|
|
diff_stats if isinstance(diff_stats, Mapping) else None,
|
|
len(files) if isinstance(files, list) else 0,
|
|
),
|
|
"diffPreview": str(record.get("diff_preview") or ""),
|
|
"diffPreviewTruncated": record.get("diff_preview_truncated") is True,
|
|
"approvalUrl": approval_url if isinstance(approval_url, str) and approval_url else None,
|
|
"requestedAt": requested_at if isinstance(requested_at, str) else None,
|
|
"decidedAt": decided_at if isinstance(decided_at, str) else None,
|
|
"decidedBy": decided_by if isinstance(decided_by, str) else None,
|
|
}
|
|
|
|
|
|
def workflow_push_approval_responses(
|
|
approvals: Mapping[str, Mapping[str, Any]],
|
|
) -> list[dict[str, Any]]:
|
|
ordered = sorted(approvals.values(), key=lambda r: str(r.get("requested_at", "")), reverse=True)
|
|
return [workflow_push_approval_response(record) for record in ordered]
|
|
|
|
|
|
async def mark_workflow_push_notified(thread_id: str, fingerprint: str) -> None:
|
|
approvals = await get_workflow_push_approvals(thread_id)
|
|
record = approvals.get(fingerprint)
|
|
if not record:
|
|
return
|
|
record["notified"] = True
|
|
record["notified_at"] = _now()
|
|
approvals[fingerprint] = record
|
|
await _save_approvals(thread_id, approvals)
|
|
|
|
|
|
async def decide_workflow_push_approval(
|
|
thread_id: str,
|
|
fingerprint: str,
|
|
*,
|
|
approved: bool,
|
|
actor: str,
|
|
) -> dict[str, Any] | None:
|
|
approvals = await get_workflow_push_approvals(thread_id)
|
|
record = approvals.get(fingerprint)
|
|
if not record:
|
|
return None
|
|
record["status"] = WORKFLOW_APPROVAL_APPROVED if approved else WORKFLOW_APPROVAL_REJECTED
|
|
record["decided_at"] = _now()
|
|
record["decided_by"] = actor
|
|
approvals[fingerprint] = record
|
|
await _save_approvals(thread_id, approvals)
|
|
return record
|
|
|
|
|
|
async def _save_approvals(thread_id: str, approvals: dict[str, dict[str, Any]]) -> None:
|
|
ordered = sorted(approvals.values(), key=lambda r: str(r.get("requested_at", "")))
|
|
trimmed = ordered[-_MAX_APPROVAL_RECORDS:]
|
|
await get_client().threads.update(
|
|
thread_id=thread_id,
|
|
metadata={WORKFLOW_PUSH_APPROVALS_KEY: {str(r["fingerprint"]): r for r in trimmed}},
|
|
)
|