open-swe/agent/utils/jira.py

269 lines
9.2 KiB
Python
Raw Permalink Normal View History

feat: Jira + Confluence integration (tools + triggers) (#182) * feat(open-swe): add Jira tool plane (Phase 1) Curated Jira Cloud REST v3 toolset for the agent, mirroring the Linear tools: - utils/jira.py: service-account REST client (Basic auth) with get/ create/update issue, comments, list projects, trace comment; issue and comment bodies normalized to markdown. - utils/adf.py: minimal ADF <-> markdown conversion (read paths convert Jira ADF to markdown; agent comments convert prose to ADF). - tools/jira_{comment,get_issue,get_issue_comments,create_issue, update_issue,list_projects}.py wired into the tool registry and the main agent tool list. - tests/test_jira_utils.py: ADF conversion + mocked-transport util tests. Reads JIRA_BASE_URL / JIRA_SERVICE_EMAIL / JIRA_API_TOKEN; unset env returns a clean error, so this is safe to land dark. Trigger plane, prompt guidance, and config plumbing follow in Phase 2. * feat(open-swe): add Confluence tool plane (Phase 3) Curated Confluence Cloud REST toolset for the agent, mirroring the Jira tools: - utils/confluence.py: service-account REST client (Basic auth) with get/create/update page, add comment, CQL search. Page bodies are XHTML storage format (not ADF), with minimal storage<->text converters; update_page reads the current version and bumps it, as Confluence requires. - tools/confluence_{get_page,create_page,update_page,comment,search}.py registered in the tool registry. - tests/test_confluence_utils.py: converter + mocked-transport tests including the version-bump path. Reads CONFLUENCE_BASE_URL / CONFLUENCE_EMAIL / CONFLUENCE_API_TOKEN; unset env returns a clean error. Activation in the agent tool list lands with the Phase 2 server.py wiring. * feat(open-swe): add Jira trigger plane (Phase 2) Make an @openswe comment on a Jira issue spawn an agent run, mirroring the Linear trigger plane: - webhooks/jira.py: process_jira_issue clones process_linear_issue — deterministic thread id, full-issue fetch, actor accountId->email attribution feeding resolve_login_from_email_async (PRs open as the human), multimodal image handling, source="jira" + jira_issue config. - webapp.py: POST/GET /webhooks/jira, verify_jira_secret (constant-time X-Automation-Webhook-Token check, fails closed), repo-resolution cascade, get_repo_config_from_jira_mapping. - utils/jira_project_repo_map.py: JIRA_PROJECT_TO_REPO (placeholder entry — real project->repo mappings still needed). - utils/jira.py: get_user_email (accountId -> email) for attribution. - completion.py: source=="jira" failure-reply branch. - prompt.py: Jira-triggered notify guidance + Refs:/branch key from {jira_project_key}-{jira_issue_number}. - server.py: read jira_issue config + pass jira key to the system prompt; also activates the Phase 3 Confluence tools in the agent list. Jira Automation lacks native webhook HMAC signing, so trust is a shared secret header (decision D2); replay protection is weaker than Linear's HMAC+timestamp. /sh-security-review + an Atlassian IP allowlist are the outstanding gate/hardening before push. * fix(open-swe): harden Jira webhook trust (sh-security-review) Resolves findings from the Phase 2 security review (detector fan-out + proof-or-kill verifier). The unsigned Jira Automation webhook body was trusted for identity, comment content, repo routing, and issue existence; a JIRA_WEBHOOK_SECRET holder could forge those fields. - Corroborate against the real Jira record: the webhook body is now only a pointer (issue_key + required comment_id). The triggering comment's author and text are re-fetched server-side via get_comment/fetch_jira_ comment, and identity, the @openswe check, prompt text, and project key are derived from that authoritative record — never payload author/ body fields. An uncorroborated comment is rejected. (closes the account-id impersonation, unsigned-body prompt injection, and fabricated-issue findings) - Validate issue_key against the Jira key format and percent-encode all untrusted path segments (_seg) so a crafted key can't traverse to a different Jira REST endpoint or inject query params. (closes the path- traversal / query-injection findings) - Route source=="jira" through the bot-token-default / author_prs_as_ user opt-in path in resolve_github_token, matching Linear, instead of unconditionally resolving a per-user OAuth token from a payload email. - Gate attribution on an active user mapping (is_login_mapped) so a pending/unconfirmed mapping can't drive PR authorship. Adds regression tests: server-corroboration wins over payload, malformed issue_key rejected, uncorroborated comment rejected, path-segment encoding, project-key derivation, active-mapping gate. Remaining (non-blocking, deployment/hardening): set ALLOWED_GITHUB_ORGS/ REPOS so the shared allowlist isn't fail-open; consider HMAC-over-body + timestamp on the Automation payload to close the residual replay gap. * harden(open-swe): opt-in Jira webhook replay/IP + fail-closed allowlist Folds the two deployment-hardening items from the Phase 2 security review into code (all opt-in / default-off, so existing and upstream deployments are unaffected): - JIRA_WEBHOOK_REQUIRE_SIGNATURE: when set, the Automation payload must carry X-Openswe-Signature (hex HMAC-SHA256 of the raw body keyed by JIRA_WEBHOOK_SECRET) plus a fresh timestamp, verified by verify_jira_signature / _jira_timestamp_is_fresh (mirrors the Linear HMAC+freshness model). Closes the static-token model's replay/forgery gap when enabled. - JIRA_WEBHOOK_IP_ALLOWLIST: optional CIDR allowlist on the webhook's direct client IP (verify_jira_source_ip). Documented as direct-peer only; behind a proxy/LB, allowlist Atlassian's ranges at that layer. - REQUIRE_REPO_ALLOWLIST: makes an empty ALLOWED_GITHUB_ORGS/REPOS fail CLOSED instead of the back-compat allow-all, plus a startup fail-open warning. Applies to all channels for consistency. Documents all new vars (and a Jira section) in .env.example. Adds tests for signature on/off + valid/missing/wrong/stale, IP allow/deny/off, and the fail-closed allowlist. * feat(open-swe): Confluence Atlassian Connect trigger (Phase 4) Adds the @openswe-on-a-Confluence-comment trigger via a private Atlassian Connect app. Designed and adversarially verified with the ultracode workflow (3 divergent Opus designs + judge; 3 proof-or-kill Opus skeptics on the implemented crypto). - utils/atlassian_connect.py: hand-rolled qsh (pinned to Atlassian's official test vector), PyJWT HS256 webhook verifier with alg-pinning, issuer binding, and qsh-verified-last ordering; RS256 signed-install lifecycle verifier against Atlassian's published keys; installation store keyed by clientKey with the sharedSecret encrypted at rest (TOKEN_ENCRYPTION_KEY / Fernet). No new dependency (PyJWT already pinned). - webhooks/confluence.py: install/uninstall lifecycle + comment handler. The JWT-signed webhook body is only a pointer; the comment's real author/text/container are re-fetched server-side via the Basic-auth service account (Phase-2 corroboration lesson), with active-only login attribution and the repo allowlist. - utils/confluence.py: get_comment / get_user_email (path-encoded). - webapp.py: GET /connect/atlassian-connect.json (served dynamically), POST /connect/{installed,uninstalled,webhook/comment-created}, the space->repo resolver, thread-id, and fetch helpers. - completion.py: source=="confluence" failure-reply branch. Security: the sh-security-review verify pass confirmed one HIGH — the symmetric signed-install=false first-install was trust-on-first-use gated only by the public Confluence hostname (webhook-auth bypass). Fixed by switching to signed-install=true + RS256 verification of lifecycle callbacks, which cryptographically authenticates the first install. All other attack lenses (forgery/replay/alg-confusion/overwrite/uninstall DoS/corroboration/injection) were defeated; residuals are deployment config (REQUIRE_REPO_ALLOWLIST) or accepted-by-design (qsh cannot cover bodies; comment-trigger prompt injection, shared with all sources). New env (documented in .env.example): CONFLUENCE_BASE_URL/EMAIL/API_TOKEN, CONNECT_BASE_URL, CONNECT_EXPECTED_BASE_URL (optional). Install secrets require the durable Postgres LangGraph store in prod. Outstanding before push: /sh-security-review on the real diff and the GPT-4.1 cross-family review (auth boundary); README/CLAUDE.md + memory. * docs(open-swe): Phase 5 — Confluence prompt guidance + architecture docs - prompt.py: Confluence-triggered runs notify via confluence_comment on the triggering page; add Confluence to the shared-base source list. - CLAUDE.md: document the Jira + Confluence tool planes and the Atlassian triggers (Jira Automation shared-secret webhook; Confluence Connect app with HS256 webhook + qsh and RS256 signed-install lifecycle), plus the server-side corroboration + encrypted install store. Phase 5 also verified the trigger surface end-to-end against a running uvicorn app (descriptor served; /connect/* and /webhooks/jira fail closed without valid auth) and recorded the integration in project memory. * fix(open-swe): resolve /sh-security-review findings on the Atlassian surface Formal sh-security-review (detector fan-out + verifier) over the Phase-4 Connect surface (esp. the new RS256 signed-install code, unseen by the earlier adversarial verify) and the Phase-2 opt-in hardening. CRITICAL — cross-tenant install (origin validation, CWE-346): signed- install proves the caller is *an* Atlassian tenant, not *ours*, and the descriptor is served publicly, so any attacker could install the app on their own Confluence site and drive agent runs against our allowlisted repos. The baseUrl body field is attacker-controlled and cannot bind the tenant; only the signature-verified clientKey (JWT iss) can. Added a MANDATORY, fail-closed CONNECT_EXPECTED_CLIENT_KEYS allowlist checked in process_install after signature+iss verification. HIGH — cross-tenant thread-id collision (CWE-330/863): Confluence comment ids are per-instance, so generate_thread_id_from_confluence_comment now salts the hash with the verified clientKey (plumbed from the webhook JWT iss) to prevent thread hijack across tenants. HIGH/MEDIUM — path/query injection (CWE-22/88): get_page and update_page interpolated page_id into the REST path unencoded (update_page on a mutating PUT with no params= backstop). Now _seg()-encoded, matching the rest of the module. MEDIUM — self-trigger loop (CWE-405): process_confluence_comment had no bot-authorship early-out. Added an optional CONFLUENCE_BOT_ACCOUNT_ID guard mirroring the Linear botActor / Jira comment_author_is_bot checks. LOW — corrected the CONNECT_EXPECTED_BASE_URL comment to document it as opt-in defense-in-depth (the clientKey allowlist is the real gate). Verified clean by the detectors: RS256/HS256 alg-pinning, aud/iss/exp, kid-fetch SSRF (host-pinned + quote-encoded), at-rest secret encryption, constant-time comparisons, and the Phase-2 hardening. New regression tests for each fix; full suite green (1602). * harden(open-swe): GPT-4.1 cross-family review follow-ups Cross-family review (GPT-4.1 via orchestrator cross_reviewer) found no critical/high issues and confirmed the auth boundary is fail-closed and correct. Two low-cost defense-in-depth items applied: - Validate the signed-install JWT 'kid' against a strict charset before the public-key fetch, so a malformed kid fails fast with no network call (on top of the existing fixed host + percent-encoding). - Make JWT nbf verification explicit (verify_nbf) on both the RS256 lifecycle and HS256 webhook decodes. Other suggestions triaged as already-handled (aud cross-app replay is blocked by the per-tenant iss->secret lookup; documented static-token/IP/ baseUrl tradeoffs; qsh pinned to Atlassian's vector) or ops/infra (Fernet rotation via MultiFernet; rate limiting at the gateway). * docs(open-swe): document Jira + Confluence in installation & customization guides - INSTALLATION.md §5: add Jira (Automation-rule webhook + shared secret, service account, JIRA_PROJECT_TO_REPO) and Confluence (Atlassian Connect app install, CONNECT_EXPECTED_CLIENT_KEYS bootstrap, durable-store note, CONFLUENCE_SPACE_TO_REPO) trigger setup; §6: add the new env vars + REQUIRE_REPO_ALLOWLIST. - CUSTOMIZATION.md: jira_*/confluence_* in the tools table; repo-extraction note covers all four sources. - AGENTS.md: match CLAUDE.md (triggers, webhooks, tool list, auth). - README.md: invocation section, tools table, and overview line.
2026-07-13 19:45:54 -04:00
"""Jira Cloud REST API utilities.
Mirrors ``agent/utils/linear.py`` but talks to Jira Cloud REST v3 with a single
service-account (Basic auth over ``email:api_token``). Issue/comment bodies are
Atlassian Document Format (ADF), so read paths convert ADF -> markdown and write
paths convert markdown -> ADF via ``agent/utils/adf.py``.
"""
from __future__ import annotations
import base64
import logging
import os
import re
from typing import Any
from urllib.parse import quote
import httpx
from agent.utils.langsmith import get_langsmith_trace_url
from .adf import adf_to_markdown, markdown_to_adf
from .http import DEFAULT_HTTP_TIMEOUT
logger = logging.getLogger(__name__)
# Jira issue keys are `<PROJECT>-<number>` (e.g. PROJ-123). Untrusted webhook
# input is interpolated into REST paths, so keys are validated against this and
# path segments are percent-encoded to prevent traversal / query injection.
_ISSUE_KEY_RE = re.compile(r"^[A-Za-z][A-Za-z0-9]*-\d+$")
def is_valid_issue_key(issue_key: str) -> bool:
"""Whether ``issue_key`` matches the Jira `<PROJECT>-<number>` format."""
return bool(issue_key) and bool(_ISSUE_KEY_RE.match(issue_key))
def _seg(value: str) -> str:
"""Percent-encode a single untrusted URL path segment (no '/' passthrough)."""
return quote(value, safe="")
JIRA_BASE_URL = os.environ.get("JIRA_BASE_URL", "").rstrip("/") # https://seahaven.atlassian.net
JIRA_EMAIL = os.environ.get("JIRA_SERVICE_EMAIL", "")
JIRA_API_TOKEN = os.environ.get("JIRA_API_TOKEN", "")
_ISSUE_FIELDS = (
"summary,description,status,assignee,reporter,priority,labels,"
"project,issuetype,created,updated,comment"
)
def _headers() -> dict[str, str]:
token = base64.b64encode(f"{JIRA_EMAIL}:{JIRA_API_TOKEN}".encode()).decode()
return {
"Authorization": f"Basic {token}",
"Content-Type": "application/json",
"Accept": "application/json",
}
async def _request(
method: str,
path: str,
*,
json: dict[str, Any] | None = None,
params: dict[str, Any] | None = None,
) -> dict[str, Any]:
"""Execute a REST request against the Jira Cloud v3 API."""
if not (JIRA_BASE_URL and JIRA_EMAIL and JIRA_API_TOKEN):
return {"error": "JIRA_BASE_URL / JIRA_SERVICE_EMAIL / JIRA_API_TOKEN are not set"}
async with httpx.AsyncClient(timeout=DEFAULT_HTTP_TIMEOUT) as client:
try:
response = await client.request(
method,
f"{JIRA_BASE_URL}/rest/api/3{path}",
headers=_headers(),
json=json,
params=params,
)
response.raise_for_status()
return response.json() if response.content else {}
except Exception as e: # noqa: BLE001
return {"error": str(e)}
def _issue_url(issue_key: str) -> str:
return f"{JIRA_BASE_URL}/browse/{_seg(issue_key)}" if JIRA_BASE_URL else ""
def _normalize_issue(raw: dict[str, Any]) -> dict[str, Any]:
"""Flatten a raw Jira issue into an agent-friendly dict with markdown bodies."""
fields = raw.get("fields", {}) or {}
project = fields.get("project") or {}
status = fields.get("status") or {}
assignee = fields.get("assignee") or {}
priority = fields.get("priority") or {}
issue_type = fields.get("issuetype") or {}
return {
"key": raw.get("key", ""),
"id": raw.get("id", ""),
"title": fields.get("summary", ""),
"description": adf_to_markdown(fields.get("description")),
"status": status.get("name", ""),
"assignee": {
"name": assignee.get("displayName"),
"email": assignee.get("emailAddress"),
"account_id": assignee.get("accountId"),
}
if assignee
else None,
"priority": priority.get("name", ""),
"labels": fields.get("labels", []),
"project_key": project.get("key", ""),
"project_name": project.get("name", ""),
"issue_type": issue_type.get("name", ""),
"created": fields.get("created", ""),
"updated": fields.get("updated", ""),
"url": _issue_url(raw.get("key", "")),
}
def _normalize_comment(raw: dict[str, Any]) -> dict[str, Any]:
author = raw.get("author") or {}
return {
"id": raw.get("id", ""),
"body": adf_to_markdown(raw.get("body")),
"created": raw.get("created", ""),
"updated": raw.get("updated", ""),
"author": {
"name": author.get("displayName"),
"email": author.get("emailAddress"),
"account_id": author.get("accountId"),
},
}
async def comment_on_issue(issue_key: str, comment_body: str) -> bool:
"""Add a comment (markdown) to a Jira issue. Returns True on success."""
result = await _request(
"POST",
f"/issue/{_seg(issue_key)}/comment",
json={"body": markdown_to_adf(comment_body)},
)
return bool(result.get("id")) and "error" not in result
async def post_jira_trace_comment(issue_key: str, thread_id: str) -> None:
"""Post a trace URL comment on a Jira issue."""
trace_url = get_langsmith_trace_url(thread_id)
body = f"On it! [View trace]({trace_url})" if trace_url else "On it!"
await comment_on_issue(issue_key, body)
async def get_user_email(account_id: str) -> str | None:
"""Look up a Jira user's email by accountId (webhooks only carry accountId)."""
result = await _request("GET", "/user", params={"accountId": account_id})
if "error" in result:
return None
return result.get("emailAddress")
async def get_issue(issue_key: str) -> dict[str, Any]:
"""Get a Jira issue by its key (e.g. PROJ-123)."""
result = await _request("GET", f"/issue/{_seg(issue_key)}", params={"fields": _ISSUE_FIELDS})
if "error" in result:
return result
return {"issue": _normalize_issue(result)}
async def get_issue_comments(issue_key: str) -> dict[str, Any]:
"""Get comments for a Jira issue (newest ordering as returned by Jira)."""
result = await _request("GET", f"/issue/{_seg(issue_key)}/comment")
if "error" in result:
return result
comments = result.get("comments", [])
return {"comments": [_normalize_comment(c) for c in comments]}
async def get_comment(issue_key: str, comment_id: str) -> dict[str, Any]:
"""Fetch a single comment by id — the authoritative record for a webhook.
Webhook payloads are unsigned, so the triggering comment's real author and
body must be read from Jira server-side (matched by comment_id) rather than
trusted from the payload.
"""
result = await _request("GET", f"/issue/{_seg(issue_key)}/comment/{_seg(comment_id)}")
if "error" in result:
return result
return {"comment": _normalize_comment(result)}
async def create_issue(
project_key: str,
summary: str,
description: str | None = None,
issue_type: str = "Task",
assignee_account_id: str | None = None,
priority: str | None = None,
labels: list[str] | None = None,
) -> dict[str, Any]:
"""Create a new Jira issue."""
fields: dict[str, Any] = {
"project": {"key": project_key},
"summary": summary,
"issuetype": {"name": issue_type},
}
if description is not None:
fields["description"] = markdown_to_adf(description)
if assignee_account_id is not None:
fields["assignee"] = {"accountId": assignee_account_id}
if priority is not None:
fields["priority"] = {"name": priority}
if labels is not None:
fields["labels"] = labels
result = await _request("POST", "/issue", json={"fields": fields})
if "error" in result:
return result
key = result.get("key", "")
return {
"success": bool(key),
"issue": {"key": key, "id": result.get("id", ""), "url": _issue_url(key)},
}
async def update_issue(
issue_key: str,
summary: str | None = None,
description: str | None = None,
assignee_account_id: str | None = None,
priority: str | None = None,
labels: list[str] | None = None,
) -> dict[str, Any]:
"""Update an existing Jira issue."""
fields: dict[str, Any] = {}
if summary is not None:
fields["summary"] = summary
if description is not None:
fields["description"] = markdown_to_adf(description)
if assignee_account_id is not None:
fields["assignee"] = {"accountId": assignee_account_id}
if priority is not None:
fields["priority"] = {"name": priority}
if labels is not None:
fields["labels"] = labels
if not fields:
return {"error": "No fields to update"}
# A 204 (empty body) is success; _request returns {} in that case.
result = await _request("PUT", f"/issue/{_seg(issue_key)}", json={"fields": fields})
if "error" in result:
return result
return {"success": True, "issue": {"key": issue_key, "url": _issue_url(issue_key)}}
async def list_projects() -> dict[str, Any]:
"""List projects visible to the service account."""
result = await _request("GET", "/project/search")
if "error" in result:
return result
projects = [
{"key": p.get("key", ""), "name": p.get("name", ""), "id": p.get("id", "")}
for p in result.get("values", [])
]
return {"projects": projects}