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
147 lines
6.4 KiB
Python
147 lines
6.4 KiB
Python
"""Command tools - run_command, install_package (R05-T02).
|
|
|
|
Moved verbatim out of ``core/tools.py`` (see ``file_tools.py`` for why). These
|
|
two are the ones today's hand-written permission gate in
|
|
``core/chat_agent.py`` singles out by literal name
|
|
(``name in ("run_command", "install_package")``) — R05-T03 replaces that
|
|
tuple with a capability lookup, but the tools themselves are unchanged here.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import os
|
|
from pathlib import Path
|
|
from typing import Any, Dict, Optional
|
|
|
|
from .tool_context import CancelFn, ToolContext
|
|
|
|
COMMAND_TIMEOUT = 120 # seconds
|
|
|
|
_SNAPSHOT_SKIP = {".git", "__pycache__", "node_modules", ".scratch", ".venv",
|
|
".idea", ".mypy_cache", ".pytest_cache"}
|
|
|
|
|
|
def _snapshot(workdir: Path) -> Dict[str, Any]:
|
|
"""Map of file path -> (mtime, size) under the workdir (noise dirs skipped)."""
|
|
snap: Dict[str, Any] = {}
|
|
try:
|
|
for dirpath, dirnames, filenames in os.walk(str(workdir)):
|
|
dirnames[:] = [d for d in dirnames if d not in _SNAPSHOT_SKIP]
|
|
for fn in filenames:
|
|
full = os.path.join(dirpath, fn)
|
|
try:
|
|
st = os.stat(full)
|
|
snap[full] = (st.st_mtime_ns, st.st_size)
|
|
except OSError:
|
|
pass
|
|
if len(snap) > 5000:
|
|
return snap
|
|
except OSError:
|
|
pass
|
|
return snap
|
|
|
|
|
|
def _sandbox_python(ctx: ToolContext, cancel: Optional[CancelFn] = None,
|
|
on_output=None) -> Optional[str]:
|
|
"""Lazily create/reuse this ctx's project sandbox venv (Code tab only —
|
|
``ctx.sandbox``); returns its python path, or None to use the app's own."""
|
|
if not ctx.sandbox:
|
|
return None
|
|
from cowork_local.core.deps import ensure_project_venv
|
|
|
|
py = ensure_project_venv(ctx.workdir, cancel=cancel, on_output=on_output)
|
|
return str(py) if py else None
|
|
|
|
|
|
def run_command(ctx: ToolContext, args: Dict[str, Any],
|
|
cancel: Optional[CancelFn] = None,
|
|
on_output=None) -> Dict[str, Any]:
|
|
"""Chạy một lệnh shell trong thư mục làm việc, có hạn giờ và có sandbox.
|
|
|
|
Biến môi trường được lọc và mạng bị chặn theo cấu hình an toàn — agent chạy
|
|
lệnh không được thừa hưởng toàn bộ môi trường của người dùng.
|
|
"""
|
|
from cowork_local.core.deps import network_blocked_env, run_cancellable, sandbox_env
|
|
from cowork_local.core.sandbox_manager import ExecutionConfig, SandboxManager
|
|
from cowork_local.security.command_risk_classifier import (
|
|
classify_command, command_bypasses_network_proxy,
|
|
)
|
|
|
|
command = str(args.get("command", "")).strip()
|
|
if not command:
|
|
return {"ok": False, "output": "Empty command."}
|
|
|
|
# --- Security validation pipeline ---
|
|
risk = classify_command(command, is_cowork_mode=ctx.flatten_writes)
|
|
if risk.blocked:
|
|
denial = "Command blocked by security policy: " + "; ".join(risk.reasons)
|
|
return {"ok": False, "output": denial}
|
|
|
|
# With the network blocked, SandboxManager runs the command in an OS-level
|
|
# network-less process (AppContainer on Windows — see
|
|
# infrastructure/sandbox/network_isolation.py). Tools that exist only to
|
|
# reach the network (ping, nslookup, ssh...) are still denied BY NAME
|
|
# first: the model gets a clear reason instead of a cryptic socket error.
|
|
if ctx.block_network:
|
|
bypass_tool = command_bypasses_network_proxy(command)
|
|
if bypass_tool:
|
|
return {"ok": False, "output": (
|
|
f"Command blocked: '{bypass_tool}' can reach the network without going through "
|
|
"an HTTP proxy, so the sandbox's network block (which only filters proxy-aware "
|
|
"traffic) cannot stop it by itself — blocked by name instead while "
|
|
"'Chặn mạng cho lệnh do agent chạy' is on."
|
|
)}
|
|
|
|
# Route through SandboxManager for risk-based isolation
|
|
mgr = SandboxManager(ExecutionConfig(
|
|
enabled=True,
|
|
block_network_by_default=ctx.block_network,
|
|
is_cowork_mode=ctx.flatten_writes,
|
|
))
|
|
sandbox_result = mgr.run(
|
|
command=command,
|
|
workdir=str(ctx.workdir),
|
|
block_network=ctx.block_network,
|
|
timeout_sec=COMMAND_TIMEOUT,
|
|
cancel=cancel,
|
|
)
|
|
# Sandbox ALWAYS executes (never double-run). Return its result directly.
|
|
if sandbox_result.get("sandbox") == "blocked":
|
|
return {"ok": False, "output": sandbox_result.get("stderr", "Command blocked")}
|
|
out = sandbox_result.get("stdout", "").strip() or "(no output)"
|
|
err = sandbox_result.get("stderr", "")
|
|
rc = sandbox_result.get("returncode", -1)
|
|
if err:
|
|
out = f"{out}\n{err}" if out else err
|
|
return {"ok": sandbox_result.get("ok", False), "output": f"[exit {rc}]\n{out}"}
|
|
|
|
|
|
def install_package(ctx: ToolContext, args: Dict[str, Any],
|
|
cancel: Optional[CancelFn] = None,
|
|
on_output=None) -> Dict[str, Any]:
|
|
"""Cài một gói Python vào môi trường phụ trợ của lượt chạy.
|
|
|
|
Cài vào venv riêng chứ không vào Python của hệ thống — một task không được
|
|
phép làm hỏng môi trường của cả máy.
|
|
"""
|
|
from cowork_local.core.deps import pip_install
|
|
|
|
package = str(args.get("package", "")).strip()
|
|
if not package:
|
|
return {"ok": False, "output": "No package specified."}
|
|
# ``pip install`` bắt buộc phải ra internet, mà ``deps.pip_install`` chạy
|
|
# subprocess với ``os.environ`` nguyên vẹn — biến proxy hố đen của
|
|
# ``network_blocked_env`` không chạm tới nó. Từ chối thẳng ở đây (giống cách
|
|
# run_command chặn theo tên các công cụ không đi qua proxy) thay vì để pip
|
|
# thử 600 giây rồi báo một lỗi proxy khó hiểu.
|
|
if ctx.block_network:
|
|
return {"ok": False, "output": (
|
|
"install_package: network access is blocked by the Sandbox Security Layer "
|
|
"(\"Block network for agent-run commands\" is on in Settings).")}
|
|
python = _sandbox_python(ctx, cancel, on_output)
|
|
ok, detail = pip_install(package, cancel=cancel, on_output=on_output, python=python)
|
|
head = f"Installed {package}." if ok else f"Could not install {package}."
|
|
return {"ok": ok, "output": f"{head}\n{detail}"}
|
|
|
|
|
|
__all__ = ["COMMAND_TIMEOUT", "run_command", "install_package", "_snapshot"]
|