Compare commits
2
Commits
f084f71c72
...
hardening
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
82c6f7726e | ||
|
|
025c5dbfb2 |
@@ -271,6 +271,16 @@ def get_history_any_user(tab_id: str, limit: int = 100) -> list[dict]:
|
||||
return [dict(r) for r in reversed(rows)]
|
||||
|
||||
|
||||
def get_tab_owner(tab_id: str) -> str | None:
|
||||
"""Username who owns a dialog tab (author of its first message)."""
|
||||
with _conn() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT username FROM messages WHERE tab_id = ? ORDER BY id LIMIT 1",
|
||||
(tab_id,),
|
||||
).fetchone()
|
||||
return row["username"] if row else None
|
||||
|
||||
|
||||
# === Audit Log ===
|
||||
|
||||
def log_action(username: str | None, action: str, method: str, path: str,
|
||||
|
||||
@@ -136,7 +136,7 @@ MAX_MESSAGE_LEN = 10_000
|
||||
|
||||
# ⚠️ Версия UI — единый источник. БАМПАТЬ ПРИ КАЖДОМ ДЕПЛОЕ (формат: YYYY-MM-DD + буква).
|
||||
# Фронт берёт её через GET /api/version (chat.html + admin.html, элемент .app-version).
|
||||
APP_VERSION = "2026-06-25"
|
||||
APP_VERSION = "2026-07-03b"
|
||||
|
||||
# Audit: path → action name mapping
|
||||
_AUDIT_MAP = [
|
||||
@@ -424,9 +424,23 @@ async def register_page():
|
||||
return Path("static/register.html").read_text(encoding="utf-8")
|
||||
|
||||
|
||||
def _work_dir_snapshot(work_dir: Path) -> dict:
|
||||
"""Map filename -> (mtime_ns, size) for visible files in work_dir."""
|
||||
snap = {}
|
||||
for f in work_dir.iterdir():
|
||||
if f.is_file() and not f.name.startswith("."):
|
||||
st = f.stat()
|
||||
snap[f.name] = (st.st_mtime_ns, st.st_size)
|
||||
return snap
|
||||
|
||||
|
||||
async def _stream_and_save(message: str, user: str, tab_id: str):
|
||||
"""Wrap stream_claude to save messages to DB."""
|
||||
save_message(user, tab_id, "user", message)
|
||||
# Снимок work_dir ДО ответа: после ответа diff покажет файлы, которые
|
||||
# агент создал/изменил, и пользователь получит кнопки скачивания в чате.
|
||||
work_dir = get_work_dir(user, tab_id)
|
||||
before = _work_dir_snapshot(work_dir)
|
||||
full_response = ""
|
||||
async for chunk in stream_claude(message, user, tab_id):
|
||||
yield chunk
|
||||
@@ -452,6 +466,20 @@ async def _stream_and_save(message: str, user: str, tab_id: str):
|
||||
pass
|
||||
if full_response:
|
||||
save_message(user, tab_id, "assistant", full_response)
|
||||
# Новые/изменённые файлы за время ответа → кнопки скачивания в чате.
|
||||
# .md включён: агент отдаёт отчёты и в markdown. Служебные *_csv/ —
|
||||
# директории, отсекаются is_file().
|
||||
new_files = []
|
||||
for name, (mtime_ns, size) in sorted(_work_dir_snapshot(work_dir).items()):
|
||||
if not (is_allowed_file(name) or name.lower().endswith(".md")):
|
||||
continue
|
||||
if before.get(name) != (mtime_ns, size):
|
||||
new_files.append({"name": name, "size": size})
|
||||
if new_files:
|
||||
# role='files' — не попадает в history_recap (там только user/assistant),
|
||||
# но восстанавливает кнопки при перезагрузке истории.
|
||||
save_message(user, tab_id, "files", json.dumps(new_files, ensure_ascii=False))
|
||||
yield f"event: files\ndata: {json.dumps({'files': new_files}, ensure_ascii=False)}\n\n"
|
||||
|
||||
|
||||
@app.post("/api/chat")
|
||||
@@ -550,11 +578,31 @@ async def upload(request: Request, file: UploadFile):
|
||||
return {"filename": safe_name, "size": total}
|
||||
|
||||
|
||||
def _admin_tab_owner(request: Request, user: str, tab_id: str) -> str | None:
|
||||
"""Владелец вкладки, если её смотрит админ (зеркало фолбэка /api/history).
|
||||
|
||||
Не-админам и для собственных вкладок возвращает None."""
|
||||
from auth import get_token_role
|
||||
token = request.headers.get("authorization", "").removeprefix("Bearer ").strip()
|
||||
if get_token_role(token) != "admin":
|
||||
return None
|
||||
from db import get_tab_owner
|
||||
owner = get_tab_owner(tab_id)
|
||||
if not owner or owner == user:
|
||||
return None
|
||||
return owner
|
||||
|
||||
|
||||
@app.get("/api/files")
|
||||
async def files(request: Request):
|
||||
user = _get_user(request)
|
||||
tab_id = request.headers.get("x-tab-id", "default")
|
||||
return list_user_files(user, tab_id)
|
||||
result = list_user_files(user, tab_id)
|
||||
if not result:
|
||||
owner = _admin_tab_owner(request, user, tab_id)
|
||||
if owner:
|
||||
result = list_user_files(owner, tab_id)
|
||||
return result
|
||||
|
||||
|
||||
@app.get("/api/files/{filename}")
|
||||
@@ -564,7 +612,11 @@ async def download_file(filename: str, request: Request):
|
||||
safe_name = Path(filename).name
|
||||
fpath = get_work_dir(user, tab_id) / safe_name
|
||||
if not fpath.exists() or not fpath.is_file():
|
||||
raise HTTPException(404, "File not found")
|
||||
owner = _admin_tab_owner(request, user, tab_id)
|
||||
if owner:
|
||||
fpath = get_work_dir(owner, tab_id) / safe_name
|
||||
if not fpath.exists() or not fpath.is_file():
|
||||
raise HTTPException(404, "File not found")
|
||||
return FileResponse(fpath, filename=filename)
|
||||
|
||||
|
||||
|
||||
+41
-18
@@ -76,6 +76,8 @@ button { font-family: inherit; }
|
||||
.msg-file { align-self: flex-start; background: var(--file-bg); border: 1px solid var(--file-border); font-size: .85rem; }
|
||||
.msg-file a { color: #16a34a; text-decoration: none; font-weight: 500; }
|
||||
.msg-file a:hover { text-decoration: underline; }
|
||||
.dl-btn { display: block; width: fit-content; margin: .35rem 0 0; padding: .45rem .8rem; background: #16a34a; color: #fff !important; border-radius: var(--radius); font-weight: 600; }
|
||||
.dl-btn:hover { background: #15803d; text-decoration: none !important; }
|
||||
.msg-error { align-self: center; background: var(--error-bg); border: 1px solid var(--error-border); color: #e03131; font-size: .85rem; box-shadow: none; }
|
||||
.msg-system { align-self: center; background: var(--system-bg); border: none; font-size: .8rem; color: var(--system-text); box-shadow: none; padding: .4rem .8rem; }
|
||||
.typing { align-self: flex-start; color: var(--text-light); font-style: italic; font-size: .85rem; padding: .4rem 0; }
|
||||
@@ -978,6 +980,9 @@ async function sendMessage() {
|
||||
if (!aiText && data.result) {
|
||||
aiDiv = addMsg('ai', data.result);
|
||||
}
|
||||
} else if (eventType === 'files') {
|
||||
// Агент подготовил файлы — кнопки скачивания прямо в чате
|
||||
if (data.files && data.files.length) addFilesMsg(data.files);
|
||||
}
|
||||
eventType = '';
|
||||
}
|
||||
@@ -1019,29 +1024,44 @@ function closeSidebar() {
|
||||
document.getElementById('sidebar-backdrop').classList.remove('show');
|
||||
}
|
||||
|
||||
function downloadWorkFile(name) {
|
||||
fetch(API + '/api/files/' + encodeURIComponent(name), {headers: authHeaders()})
|
||||
.then(r => { if (!r.ok) throw new Error(r.status); return r.blob(); })
|
||||
.then(b => {
|
||||
const u = URL.createObjectURL(b);
|
||||
const l = document.createElement('a');
|
||||
l.href = u; l.download = name; l.click();
|
||||
// Немедленный revoke в Firefox может оборвать ещё не начавшееся скачивание
|
||||
setTimeout(() => URL.revokeObjectURL(u), 30000);
|
||||
})
|
||||
.catch(err => addMsg('error', 'Не удалось скачать «' + name + '» (ошибка ' + err.message + '). Обновите страницу и попробуйте ещё раз.'));
|
||||
}
|
||||
|
||||
function fmtSize(size) {
|
||||
return size >= 1048576 ? (size / 1048576).toFixed(1) + ' МБ' : (size / 1024).toFixed(1) + ' КБ';
|
||||
}
|
||||
|
||||
// Message with download buttons for files the agent prepared. files: [{name, size}]
|
||||
function addFilesMsg(files, ts, title) {
|
||||
const div = addMsg('file', title || 'Готовые файлы:', ts);
|
||||
const copyBtn = div.querySelector('.copy-btn'); // кнопки файлов — над «Копировать»
|
||||
files.forEach(f => {
|
||||
const a = document.createElement('a');
|
||||
a.className = 'dl-btn';
|
||||
a.textContent = '⬇ ' + f.name + ' (' + fmtSize(f.size) + ')';
|
||||
a.href = API + '/api/files/' + encodeURIComponent(f.name);
|
||||
a.onclick = e => { e.preventDefault(); downloadWorkFile(f.name); };
|
||||
div.insertBefore(a, copyBtn);
|
||||
});
|
||||
return div;
|
||||
}
|
||||
|
||||
async function listFiles() {
|
||||
const r = await fetch(API + '/api/files', {headers: authHeaders()});
|
||||
if (!r.ok) return;
|
||||
const files = await r.json();
|
||||
if (files.length === 0) { addMsg('system', 'Файлов нет.'); return; }
|
||||
const list = files.map(f => {
|
||||
const kb = (f.size / 1024).toFixed(1);
|
||||
return f.name + ' (' + kb + ' KB)';
|
||||
}).join('\n');
|
||||
const div = addMsg('file', 'Файлы в рабочей директории:\n' + list);
|
||||
// Add download links
|
||||
files.forEach(f => {
|
||||
const a = document.createElement('a');
|
||||
a.textContent = ' [скачать ' + f.name + ']';
|
||||
a.href = API + '/api/files/' + encodeURIComponent(f.name);
|
||||
a.onclick = e => {
|
||||
e.preventDefault();
|
||||
fetch(a.href, {headers: authHeaders()})
|
||||
.then(r => r.blob())
|
||||
.then(b => { const u = URL.createObjectURL(b); const l = document.createElement('a'); l.href = u; l.download = f.name; l.click(); });
|
||||
};
|
||||
div.appendChild(a);
|
||||
});
|
||||
addFilesMsg(files, null, 'Файлы в рабочей директории:');
|
||||
}
|
||||
|
||||
// --- History ---
|
||||
@@ -1056,6 +1076,9 @@ async function loadHistory() {
|
||||
if (m.role === 'user') addMsg('user', m.content, m.timestamp);
|
||||
else if (m.role === 'assistant') addMsg('ai', m.content, m.timestamp);
|
||||
else if (m.role === 'system') addMsg('system', m.content, m.timestamp);
|
||||
else if (m.role === 'files') {
|
||||
try { addFilesMsg(JSON.parse(m.content), m.timestamp); } catch {}
|
||||
}
|
||||
}
|
||||
} catch {}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
"""Admin viewing a foreign dialog must be able to download its files.
|
||||
|
||||
/api/history already falls back to any-user history for admins; /api/files and
|
||||
/api/files/{filename} resolved work_dir by the REQUESTER's username only →
|
||||
admin opening a user's dialog got 404 on every download button (prod incident
|
||||
2026-07-03, dialog smeta/b1f47437, admin yuri111@inbox.ru).
|
||||
"""
|
||||
|
||||
import importlib
|
||||
import os
|
||||
import sys
|
||||
|
||||
import pytest
|
||||
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
if ROOT not in sys.path:
|
||||
sys.path.insert(0, ROOT)
|
||||
|
||||
TAB = "tab-foreign"
|
||||
OWNER = "smeta"
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def env(tmp_path, monkeypatch):
|
||||
"""main.app + TestClient on isolated DB/DATA_DIR with a known JWT secret."""
|
||||
monkeypatch.setenv("DB_PATH", str(tmp_path / "t.db"))
|
||||
monkeypatch.setenv("DATA_DIR", str(tmp_path / "data"))
|
||||
monkeypatch.setenv("AI_BACKEND", "claude")
|
||||
monkeypatch.setenv("SESSION_SECRET", "test-secret")
|
||||
monkeypatch.chdir(ROOT)
|
||||
import db, auth, claude_bridge, main
|
||||
importlib.reload(db)
|
||||
importlib.reload(auth)
|
||||
importlib.reload(claude_bridge)
|
||||
importlib.reload(main)
|
||||
db.init_db()
|
||||
# Owner's dialog: a message row (makes them the tab owner) + a work file
|
||||
db.save_message(OWNER, TAB, "user", "составь смету")
|
||||
wd = main.get_work_dir(OWNER, TAB)
|
||||
(wd / "смета.xlsx").write_bytes(b"x" * 42)
|
||||
|
||||
from fastapi.testclient import TestClient
|
||||
client = TestClient(main.app)
|
||||
return auth, client
|
||||
|
||||
|
||||
def _headers(auth, username, role):
|
||||
return {
|
||||
"Authorization": "Bearer " + auth._make_token(username, role),
|
||||
"X-Tab-Id": TAB,
|
||||
}
|
||||
|
||||
|
||||
def test_admin_downloads_file_from_foreign_dialog(env):
|
||||
auth, client = env
|
||||
r = client.get("/api/files/смета.xlsx", headers=_headers(auth, "boss@x", "admin"))
|
||||
assert r.status_code == 200
|
||||
assert r.content == b"x" * 42
|
||||
|
||||
|
||||
def test_admin_lists_files_of_foreign_dialog(env):
|
||||
auth, client = env
|
||||
r = client.get("/api/files", headers=_headers(auth, "boss@x", "admin"))
|
||||
assert r.status_code == 200
|
||||
assert [f["name"] for f in r.json()] == ["смета.xlsx"]
|
||||
|
||||
|
||||
def test_regular_user_cannot_download_foreign_file(env):
|
||||
auth, client = env
|
||||
r = client.get("/api/files/смета.xlsx", headers=_headers(auth, "mallory@x", "user"))
|
||||
assert r.status_code == 404
|
||||
|
||||
|
||||
def test_regular_user_foreign_list_is_empty(env):
|
||||
auth, client = env
|
||||
r = client.get("/api/files", headers=_headers(auth, "mallory@x", "user"))
|
||||
assert r.status_code == 200
|
||||
assert r.json() == []
|
||||
|
||||
|
||||
def test_owner_still_downloads_own_file(env):
|
||||
auth, client = env
|
||||
r = client.get("/api/files/смета.xlsx", headers=_headers(auth, OWNER, "user"))
|
||||
assert r.status_code == 200
|
||||
assert r.content == b"x" * 42
|
||||
@@ -0,0 +1,129 @@
|
||||
"""Files-event tests: agent-created files must reach the user as chat download buttons.
|
||||
|
||||
_stream_and_save diffs the work dir around the stream and emits `event: files`
|
||||
with new/changed files + persists a role='files' row for history reload.
|
||||
No GLM/Docker/.env needed: stream_claude is stubbed.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import importlib
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
|
||||
import pytest
|
||||
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
if ROOT not in sys.path:
|
||||
sys.path.insert(0, ROOT)
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def env(tmp_path, monkeypatch):
|
||||
"""main.py bound to isolated temp DB + DATA_DIR, real bridges untouched."""
|
||||
monkeypatch.setenv("DB_PATH", str(tmp_path / "t.db"))
|
||||
monkeypatch.setenv("DATA_DIR", str(tmp_path / "data"))
|
||||
monkeypatch.setenv("AI_BACKEND", "claude")
|
||||
monkeypatch.chdir(ROOT) # main.py mounts ./static at import
|
||||
import db
|
||||
importlib.reload(db)
|
||||
import claude_bridge
|
||||
importlib.reload(claude_bridge)
|
||||
import main
|
||||
importlib.reload(main)
|
||||
db.init_db()
|
||||
return db, main
|
||||
|
||||
|
||||
def _run(main_mod, message="сделай смету", user="u", tab="tab"):
|
||||
async def collect():
|
||||
return [c async for c in main_mod._stream_and_save(message, user, tab)]
|
||||
return asyncio.run(collect())
|
||||
|
||||
|
||||
def _files_events(chunks):
|
||||
out = []
|
||||
for c in chunks:
|
||||
if c.startswith("event: files\n"):
|
||||
out.append(json.loads(c.split("data: ", 1)[1].strip()))
|
||||
return out
|
||||
|
||||
|
||||
def test_agent_created_file_emits_files_event_and_persists(env, monkeypatch):
|
||||
db, main = env
|
||||
|
||||
async def fake_stream(message, user, tab_id):
|
||||
wd = main.get_work_dir(user, tab_id)
|
||||
(wd / "смета_готовая.xlsx").write_bytes(b"x" * 100)
|
||||
yield 'event: text\ndata: {"text": "Готово"}\n\n'
|
||||
yield 'event: done\ndata: {"result": "Готово"}\n\n'
|
||||
|
||||
monkeypatch.setattr(main, "stream_claude", fake_stream)
|
||||
chunks = _run(main)
|
||||
|
||||
events = _files_events(chunks)
|
||||
assert events == [{"files": [{"name": "смета_готовая.xlsx", "size": 100}]}]
|
||||
|
||||
# role='files' row persisted so history reload re-renders the buttons
|
||||
rows = db.get_history("u", "tab")
|
||||
files_rows = [r for r in rows if r["role"] == "files"]
|
||||
assert len(files_rows) == 1
|
||||
assert json.loads(files_rows[0]["content"]) == [
|
||||
{"name": "смета_готовая.xlsx", "size": 100}
|
||||
]
|
||||
|
||||
|
||||
def test_preexisting_upload_not_reannounced(env, monkeypatch):
|
||||
"""A file uploaded before the turn (unchanged) must NOT get a button again."""
|
||||
db, main = env
|
||||
wd = main.get_work_dir("u", "tab")
|
||||
(wd / "загруженная.xlsm").write_bytes(b"y" * 50)
|
||||
|
||||
async def fake_stream(message, user, tab_id):
|
||||
yield 'event: done\ndata: {"result": "ответ без файлов"}\n\n'
|
||||
|
||||
monkeypatch.setattr(main, "stream_claude", fake_stream)
|
||||
chunks = _run(main)
|
||||
|
||||
assert _files_events(chunks) == []
|
||||
assert all(r["role"] != "files" for r in db.get_history("u", "tab"))
|
||||
|
||||
|
||||
def test_modified_upload_is_reannounced(env, monkeypatch):
|
||||
"""Agent editing an uploaded file in place → user gets the fresh version."""
|
||||
db, main = env
|
||||
wd = main.get_work_dir("u", "tab")
|
||||
(wd / "реестр.xlsm").write_bytes(b"old")
|
||||
|
||||
async def fake_stream(message, user, tab_id):
|
||||
f = main.get_work_dir(user, tab_id) / "реестр.xlsm"
|
||||
f.write_bytes(b"new-longer-content")
|
||||
yield 'event: done\ndata: {"result": "заполнил"}\n\n'
|
||||
|
||||
monkeypatch.setattr(main, "stream_claude", fake_stream)
|
||||
chunks = _run(main)
|
||||
|
||||
events = _files_events(chunks)
|
||||
assert len(events) == 1
|
||||
assert events[0]["files"][0]["name"] == "реестр.xlsm"
|
||||
|
||||
|
||||
def test_service_files_excluded(env, monkeypatch):
|
||||
"""Scratch .py/.log and hidden files are noise — no download buttons."""
|
||||
db, main = env
|
||||
|
||||
async def fake_stream(message, user, tab_id):
|
||||
wd = main.get_work_dir(user, tab_id)
|
||||
(wd / "script.py").write_text("print(1)")
|
||||
(wd / "debug.log").write_text("...")
|
||||
(wd / ".hidden").write_text("...")
|
||||
(wd / "отчёт.md").write_text("# Отчёт") # .md — валидный артефакт
|
||||
yield 'event: done\ndata: {"result": "ok"}\n\n'
|
||||
|
||||
monkeypatch.setattr(main, "stream_claude", fake_stream)
|
||||
chunks = _run(main)
|
||||
|
||||
events = _files_events(chunks)
|
||||
assert len(events) == 1
|
||||
names = [f["name"] for f in events[0]["files"]]
|
||||
assert names == ["отчёт.md"]
|
||||
Reference in New Issue
Block a user