Files
cowork-local/core/jira_tool.py
T
a03a740ea1
CI / test (push) Canceled after 0s
Feature/perf ui logic (#13)
## Summary

Nhánh `feature/perf-ui-logic`: tối ưu hiệu năng/UI, sửa lỗi workspace và điều hướng, và làm cho công tắc **"Block network for agent-run commands"** chặn thật mọi đường ra mạng của app, **trừ nhà cung cấp AI**.

**Chặn mạng (b78d483, 8c497cf, 10b8379)**
- Bộ kiểm tra chung `application/network/network_guard.py`, nối vào cấu hình đang chạy ở Composition Root: đổi công tắc trong Settings là có hiệu lực ngay.
- Lệnh shell của agent và task script chạy trong **Windows AppContainer không có quyền mạng**: kernel chặn socket, ping, DNS, Invoke-WebRequest… Không cần quyền admin. Không cô lập được thì lệnh bị từ chối, không chạy khi mạng còn mở. macOS dùng `sandbox-exec`, Linux dùng `unshare --net`.
- Bật chặn thì: dừng MCP đang chạy, không khởi động server mới, từ chối lời gọi connector; Microsoft 365 (đăng nhập, Graph, đồng bộ cloud, rules, mail), Teams, nút Test REST/Jira/MCP, link đính kèm task, pip tự cài và tài nguyên web trong xem trước HTML đều bị từ chối.
- Vẫn dùng được: chat, tải danh sách model, thử model; tool OneDrive đã đồng bộ trên máy.
- Công tắc **mặc định tắt** khi mở app lần đầu; nhãn giữ nguyên như cũ.
- Xem trước HTML trong tab Folder giờ hiện được ảnh/CSS/JS từ web khi mạng mở (trước đây trang `file://` không tải được).
- Sửa lỗi app văng khi chuyển tab Graph → Folder: profile WebEngine của trang xem trước bị huỷ trước trang (`0xc0000409` trong Qt6Core.dll); giờ dùng một profile chung thuộc QApplication.
- Không cấp quyền AppContainer kế thừa lên thư mục chứa PySide6 (nếu có, Chromium không nạp được `Qt6WebEngineCore.dll` và tab Graph trắng).
- Cột mục lục trong Settings tính độ rộng theo kiểu chữ của mục đang chọn, "Sandbox Security Layer" không còn bị cắt.

**Các commit khác trong nhánh**
- `b7a41b3` mỗi thư mục làm việc chỉ thuộc về một project · `bbdf146` bật nút Sửa project khi đã có project đang mở
- `35f24e0`, `cc8d5c8`, `2e3e719`, `c699beb` canh hàng / khoảng cách thanh điều hướng
- `2759ed9` không refresh workspace khi chuyển tab Cowork · `7607f44` checkpoint hiệu năng và UI
- `8548c1e` chặn tool mạng của agent · `caf3b74` renderer GraphRAG native trên macOS · `c00b83c` khoảng cách metadata hàng project · `a04f8a9` ẩn picker workspace cloud

## Change Type

- [x] Cowork feature
- [x] Bug fix
- [ ] Core AI contribution
- [x] Test / hardening
- [x] Performance
- [ ] Documentation

## Related Work

Cowork Task:

Core Repo: http://34.143.229.138/gitea-admin/fsg-ai-core-assets

Core AI Issue:

Core Task:

Related PR:

## Scope

What is intentionally included?
- Mọi đường ra mạng do app tự mở, trừ nhà cung cấp AI (xem Summary).
- Test: `tests/test_network_guard_lanes.py` (có bài chạy AppContainer thật trên Windows), `tests/ui/test_html_preview_remote_images.py`.

What is intentionally NOT included?
- Chặn cả nhà cung cấp AI / chạy model trên máy (Phương án 2).
- Terminal người dùng tự gõ trong tab Folder, sinh ảnh, cơ chế tự tin chứng chỉ lạ (`tls_trust`).
- Huy hiệu trạng thái "đang chặn" trên thanh trên cùng.

## Validation

- [x] Unit tests
- [x] Integration tests
- [x] Manual verification
- [x] Regression check

Commands / evidence:
- `python -m pytest tests/test_network_guard_lanes.py tests/test_sandbox_block_network.py tests/ui -q` → chỉ còn 1 bài fail, fail cả trên `b7a41b3` (nhãn `ProjectRow` 'Project' chưa dịch, `tests/ui/test_i18n_khong_con_chu_cu.py`).
- `python -m pytest tests -q --ignore=tests/ui` → 4 bài fail, cả 4 cũng fail trên `b7a41b3` (`test_canonical_audit_logger`, 2 bài `test_mcp_audit_security`, `test_monitoring_tab_container`).
- Chạy cả `tests` trong một lượt thì treo ở các test dựng MainWindow trong `tests/ui`; `b7a41b3` cũng treo đúng chỗ đó.
- `check_imports.py` và `check_orphan_modules.py` PASS. `check_loc.py` báo 9 file quá dài, giống hệt trước khi sửa (không file nào do nhánh này làm dài thêm).
- Kiểm tra tay trên Windows 11: trong AppContainer, Python báo `WinError 10013`, ping/nslookup/PowerShell/curl đều không ra được mạng; cmd, git, python chạy bình thường.
- Kiểm tra tay trên Windows 11: xem trước HTML tải được 4/4 tài nguyên web khi mạng mở, 0/4 khi bật chặn; tab Graph hoạt động; tạo/huỷ trang xem trước nhiều lần không còn cảnh báo profile của Qt.

## Security Impact

Permission / credential / network / customer data impact:
- Network: khi bật công tắc, chỉ nhà cung cấp AI còn ra mạng; nội dung chat vẫn gửi tới nhà cung cấp AI.
- Permission: lần đầu chạy lệnh trong sandbox, app **thêm quyền (ACE) cho SID AppContainer** trên thư mục làm việc (ghi), thư mục cài Python gốc (đọc), gốc venv và `Scripts` (đọc). Không xoá quyền nào. Thư mục chứa PySide6 không bao giờ nhận quyền kế thừa; một quyền kế thừa sai trên venv (từ bản dev trước) được tự gỡ.
- Credential: không đổi. Khi chặn, trạng thái đăng nhập M365 được đọc thẳng từ kho token trên máy, không dựng MSAL.

## Compatibility

- [x] No breaking change
- [ ] Breaking change documented

Ghi chú: `block_network` mặc định đổi từ bật sang tắt cho cấu hình mới; máy đã lưu `true` thì giữ nguyên. Khi đang chặn, lệnh dùng công cụ cài trong thư mục người dùng (ngoài Program Files) có thể báo Access denied; thư viện trong venv của app không dùng được trong sandbox.

## Reviewer Notes

- `infrastructure/sandbox/appcontainer_process.py` gọi Win32 bằng ctypes (CreateAppContainerProfile, CreateProcessW với SECURITY_CAPABILITIES) và dùng `icacls` để cấp quyền: nên xem kỹ phần cấp quyền.
- `tests/conftest.py` thêm fixture autouse gỡ `network_guard` sau mỗi test, vì `build_context()` gắn cổng này ở mức process.
- `core/task_executors.py` đang đúng bằng trần LOC nên `_run_script` được tách sang `core/task_script.py`.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: minhanhpkpro <minhanhpkpro@gmail.com>
Co-authored-by: Duy Le Huu <duylh19@fpt.com>
Co-authored-by: thanhnv <thanhnv.ip@gmail.com>
Reviewed-on: #13
2026-09-20 12:26:03 +00:00

161 lines
6.5 KiB
Python

"""Read-only Jira connector for the agent (jira_search / jira_get_issue).
Talks to Jira Cloud's REST API v2 with Basic auth (email + API token), so no
OAuth/app setup is needed — the user pastes a base URL, their Atlassian email
and an API token (id.atlassian.com → Security → API tokens) once in
Monitoring → Tools. Read-only: it fetches issues/fields, never writes.
Every function returns a human-readable text block (or an explanatory error
string) and never raises, so a Jira hiccup can't break an agent turn.
"""
from __future__ import annotations
import re
from typing import Any, Dict, List, Optional
from urllib.parse import parse_qs, urlparse
_TIMEOUT = (10, 20)
_MAX_RESULTS = 25
_KEY_RE = re.compile(r"\b([A-Z][A-Z0-9]+-\d+)\b")
def _conf(config: Dict[str, Any] | None) -> Dict[str, str]:
"""Ba trường cấu hình Jira đã cắt khoảng trắng: base_url, email, api_token."""
return {k: str((config or {}).get(k, "") or "").strip()
for k in ("base_url", "email", "api_token")}
def configured(config: Dict[str, Any] | None) -> bool:
"""Đã cấu hình đủ ba trường để gọi Jira chưa."""
c = _conf(config)
return bool(c["base_url"] and c["email"] and c["api_token"])
def key_from_url(url: str) -> Optional[str]:
"""Extract an issue key (ABX-123) from a Jira URL — handles /browse/KEY and
boards/backlog links with ?selectedIssue=KEY. Returns None if none found."""
if not url:
return None
try:
parsed = urlparse(url)
except ValueError:
return None
sel = parse_qs(parsed.query or "").get("selectedIssue")
if sel:
m = _KEY_RE.search(sel[0])
if m:
return m.group(1)
m = _KEY_RE.search(parsed.path or "")
return m.group(1) if m else None
def base_url_from_link(url: str) -> str:
"""Derive the Jira site base URL (scheme://host) from ANY pasted Jira link,
so the user can paste an issue/board link and the base URL fills itself."""
try:
p = urlparse((url or "").strip())
except ValueError:
return ""
if p.scheme in ("http", "https") and p.hostname:
return f"{p.scheme}://{p.hostname}"
return ""
def is_jira_issue_url(config: Dict[str, Any] | None, url: str) -> bool:
"""True when ``url`` points at an issue on the CONFIGURED Jira host — so a
pasted link can be resolved through the authenticated API instead of a raw
(login-walled) HTTP fetch."""
if not configured(config) or not url:
return False
try:
host = (urlparse(url).hostname or "").lower()
base = (urlparse(_conf(config)["base_url"]).hostname or "").lower()
except ValueError:
return False
return bool(host and base and host == base and key_from_url(url))
def get_issue_by_url(config: Dict[str, Any] | None, url: str) -> str:
"""Read the issue a Jira URL points at, via the authenticated API."""
key = key_from_url(url)
if not key:
return f"[Jira link: {url}] (couldn't find an issue key in the URL)."
return get_issue(config, key)
def _get(config: Dict[str, Any], path: str, params: dict = None):
"""Gọi Jira REST API bằng xác thực cơ bản, qua lớp TLS có ghim chứng chỉ nội bộ."""
from ..application.network import network_guard
from . import tls_trust
network_guard.ensure_allowed("Jira")
c = _conf(config)
url = c["base_url"].rstrip("/") + path
# Same TLS auto-recovery the LLM provider calls get (core/tls_trust.py) —
# a corporate gateway that terminates TLS with its own certificate used to
# break this outright with SSLCertVerificationError.
resp = tls_trust.request("get", url, params=params or {}, timeout=_TIMEOUT,
auth=(c["email"], c["api_token"]),
headers={"Accept": "application/json"})
resp.raise_for_status()
return resp.json()
def _fmt_issue(it: dict) -> str:
"""Một dòng tóm tắt issue: mã, trạng thái và tiêu đề."""
f = it.get("fields", {}) or {}
status = (f.get("status") or {}).get("name", "?")
assignee = (f.get("assignee") or {}).get("displayName", "unassigned")
prio = (f.get("priority") or {}).get("name", "")
parts = [f"{it.get('key', '?')} — {f.get('summary', '(no summary)')}",
f" status: {status} · assignee: {assignee}" + (f" · priority: {prio}" if prio else "")]
return "\n".join(parts)
def search(config: Dict[str, Any] | None, jql: str, max_results: int = _MAX_RESULTS) -> str:
"""Search issues by JQL, e.g. ``project = ABX AND status = "In Progress"``."""
if not configured(config):
return ("Jira is not configured. Set base URL, email and API token in "
"Monitoring → Tools → Jira first.")
if not (jql or "").strip():
return "jira_search: a JQL query is required."
try:
data = _get(config, "/rest/api/2/search",
{"jql": jql, "maxResults": max(1, min(max_results, 50)),
"fields": "summary,status,assignee,priority"})
except Exception as exc: # noqa: BLE001
return f"Jira search failed: {exc}"
issues: List[dict] = data.get("issues", []) or []
if not issues:
return f"No issues match: {jql}"
total = data.get("total", len(issues))
head = f"Found {total} issue(s) for `{jql}` (showing {len(issues)}):\n"
return head + "\n\n".join(_fmt_issue(it) for it in issues)
def get_issue(config: Dict[str, Any] | None, key: str) -> str:
"""Fetch one issue's key fields + description by key (e.g. ABX-123)."""
if not configured(config):
return ("Jira is not configured. Set base URL, email and API token in "
"Monitoring → Tools → Jira first.")
key = (key or "").strip()
if not key:
return "jira_get_issue: an issue key is required (e.g. ABX-123)."
try:
it = _get(config, f"/rest/api/2/issue/{key}",
{"fields": "summary,status,assignee,priority,description,labels,updated"})
except Exception as exc: # noqa: BLE001
return f"Could not fetch {key}: {exc}"
f = it.get("fields", {}) or {}
desc = f.get("description")
if isinstance(desc, dict): # ADF (v3) → not requested here, but be safe
desc = "(rich-text description — open in Jira)"
lines = [_fmt_issue(it)]
if f.get("labels"):
lines.append(f" labels: {', '.join(f['labels'])}")
if f.get("updated"):
lines.append(f" updated: {f['updated']}")
if desc:
lines.append(f"\n{str(desc)[:4000]}")
return "\n".join(lines)