CI / test (push) Canceled after 0s
## 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
179 lines
7.3 KiB
Python
179 lines
7.3 KiB
Python
"""Microsoft Teams notifications via Incoming Webhook / Power Automate Workflow.
|
|
|
|
The user pastes a webhook URL in Settings. We try the common payload formats in
|
|
order so it works with both classic Incoming Webhook connectors (MessageCard)
|
|
and the newer Workflows (Adaptive Card) URLs.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
from typing import Dict, List, Optional, Tuple
|
|
|
|
import requests
|
|
|
|
from . import tls_trust
|
|
|
|
_TIMEOUT = 20
|
|
ACCENT = "F37021"
|
|
|
|
|
|
class TeamsNotifier:
|
|
"""Gửi thông báo lên Microsoft Teams qua webhook.
|
|
|
|
Tự thử hai khuôn thẻ: Adaptive Card (webhook Workflows mới) rồi tới
|
|
MessageCard (webhook Connector cũ) — hai loại webhook không nhận chung một khuôn.
|
|
"""
|
|
def __init__(self, webhook_url: str = "", ca_bundle: str = ""):
|
|
"""``webhook_url`` rỗng nghĩa là chưa cấu hình — mọi lượt gửi về sau lặng lẽ bỏ
|
|
qua thay vì lỗi.
|
|
"""
|
|
self.webhook_url = (webhook_url or "").strip()
|
|
self.ca_bundle = (ca_bundle or "").strip()
|
|
|
|
@property
|
|
def configured(self) -> bool:
|
|
"""Đã cấu hình webhook hợp lệ chưa."""
|
|
return self.webhook_url.startswith("http")
|
|
|
|
def send(
|
|
self,
|
|
title: str,
|
|
text: str,
|
|
facts: Optional[Dict[str, str]] = None,
|
|
) -> Tuple[bool, str]:
|
|
"""Post a notification. Returns ``(ok, detail)``."""
|
|
if not self.configured:
|
|
return False, "Teams webhook URL is not configured."
|
|
from ..application.network import network_guard
|
|
|
|
if network_guard.is_blocked():
|
|
return False, network_guard.refusal("Teams notification")
|
|
|
|
# Workflows webhooks expect an Adaptive Card; classic connectors expect a
|
|
# MessageCard. Try both, then a plain-text fallback.
|
|
payloads = [
|
|
self._adaptive_card(title, text, facts),
|
|
self._message_card(title, text, facts),
|
|
{"text": f"**{title}**\n\n{text}"},
|
|
]
|
|
warn = self.url_warning()
|
|
last = ""
|
|
for payload in payloads:
|
|
try:
|
|
resp = self._post(self.webhook_url, payload)
|
|
except requests.RequestException as exc:
|
|
last = f"Teams connection error: {exc}"
|
|
continue
|
|
if resp.status_code < 300:
|
|
return True, "Notification sent to Teams."
|
|
last = self._explain(resp)
|
|
if warn:
|
|
last = f"{last} {warn}"
|
|
return False, last
|
|
|
|
_WEBHOOK_HOSTS = ("logic.azure.com", "webhook.office.com", "office.com", "powerplatform", "powerautomate")
|
|
|
|
def url_warning(self) -> str:
|
|
"""Return a hint if the configured URL doesn't look like a real webhook."""
|
|
url = self.webhook_url.lower()
|
|
if not any(h in url for h in self._WEBHOOK_HOSTS):
|
|
return ("⚠ This URL doesn't look like a Teams webhook — it should contain "
|
|
"'logic.azure.com' or 'webhook.office.com'. Copy the FULL HTTP URL from "
|
|
"Teams → Workflows → 'Post to a channel when a webhook request is received'.")
|
|
if "logic.azure.com" in url and "sig=" not in url:
|
|
return "⚠ The Workflows URL looks incomplete (missing '&sig=...'). Copy the entire URL."
|
|
return ""
|
|
|
|
def _post(self, url: str, payload: Dict):
|
|
"""POST while preserving the method across redirects.
|
|
|
|
``requests`` downgrades POST→GET on 301/302/303 redirects, and Teams
|
|
webhooks (``*.webhook.office.com``) often 302 to a regional endpoint —
|
|
the GET then fails with 405. We follow redirects manually as POST.
|
|
"""
|
|
current = url
|
|
resp = None
|
|
for _ in range(5):
|
|
verify = tls_trust.verify_for(current, self.ca_bundle)
|
|
try:
|
|
resp = requests.post(
|
|
current,
|
|
json=payload,
|
|
timeout=_TIMEOUT,
|
|
allow_redirects=False,
|
|
headers={"Content-Type": "application/json"},
|
|
verify=verify,
|
|
)
|
|
except requests.exceptions.SSLError as exc:
|
|
# Self-signed/internal-CA gateway: capture and pin its exact
|
|
# certificate instead of asking the user to hunt down a .pem
|
|
# file — see core.tls_trust.
|
|
if self.ca_bundle or not tls_trust.looks_like_cert_trust_error(exc):
|
|
raise
|
|
pinned = tls_trust.capture_and_trust(current)
|
|
if not pinned:
|
|
raise
|
|
resp = requests.post(
|
|
current, json=payload, timeout=_TIMEOUT, allow_redirects=False,
|
|
headers={"Content-Type": "application/json"}, verify=pinned,
|
|
)
|
|
if resp.status_code in (301, 302, 303, 307, 308):
|
|
location = (getattr(resp, "headers", {}) or {}).get("Location")
|
|
if location:
|
|
current = location
|
|
continue
|
|
return resp
|
|
return resp
|
|
|
|
@staticmethod
|
|
def _explain(resp) -> str:
|
|
"""Đổi phản hồi lỗi của Teams thành câu đọc được, kèm mã HTTP và 200 ký tự thân."""
|
|
code = resp.status_code
|
|
body = (getattr(resp, "text", "") or "")[:200]
|
|
if code == 405:
|
|
return ("Teams returned 405 (Method Not Allowed). The webhook URL is likely the "
|
|
"wrong type or expired. Recreate it via Teams → Workflows → "
|
|
"'Post to a channel when a webhook request is received' and paste the new URL.")
|
|
if code in (401, 403):
|
|
return f"Teams returned {code} (forbidden). The webhook may be revoked — recreate the URL."
|
|
if code == 404:
|
|
return "Teams returned 404. The webhook URL does not exist — check it or create a new one."
|
|
return f"Teams error {code}: {body}"
|
|
|
|
@staticmethod
|
|
def _message_card(title: str, text: str, facts: Optional[Dict[str, str]]) -> Dict:
|
|
"""Dựng payload khuôn MessageCard (webhook Connector cũ)."""
|
|
section: Dict = {"activityTitle": title, "text": text}
|
|
if facts:
|
|
section["facts"] = [{"name": k, "value": v} for k, v in facts.items()]
|
|
return {
|
|
"@type": "MessageCard",
|
|
"@context": "http://schema.org/extensions",
|
|
"themeColor": ACCENT,
|
|
"summary": title,
|
|
"sections": [section],
|
|
}
|
|
|
|
@staticmethod
|
|
def _adaptive_card(title: str, text: str, facts: Optional[Dict[str, str]]) -> Dict:
|
|
"""Dựng payload khuôn Adaptive Card (webhook Workflows mới)."""
|
|
body: List[Dict] = [
|
|
{"type": "TextBlock", "text": title, "weight": "Bolder", "size": "Medium"},
|
|
{"type": "TextBlock", "text": text, "wrap": True},
|
|
]
|
|
if facts:
|
|
body.append({
|
|
"type": "FactSet",
|
|
"facts": [{"title": k, "value": v} for k, v in facts.items()],
|
|
})
|
|
return {
|
|
"type": "message",
|
|
"attachments": [{
|
|
"contentType": "application/vnd.microsoft.card.adaptive",
|
|
"content": {
|
|
"type": "AdaptiveCard",
|
|
"version": "1.4",
|
|
"body": body,
|
|
},
|
|
}],
|
|
}
|