open-swe/tests/tools/test_jira_utils.py

275 lines
9.2 KiB
Python
Raw 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
"""Unit tests for the Jira REST utilities and ADF conversion."""
from __future__ import annotations
from typing import Any
import pytest
from agent.utils import adf, jira
# --- ADF conversion --------------------------------------------------------
def test_adf_to_markdown_handles_none_and_empty() -> None:
assert adf.adf_to_markdown(None) == ""
assert adf.adf_to_markdown({}) == ""
assert adf.adf_to_markdown("not a dict") == ""
def test_adf_to_markdown_paragraphs_marks_and_links() -> None:
doc = {
"type": "doc",
"version": 1,
"content": [
{
"type": "paragraph",
"content": [
{"type": "text", "text": "Hello "},
{"type": "text", "text": "world", "marks": [{"type": "strong"}]},
],
},
{
"type": "paragraph",
"content": [
{
"type": "text",
"text": "a link",
"marks": [{"type": "link", "attrs": {"href": "https://x.com"}}],
}
],
},
],
}
md = adf.adf_to_markdown(doc)
assert "Hello **world**" in md
assert "[a link](https://x.com)" in md
def test_adf_to_markdown_bullet_and_code() -> None:
doc = {
"type": "doc",
"content": [
{
"type": "bulletList",
"content": [
{
"type": "listItem",
"content": [
{"type": "paragraph", "content": [{"type": "text", "text": "one"}]}
],
},
{
"type": "listItem",
"content": [
{"type": "paragraph", "content": [{"type": "text", "text": "two"}]}
],
},
],
},
{
"type": "codeBlock",
"attrs": {"language": "python"},
"content": [{"type": "text", "text": "print(1)"}],
},
],
}
md = adf.adf_to_markdown(doc)
assert "- one" in md
assert "- two" in md
assert "```python" in md
assert "print(1)" in md
def test_markdown_to_adf_structure() -> None:
doc = adf.markdown_to_adf("first block\n\nsecond block")
assert doc["type"] == "doc"
assert doc["version"] == 1
assert len(doc["content"]) == 2
assert doc["content"][0]["content"][0]["text"] == "first block"
def test_markdown_to_adf_empty_is_valid_doc() -> None:
doc = adf.markdown_to_adf("")
assert doc["type"] == "doc"
assert doc["content"] == [{"type": "paragraph", "content": []}]
def test_markdown_to_adf_multiline_block_uses_hardbreaks() -> None:
doc = adf.markdown_to_adf("line one\nline two")
para = doc["content"][0]["content"]
assert {"type": "hardBreak"} in para
# --- Jira REST utilities (mocked transport) --------------------------------
@pytest.fixture
def _jira_env(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(jira, "JIRA_BASE_URL", "https://seahaven.atlassian.net")
monkeypatch.setattr(jira, "JIRA_EMAIL", "bot@seahavenind.com")
monkeypatch.setattr(jira, "JIRA_API_TOKEN", "token")
def _mock_request(
monkeypatch: pytest.MonkeyPatch, response: dict[str, Any]
) -> list[dict[str, Any]]:
calls: list[dict[str, Any]] = []
async def fake_request(method: str, path: str, *, json=None, params=None):
calls.append({"method": method, "path": path, "json": json, "params": params})
return response
monkeypatch.setattr(jira, "_request", fake_request)
return calls
async def test_get_issue_normalizes_fields(
_jira_env: None, monkeypatch: pytest.MonkeyPatch
) -> None:
raw = {
"key": "PROJ-123",
"id": "10001",
"fields": {
"summary": "Fix the bug",
"description": {
"type": "doc",
"content": [
{"type": "paragraph", "content": [{"type": "text", "text": "details"}]}
],
},
"status": {"name": "In Progress"},
"assignee": {"displayName": "Ada", "emailAddress": "ada@x.com", "accountId": "acc1"},
"priority": {"name": "High"},
"labels": ["backend"],
"project": {"key": "PROJ", "name": "Project"},
"issuetype": {"name": "Bug"},
},
}
_mock_request(monkeypatch, raw)
result = await jira.get_issue("PROJ-123")
issue = result["issue"]
assert issue["key"] == "PROJ-123"
assert issue["title"] == "Fix the bug"
assert issue["description"] == "details"
assert issue["assignee"]["email"] == "ada@x.com"
assert issue["project_key"] == "PROJ"
assert issue["url"] == "https://seahaven.atlassian.net/browse/PROJ-123"
async def test_comment_on_issue_success(_jira_env: None, monkeypatch: pytest.MonkeyPatch) -> None:
calls = _mock_request(monkeypatch, {"id": "5001"})
ok = await jira.comment_on_issue("PROJ-1", "done, see PR")
assert ok is True
assert calls[0]["method"] == "POST"
assert calls[0]["path"] == "/issue/PROJ-1/comment"
# Body must be ADF, not raw markdown.
assert calls[0]["json"]["body"]["type"] == "doc"
async def test_comment_on_issue_error_returns_false(
_jira_env: None, monkeypatch: pytest.MonkeyPatch
) -> None:
_mock_request(monkeypatch, {"error": "boom"})
assert await jira.comment_on_issue("PROJ-1", "x") is False
async def test_get_issue_comments_normalizes(
_jira_env: None, monkeypatch: pytest.MonkeyPatch
) -> None:
_mock_request(
monkeypatch,
{
"comments": [
{
"id": "1",
"author": {"displayName": "Ada", "emailAddress": "ada@x.com", "accountId": "a"},
"body": {
"type": "doc",
"content": [
{"type": "paragraph", "content": [{"type": "text", "text": "hi"}]}
],
},
}
]
},
)
result = await jira.get_issue_comments("PROJ-1")
assert result["comments"][0]["body"] == "hi"
assert result["comments"][0]["author"]["email"] == "ada@x.com"
async def test_create_issue_builds_fields(_jira_env: None, monkeypatch: pytest.MonkeyPatch) -> None:
calls = _mock_request(monkeypatch, {"key": "PROJ-9", "id": "999"})
result = await jira.create_issue("PROJ", "New thing", description="body", priority="High")
assert result["success"] is True
assert result["issue"]["key"] == "PROJ-9"
sent = calls[0]["json"]["fields"]
assert sent["project"] == {"key": "PROJ"}
assert sent["summary"] == "New thing"
assert sent["description"]["type"] == "doc"
assert sent["priority"] == {"name": "High"}
async def test_update_issue_no_fields_errors(_jira_env: None) -> None:
result = await jira.update_issue("PROJ-1")
assert result["error"] == "No fields to update"
async def test_request_without_env_returns_error(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(jira, "JIRA_BASE_URL", "")
monkeypatch.setattr(jira, "JIRA_API_TOKEN", "")
result = await jira._request("GET", "/issue/PROJ-1")
assert "error" in result
# --- issue_key validation + path-segment encoding (INJ hardening) ----------
def test_is_valid_issue_key() -> None:
assert jira.is_valid_issue_key("PROJ-123")
assert jira.is_valid_issue_key("OS-1")
assert not jira.is_valid_issue_key("")
assert not jira.is_valid_issue_key("../../../../rest/api/2/permissions")
assert not jira.is_valid_issue_key("PROJ-1?expand=x")
assert not jira.is_valid_issue_key("PROJ-1/comment")
assert not jira.is_valid_issue_key("1-PROJ")
async def test_get_issue_percent_encodes_path(
_jira_env: None, monkeypatch: pytest.MonkeyPatch
) -> None:
# Even if a traversal key reaches the util, the path segment is encoded so it
# cannot climb out of /issue/ or inject a query.
calls = _mock_request(monkeypatch, {"key": "x", "fields": {}})
await jira.get_issue("../../../../rest/api/2/permissions")
assert calls[0]["path"] == "/issue/..%2F..%2F..%2F..%2Frest%2Fapi%2F2%2Fpermissions"
async def test_comment_on_issue_encodes_path(
_jira_env: None, monkeypatch: pytest.MonkeyPatch
) -> None:
calls = _mock_request(monkeypatch, {"id": "1"})
await jira.comment_on_issue("ABC-1?expand=evil", "hi")
assert calls[0]["path"] == "/issue/ABC-1%3Fexpand%3Devil/comment"
async def test_get_comment_fetches_single_comment(
_jira_env: None, monkeypatch: pytest.MonkeyPatch
) -> None:
calls = _mock_request(
monkeypatch,
{
"id": "10050",
"author": {"displayName": "Ada", "emailAddress": "ada@x.com", "accountId": "acc"},
"body": {
"type": "doc",
"content": [{"type": "paragraph", "content": [{"type": "text", "text": "hi"}]}],
},
},
)
result = await jira.get_comment("PROJ-1", "10050")
assert calls[0]["path"] == "/issue/PROJ-1/comment/10050"
assert result["comment"]["author"]["account_id"] == "acc"
assert result["comment"]["body"] == "hi"