fix(security): блок ① — path-traversal через x-tab-id + дыры авторизации
- get_work_dir в обоих мостах клеил DATA_DIR/username/tab_id без проверки → заголовок x-tab-id ../.. читал (GET /api/files) и УДАЛЯЛ (POST /api/clear-files) файлы вне папки юзера. Единый guard path_safety.safe_work_dir: без переписывания символов (иначе пути существующих юзеров разъедутся) — только containment внутри каталога пользователя; traversal → чистый 400 (не 500 с утечкой). - batch v2/v3 и SSR проверяли лишь факт логина, не владельца job → любой залогиненный по угаданному id тянул чужую смету. Добавлен _require_job_owner (job["user"]==user, иначе 404) + сохранение владельца на upload. - /api/gen/download и /api/check/yaml были без auth; check/yaml отдавал сырой str(exc) наружу → добавлен _get_user, ошибка замаскирована, job_id санитизован. - fail-loud на пустой SESSION_SECRET при старте (был тихий warning). Тесты: test_path_safety (7), test_block1_auth (8) — mutation-честные. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
+2
-3
@@ -7,6 +7,7 @@ from pathlib import Path
|
||||
from typing import AsyncGenerator
|
||||
|
||||
from chat_context import history_recap
|
||||
from path_safety import safe_work_dir
|
||||
|
||||
DOCKER_IMAGE = os.environ.get("CLAUDE_DOCKER_IMAGE", "smeta-claude-sandbox")
|
||||
try:
|
||||
@@ -111,9 +112,7 @@ def _preprocess_xlsx(work_dir: Path):
|
||||
|
||||
|
||||
def get_work_dir(username: str, tab_id: str) -> Path:
|
||||
d = DATA_DIR / username / tab_id
|
||||
d.mkdir(parents=True, exist_ok=True)
|
||||
return d
|
||||
return safe_work_dir(username, tab_id) # блок path-traversal через client-controlled tab_id
|
||||
|
||||
|
||||
def get_session_id(username: str, tab_id: str) -> str | None:
|
||||
|
||||
@@ -14,6 +14,8 @@ from typing import AsyncGenerator
|
||||
|
||||
import httpx
|
||||
|
||||
from path_safety import safe_work_dir
|
||||
|
||||
SMETA_DIR = Path(os.environ.get("SMETA_PROJECT_DIR", os.path.expanduser("~/smeta-railway")))
|
||||
ZAI_API_KEY = os.environ.get("ZAI_API_KEY", "")
|
||||
ZAI_BASE_URL = os.environ.get("ZAI_BASE_URL", "https://open.bigmodel.cn/api/coding/paas/v4")
|
||||
@@ -245,9 +247,7 @@ from search_engine import _normalize, _search_fssc, _search_resources, _search_g
|
||||
|
||||
|
||||
def get_work_dir(username: str, tab_id: str) -> Path:
|
||||
d = DATA_DIR / username / tab_id
|
||||
d.mkdir(parents=True, exist_ok=True)
|
||||
return d
|
||||
return safe_work_dir(username, tab_id) # блок path-traversal через client-controlled tab_id
|
||||
|
||||
|
||||
def get_session_id(username: str, tab_id: str) -> str | None:
|
||||
|
||||
@@ -2,12 +2,15 @@
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
logger = logging.getLogger("smeta_web")
|
||||
|
||||
from fastapi import FastAPI, HTTPException, Request, UploadFile
|
||||
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse, StreamingResponse
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
@@ -133,12 +136,20 @@ else:
|
||||
app = FastAPI(title="smeta-web")
|
||||
app.mount("/static", StaticFiles(directory="static"), name="static")
|
||||
|
||||
from path_safety import UnsafePath
|
||||
|
||||
|
||||
@app.exception_handler(UnsafePath)
|
||||
async def _unsafe_path_handler(request: Request, exc: UnsafePath):
|
||||
# client-controlled tab_id/username пытался выйти из папки → чистый 400 без утечки
|
||||
return JSONResponse({"detail": "Некорректный идентификатор сессии"}, status_code=400)
|
||||
|
||||
MAX_UPLOAD_SIZE = 100 * 1024 * 1024 # 100 MB
|
||||
MAX_MESSAGE_LEN = 10_000
|
||||
|
||||
# ⚠️ Версия UI — единый источник. БАМПАТЬ ПРИ КАЖДОМ ДЕПЛОЕ (формат: YYYY-MM-DD + буква).
|
||||
# Фронт берёт её через GET /api/version (chat.html + admin.html, элемент .app-version).
|
||||
APP_VERSION = "2026-07-18f"
|
||||
APP_VERSION = "2026-07-18g"
|
||||
|
||||
# Audit: path → action name mapping
|
||||
_AUDIT_MAP = [
|
||||
@@ -191,6 +202,11 @@ def _resolve_action(method: str, path: str) -> str | None:
|
||||
|
||||
@app.on_event("startup")
|
||||
async def startup():
|
||||
# fail-loud: без секрета JWT-логин молча ломается, а download-ticket подписывается
|
||||
# пустым ключом (подделываемо). Лучше не стартовать, чем работать «тихо небезопасно».
|
||||
import auth
|
||||
if not auth.SECRET:
|
||||
raise RuntimeError("SESSION_SECRET не задан — отказ запуска (см. .env)")
|
||||
init_db()
|
||||
# Прогрев справочника ФГИС в фоне: системный промпт агента берёт квартал/регионы из диск-кэша
|
||||
# БЕЗ сетевого вызова в async-пути (иначе первый чат заморозил бы весь сервер до таймаута сети).
|
||||
@@ -272,6 +288,15 @@ def _get_tab(request: Request, body: dict | None = None) -> str:
|
||||
return request.headers.get("x-tab-id", "default")
|
||||
|
||||
|
||||
def _require_job_owner(job: dict | None, user: str) -> dict:
|
||||
"""Job принадлежит этому юзеру? Иначе 404 (не 403 — не палим существование
|
||||
чужого job_id). Раньше batch/SSR-эндпоинты проверяли только факт логина, но не
|
||||
владельца → любой залогиненный по угаданному id тянул чужую смету (Fable audit)."""
|
||||
if not job or job.get("user") != user:
|
||||
raise HTTPException(404, "Job not found")
|
||||
return job
|
||||
|
||||
|
||||
@app.get("/", response_class=HTMLResponse)
|
||||
async def index(request: Request):
|
||||
# Кэш-бастинг главной (как /admin): без актуального ?v= → 302 на URL с v=APP_VERSION
|
||||
@@ -1003,6 +1028,7 @@ async def batch_v2_upload(request: Request):
|
||||
|
||||
# Create job
|
||||
job = batch_v3.create_job(job_id)
|
||||
job["user"] = user # владелец — для проверки доступа в analyze/run/status/download
|
||||
job["source_dir"] = str(source_dir)
|
||||
job["target_file"] = str(target_path)
|
||||
job["target_name"] = target_name
|
||||
@@ -1027,10 +1053,8 @@ async def batch_v2_upload(request: Request):
|
||||
@app.post("/api/batch-v2/analyze/{job_id}")
|
||||
async def batch_v2_analyze(job_id: str, request: Request):
|
||||
"""Start Claude Code analysis — returns SSE stream."""
|
||||
_get_user(request)
|
||||
job = batch_v3.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(404, "Job not found")
|
||||
user = _get_user(request)
|
||||
job = _require_job_owner(batch_v3.get_job(job_id), user)
|
||||
|
||||
job_dir = Path(job["job_dir"])
|
||||
task_desc = job["task_description"]
|
||||
@@ -1068,10 +1092,8 @@ async def batch_v2_analyze(job_id: str, request: Request):
|
||||
@app.post("/api/batch-v2/run/{job_id}")
|
||||
async def batch_v2_run(job_id: str, request: Request):
|
||||
"""Confirm and run the Claude-generated script."""
|
||||
_get_user(request)
|
||||
job = batch_v3.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(404, "Job not found")
|
||||
user = _get_user(request)
|
||||
job = _require_job_owner(batch_v3.get_job(job_id), user)
|
||||
|
||||
script = job.get("analysis", {}).get("python_script", "")
|
||||
if not script:
|
||||
@@ -1088,10 +1110,8 @@ async def batch_v2_run(job_id: str, request: Request):
|
||||
|
||||
@app.get("/api/batch-v2/status/{job_id}")
|
||||
async def batch_v2_status(job_id: str, request: Request):
|
||||
_get_user(request)
|
||||
job = batch_v3.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(404, "Job not found")
|
||||
user = _get_user(request)
|
||||
job = _require_job_owner(batch_v3.get_job(job_id), user)
|
||||
|
||||
# If status is still "uploaded" but files exist on disk — Claude finished
|
||||
# but SSE didn't deliver the done event
|
||||
@@ -1118,9 +1138,9 @@ async def batch_v2_status(job_id: str, request: Request):
|
||||
|
||||
@app.get("/api/batch-v2/download/{job_id}")
|
||||
async def batch_v2_download(job_id: str, request: Request):
|
||||
_get_user(request)
|
||||
job = batch_v3.get_job(job_id)
|
||||
if not job or not job.get("output_file"):
|
||||
user = _get_user(request)
|
||||
job = _require_job_owner(batch_v3.get_job(job_id), user)
|
||||
if not job.get("output_file"):
|
||||
raise HTTPException(404, "Result not ready")
|
||||
return FileResponse(job["output_file"], filename=Path(job["output_file"]).name)
|
||||
|
||||
@@ -1506,6 +1526,7 @@ async def batch_v3_upload(request: Request):
|
||||
sample_info = batch_v3.prepare_samples(str(source_dir), job_dir, {})
|
||||
|
||||
job = batch_v3.create_job(job_id)
|
||||
job["user"] = user # владелец — для проверки доступа в analyze/run/status/download
|
||||
job["source_dir"] = str(source_dir)
|
||||
job["target_file"] = str(target_path)
|
||||
job["target_name"] = target_name
|
||||
@@ -1530,10 +1551,8 @@ async def batch_v3_upload(request: Request):
|
||||
@app.post("/api/batch-v3/analyze/{job_id}")
|
||||
async def batch_v3_analyze(job_id: str, request: Request):
|
||||
"""Generate + verify + auto-retry — SSE stream."""
|
||||
_get_user(request)
|
||||
job = batch_v3.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(404, "Job not found")
|
||||
user = _get_user(request)
|
||||
job = _require_job_owner(batch_v3.get_job(job_id), user)
|
||||
|
||||
job_dir = Path(job["job_dir"])
|
||||
|
||||
@@ -1574,10 +1593,8 @@ async def batch_v3_analyze(job_id: str, request: Request):
|
||||
|
||||
@app.post("/api/batch-v3/run/{job_id}")
|
||||
async def batch_v3_run(job_id: str, request: Request):
|
||||
_get_user(request)
|
||||
job = batch_v3.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(404, "Job not found")
|
||||
user = _get_user(request)
|
||||
job = _require_job_owner(batch_v3.get_job(job_id), user)
|
||||
script = job.get("analysis", {}).get("python_script", "")
|
||||
if not script:
|
||||
raise HTTPException(400, "No script")
|
||||
@@ -1591,10 +1608,8 @@ async def batch_v3_run(job_id: str, request: Request):
|
||||
|
||||
@app.get("/api/batch-v3/status/{job_id}")
|
||||
async def batch_v3_status(job_id: str, request: Request):
|
||||
_get_user(request)
|
||||
job = batch_v3.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(404, "Job not found")
|
||||
user = _get_user(request)
|
||||
job = _require_job_owner(batch_v3.get_job(job_id), user)
|
||||
|
||||
# Fallback: check disk if SSE didn't deliver
|
||||
if job["status"] == "uploaded" and job.get("job_dir"):
|
||||
@@ -1622,9 +1637,9 @@ async def batch_v3_status(job_id: str, request: Request):
|
||||
|
||||
@app.get("/api/batch-v3/download/{job_id}")
|
||||
async def batch_v3_download(job_id: str, request: Request):
|
||||
_get_user(request)
|
||||
job = batch_v3.get_job(job_id)
|
||||
if not job or not job.get("output_file"):
|
||||
user = _get_user(request)
|
||||
job = _require_job_owner(batch_v3.get_job(job_id), user)
|
||||
if not job.get("output_file"):
|
||||
raise HTTPException(404, "Result not ready")
|
||||
return FileResponse(job["output_file"], filename=Path(job["output_file"]).name)
|
||||
|
||||
@@ -1746,19 +1761,15 @@ async def ssr_upload(request: Request):
|
||||
|
||||
@app.get("/api/ssr/preview/{job_id}")
|
||||
async def ssr_preview(job_id: str, request: Request):
|
||||
_get_user(request)
|
||||
job = _ssr_jobs.get(job_id)
|
||||
if not job:
|
||||
raise HTTPException(404, "Job not found")
|
||||
user = _get_user(request)
|
||||
job = _require_job_owner(_ssr_jobs.get(job_id), user)
|
||||
return HTMLResponse(Path(job["html_path"]).read_text(encoding="utf-8"))
|
||||
|
||||
|
||||
@app.get("/api/ssr/download/{job_id}")
|
||||
async def ssr_download(job_id: str, request: Request):
|
||||
_get_user(request)
|
||||
job = _ssr_jobs.get(job_id)
|
||||
if not job:
|
||||
raise HTTPException(404, "Job not found")
|
||||
user = _get_user(request)
|
||||
job = _require_job_owner(_ssr_jobs.get(job_id), user)
|
||||
return FileResponse(job["xlsx_path"], filename="ssr_generated.xlsx")
|
||||
|
||||
|
||||
@@ -1815,6 +1826,7 @@ async def check_yaml_endpoint(request: Request):
|
||||
import tempfile
|
||||
from smeta_railway.ai.checker import check_yaml_config, format_report
|
||||
|
||||
_get_user(request) # закрыт от анонима (был публичный compute-эндпоинт)
|
||||
body = await request.json()
|
||||
yaml_content = body.get("yaml", "")
|
||||
if not yaml_content.strip():
|
||||
@@ -1838,7 +1850,8 @@ async def check_yaml_endpoint(request: Request):
|
||||
"formatted": format_report(report),
|
||||
}
|
||||
except Exception as exc:
|
||||
return {"error": str(exc), "results": []}
|
||||
logger.exception("check_yaml failed") # детали — в лог оператору, не клиенту
|
||||
return {"error": "Не удалось проверить конфигурацию", "results": []}
|
||||
finally:
|
||||
Path(tmp_path).unlink(missing_ok=True)
|
||||
|
||||
@@ -1920,13 +1933,15 @@ async def calculate_estimate(request: Request):
|
||||
|
||||
|
||||
@app.get("/api/gen/download/{job_id}")
|
||||
async def download_estimate(job_id: str):
|
||||
async def download_estimate(job_id: str, request: Request):
|
||||
"""Download generated Excel estimate."""
|
||||
_get_user(request) # был публичный доступ к файлам по угадываемому id
|
||||
safe_id = Path(job_id).name # без traversal в имени файла
|
||||
data_dir = Path(os.environ.get("DATA_DIR", "./smeta-web-data")) / "_estimates"
|
||||
xlsx_path = data_dir / f"estimate_{job_id}.xlsx"
|
||||
xlsx_path = data_dir / f"estimate_{safe_id}.xlsx"
|
||||
if not xlsx_path.exists():
|
||||
raise HTTPException(404, "Файл не найден")
|
||||
return FileResponse(str(xlsx_path), filename=f"smeta_{job_id}.xlsx")
|
||||
return FileResponse(str(xlsx_path), filename=f"smeta_{safe_id}.xlsx")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
"""Единая защита work_dir от path-traversal.
|
||||
|
||||
username(email) и tab_id ОБА приходят от клиента (заголовок x-tab-id / path-param).
|
||||
Раньше get_work_dir в мостах клеил DATA_DIR/username/tab_id без проверки → заголовок
|
||||
`x-tab-id: ../..` читал (GET /api/files) и УДАЛЯЛ (POST /api/clear-files, rmtree)
|
||||
файлы вне папки пользователя. tus (`_safe_tab`) и admin-download уже защищены
|
||||
точечно — здесь единая точка для остального (Fable audit 2026-07-18).
|
||||
|
||||
Принцип: НЕ переписываем символы (иначе путь разойдётся с уже созданными каталогами
|
||||
существующих юзеров и их файлы «исчезнут») — а проверяем, что итог лежит СТРОГО внутри
|
||||
каталога данного пользователя. Легальные значения (email без '/', tab_id=UUID)
|
||||
проходят байт-в-байт; traversal и выход в чужую папку → UnsafePath (ValueError).
|
||||
"""
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
class UnsafePath(ValueError):
|
||||
"""Попытка выйти за пределы каталога пользователя (traversal / чужая папка)."""
|
||||
|
||||
|
||||
def _data_root() -> Path:
|
||||
return Path(os.environ.get("DATA_DIR", "./smeta-web-data")).resolve()
|
||||
|
||||
|
||||
def safe_work_dir(username: str, tab_id: str, *, create: bool = True) -> Path:
|
||||
"""DATA_DIR/username/tab_id с гарантией, что путь не вышел из папки пользователя."""
|
||||
root = _data_root()
|
||||
username = (username or "").strip()
|
||||
tab_id = (tab_id or "").strip() or "default"
|
||||
user_dir = (root / username).resolve()
|
||||
if user_dir.parent != root: # username содержит '/' или '..'
|
||||
raise UnsafePath("bad username component")
|
||||
d = (user_dir / tab_id).resolve()
|
||||
if d != user_dir and user_dir not in d.parents: # tab_id вышел из папки юзера
|
||||
raise UnsafePath("bad tab_id component")
|
||||
if create:
|
||||
d.mkdir(parents=True, exist_ok=True)
|
||||
return d
|
||||
@@ -0,0 +1,99 @@
|
||||
"""Block ① безопасности (Fable audit 2026-07-18): path-traversal через x-tab-id,
|
||||
анонимные compute/download-эндпоинты, владелец job'а.
|
||||
|
||||
Mutation-честность:
|
||||
- убери guard в get_work_dir → traversal-тесты пройдут МИМО (файл-часовой удалён / прочитан).
|
||||
- верни `_get_user` без ownership → foreign-job тест перестанет давать 404.
|
||||
"""
|
||||
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)
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def env(tmp_path, monkeypatch):
|
||||
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 auth, claude_bridge, db, main, path_safety
|
||||
for m in (path_safety, db, auth, claude_bridge, main):
|
||||
importlib.reload(m)
|
||||
db.init_db()
|
||||
from fastapi.testclient import TestClient
|
||||
return auth, main, TestClient(main.app), tmp_path
|
||||
|
||||
|
||||
def _h(auth, user="mallory@x", role="user", tab="tab-1"):
|
||||
return {"Authorization": "Bearer " + auth._make_token(user, role), "X-Tab-Id": tab}
|
||||
|
||||
|
||||
# ---- path traversal через заголовок вкладки ----
|
||||
|
||||
def test_traversal_read_blocked(env):
|
||||
auth, main, client, tmp = env
|
||||
h = _h(auth, tab="../../../../etc")
|
||||
r = client.get("/api/files/passwd", headers=h)
|
||||
assert r.status_code == 400 # UnsafePath → чистый 400, не 200 с /etc/passwd
|
||||
|
||||
|
||||
def test_traversal_delete_does_not_wipe_outside(env):
|
||||
auth, main, client, tmp = env
|
||||
sentinel = tmp / "sentinel.txt" # лежит ВЫШЕ DATA_DIR (tmp/data)
|
||||
sentinel.write_text("keep me")
|
||||
r = client.post("/api/clear-files", headers=_h(auth, tab="../.."))
|
||||
assert r.status_code == 400
|
||||
assert sentinel.exists() # без guard clear-files снёс бы этот файл
|
||||
|
||||
|
||||
def test_legit_tab_still_works(env):
|
||||
auth, main, client, tmp = env
|
||||
# обычный tab_id (не traversal) — 200 и пустой список, не 400
|
||||
r = client.get("/api/files", headers=_h(auth, tab="normal-uuid-1234"))
|
||||
assert r.status_code == 200
|
||||
assert r.json() == []
|
||||
|
||||
|
||||
# ---- анонимные эндпоинты закрыты ----
|
||||
|
||||
def test_gen_download_requires_auth(env):
|
||||
_auth, _main, client, _tmp = env
|
||||
r = client.get("/api/gen/download/anything") # без Authorization
|
||||
assert r.status_code == 401
|
||||
|
||||
|
||||
def test_check_yaml_requires_auth(env):
|
||||
_auth, _main, client, _tmp = env
|
||||
r = client.post("/api/check/yaml", json={"yaml": "x: 1"})
|
||||
assert r.status_code == 401
|
||||
|
||||
|
||||
# ---- владелец job'а ----
|
||||
|
||||
def test_require_job_owner_helper(env):
|
||||
_auth, main, _client, _tmp = env
|
||||
from fastapi import HTTPException
|
||||
assert main._require_job_owner({"user": "a@x"}, "a@x")["user"] == "a@x"
|
||||
with pytest.raises(HTTPException):
|
||||
main._require_job_owner({"user": "a@x"}, "b@x") # чужой → 404
|
||||
with pytest.raises(HTTPException):
|
||||
main._require_job_owner(None, "a@x") # нет job → 404
|
||||
|
||||
|
||||
def test_batch_v3_status_foreign_is_404(env):
|
||||
_auth, main, client, _tmp = env
|
||||
auth = _auth
|
||||
# заводим job вручную от имени owner@x, спрашиваем от mallory@x
|
||||
import batch_v3
|
||||
job = batch_v3.create_job("deadbeef")
|
||||
job["user"] = "owner@x"
|
||||
job["job_dir"] = "/tmp/nope"
|
||||
r = client.get("/api/batch-v3/status/deadbeef", headers=_h(auth, user="mallory@x"))
|
||||
assert r.status_code == 404
|
||||
@@ -0,0 +1,66 @@
|
||||
"""Path-traversal guard для work_dir (Fable audit 2026-07-18, P0 #1).
|
||||
|
||||
Легальные значения (email, tab_id=UUID) проходят байт-в-байт — иначе файлы
|
||||
существующих юзеров «исчезнут». Traversal и выход в чужую папку → UnsafePath.
|
||||
Mutation-честность: уберёшь containment-проверку → traversal-тесты станут зелёными
|
||||
на пути ВНЕ папки, то есть эти тесты реально падают без защиты.
|
||||
"""
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def _root(monkeypatch, tmp_path):
|
||||
monkeypatch.setenv("DATA_DIR", str(tmp_path))
|
||||
import importlib
|
||||
import path_safety as ps
|
||||
importlib.reload(ps)
|
||||
return ps, tmp_path.resolve()
|
||||
|
||||
|
||||
def test_legit_path_unchanged_and_created(_root):
|
||||
ps, root = _root
|
||||
d = ps.safe_work_dir("user@example.com", "550e8400-e29b-41d4-a716-446655440000")
|
||||
assert d == root / "user@example.com" / "550e8400-e29b-41d4-a716-446655440000"
|
||||
assert d.is_dir() # create=True
|
||||
|
||||
|
||||
def test_email_with_plus_preserved(_root):
|
||||
ps, root = _root
|
||||
d = ps.safe_work_dir("user+tag@x.com", "tab1", create=False)
|
||||
assert d == root / "user+tag@x.com" / "tab1" # символы НЕ переписаны
|
||||
|
||||
|
||||
def test_traversal_tab_id_rejected(_root):
|
||||
ps, _ = _root
|
||||
with pytest.raises(ps.UnsafePath):
|
||||
ps.safe_work_dir("user@x.com", "../..")
|
||||
|
||||
|
||||
def test_cross_user_tab_id_rejected(_root):
|
||||
ps, _ = _root
|
||||
with pytest.raises(ps.UnsafePath):
|
||||
ps.safe_work_dir("user@x.com", "../victim@x.com/tab")
|
||||
|
||||
|
||||
def test_absolute_tab_id_rejected(_root):
|
||||
ps, _ = _root
|
||||
with pytest.raises(ps.UnsafePath):
|
||||
ps.safe_work_dir("user@x.com", "/etc")
|
||||
|
||||
|
||||
def test_traversal_username_rejected(_root):
|
||||
ps, _ = _root
|
||||
with pytest.raises(ps.UnsafePath):
|
||||
ps.safe_work_dir("../../../etc", "passwd")
|
||||
|
||||
|
||||
def test_nested_tab_stays_inside_user(_root):
|
||||
"""tab_id с одиночным '/' (без '..') остаётся внутри папки юзера — не reject."""
|
||||
ps, root = _root
|
||||
d = ps.safe_work_dir("user@x.com", "sub/inner", create=False)
|
||||
assert root / "user@x.com" in d.parents # всё ещё под своим каталогом
|
||||
Reference in New Issue
Block a user