From 410a8a7568004c9a0c4cfa6a95794be48ffb8133 Mon Sep 17 00:00:00 2001 From: Leo Vasanko Date: Sat, 25 Apr 2026 17:26:08 +0000 Subject: [PATCH 1/6] Replace WebSocket control API with REST file operations - Add cista/fileserver.py: REST blueprint at /files with PUT upload, DELETE, MKCOL, POST cp/mv (combined), GET/HEAD static serving - Remove WS control handler and all ControlBase/Cmd protocol types - Frontend: SelectionToolbar, FileExplorer, Gallery now POST to /files instead of opening a control WebSocket per operation - Remove controlUrl export from WS.ts - Add tests: REST API, static streaming, path/escaping security - Catch ValueError from filename.sanitize and return 400 Bad Request --- cista/api.py | 14 +- cista/app.py | 140 ++----- cista/fileserver.py | 415 +++++++++++++++++++ cista/preview.py | 8 +- cista/protocol.py | 115 ----- cista/sanic_logging.py | 33 +- frontend/src/components/FileExplorer.vue | 105 ++--- frontend/src/components/Gallery.vue | 105 ++--- frontend/src/components/SelectionToolbar.vue | 68 +-- frontend/src/repositories/WS.ts | 1 - pyproject.toml | 1 + tests/test_control.py | 53 --- tests/test_files_path_security.py | 169 ++++++++ tests/test_files_rest_api.py | 234 +++++++++++ tests/test_files_static_streaming.py | 100 +++++ 15 files changed, 1098 insertions(+), 463 deletions(-) create mode 100644 cista/fileserver.py delete mode 100644 tests/test_control.py create mode 100644 tests/test_files_path_security.py create mode 100644 tests/test_files_rest_api.py create mode 100644 tests/test_files_static_streaming.py diff --git a/cista/api.py b/cista/api.py index aa764b9..ec74d95 100644 --- a/cista/api.py +++ b/cista/api.py @@ -8,8 +8,7 @@ from sanic.exceptions import BadRequest from cista import __version__, auth, config, sso, watching from cista.fileio import FileServer -from cista.protocol import ControlTypes, StatusMsg -from cista.util.apphelpers import asend, websocket_wrapper +from cista.util.apphelpers import websocket_wrapper bp = Blueprint("api", url_prefix="/api") fileserver = FileServer() @@ -25,17 +24,6 @@ async def stop_fileserver(app): await fileserver.stop() -@bp.websocket("control") -@websocket_wrapper -async def control(req, ws): - while True: - cmd = msgspec.json.decode(await ws.recv(), type=ControlTypes) - await asyncio.to_thread(cmd) - # Signal the watcher about affected paths - watching.notify_change(*cmd.affected_paths()) - await asend(ws, StatusMsg(status="ack", req=cmd)) - - @bp.websocket("watch") @websocket_wrapper async def watch(req, ws): diff --git a/cista/app.py b/cista/app.py index 3c64b13..08c04f0 100644 --- a/cista/app.py +++ b/cista/app.py @@ -1,19 +1,16 @@ import asyncio import datetime import mimetypes -import re import time from concurrent.futures import ThreadPoolExecutor -from multiprocessing import cpu_count from pathlib import Path, PurePath, PurePosixPath from stat import S_IFDIR, S_IFREG from urllib.parse import unquote from wsgiref.handlers import format_date_time -import sanic.helpers from blake3 import blake3 -from sanic import Blueprint, Sanic, empty, json, raw, redirect -from sanic.exceptions import BadRequest, Forbidden, NotFound +from sanic import Sanic, empty, raw, redirect +from sanic.exceptions import Forbidden, NotFound from sanic.log import logger from setproctitle import setproctitle from stream_zip import ZIP_AUTO, stream_zip @@ -21,17 +18,30 @@ from zstandard import ZstdCompressor from cista import auth, config, preview, session, sso, watching from cista.preview import shutdown_preview_workers, start_preview_workers -from cista.api import bp, fileserver -from cista.sanic_logging import configure_access_logging, configure_main_logging, format_access_log +from cista.api import bp +from cista import fileserver +from cista.sanic_logging import ( + configure_access_logging, + configure_main_logging, + format_access_log, +) from cista.sanic_logging import logger as access_logger from cista.util.apphelpers import handle_sanic_exception -# Workaround until Sanic PR #2824 is merged -sanic.helpers._ENTITY_HEADERS = frozenset() - configure_access_logging() app = Sanic("cista", strict_slashes=True) +app.router.ALLOWED_METHODS = ( + *app.router.ALLOWED_METHODS, + "MKCOL", + "MOVE", + "COPY", + "PROPFIND", + "PROPPATCH", + "LOCK", + "UNLOCK", +) + configure_main_logging() # Register either SSO proxy or built-in auth routes based on PASKIA_BACKEND_URL if sso.paskia_enabled(): @@ -40,6 +50,7 @@ else: app.blueprint(auth.bp) # Built-in auth routes app.blueprint(preview.bp) app.blueprint(bp) +app.blueprint(fileserver.bp) app.exception(Exception)(handle_sanic_exception) @@ -106,7 +117,9 @@ async def log_access(req, res): qs = qs.decode(errors="replace") path = f"{path}?{qs}" extra = getattr(req.ctx, "_log_extra", None) - line = format_access_log(client, res.status, req.method, host, path, duration_ms, extra=extra) + line = format_access_log( + client, res.status, req.method, host, path, duration_ms, extra=extra + ) access_logger.info(line) return res @@ -119,112 +132,7 @@ async def forward_sso_cookies(req, res): res.headers.add("set-cookie", cookie) -@app.before_server_start -def http_fileserver(app): - bp = Blueprint("fileserver") - - @bp.on_request - async def verify_fileserver(request): - """Verify access to file server routes.""" - await auth.verify(request) - - @bp.put("/files/") - async def upload_file_chunk(request, *args, **kwargs): - body = request.body - header = request.headers.get("content-range") - if header: - start, end, total = _parse_content_range(header, len(body)) - else: - start = 0 - end = len(body) - total = end - raw_name = kwargs.get("name") - if raw_name is None and args: - raw_name = args[0] - if not isinstance(raw_name, str) or not raw_name: - prefix = "/files/" - if not request.path.startswith(prefix): - raise BadRequest("Invalid upload path") - raw_name = request.path[len(prefix) :] - rel_name = unquote(raw_name) - upload_info = await asyncio.to_thread( - fileserver.upload_info, - rel_name, - start, - body, - total, - ) - extras = [] - chunk_len = end - start - whole_file = start == 0 and end == total - if not whole_file: - start_mib = _to_mib_int(start) - chunk_mib = _to_mib_int(chunk_len) - # Keep range logs compact for fixed-size upload blocks. - if chunk_mib == 16: - extras.append(f"{start_mib}MiB") - else: - extras.append(f"{start_mib}+{chunk_mib}MiB") - if upload_info.get("created"): - extras.append(f"created {_to_mib_int(total)}MiB") - size_before = upload_info.get("size_before") - size_after = upload_info.get("size_after") - if ( - size_before is not None - and size_after is not None - and size_before != size_after - ): - extras.append("resized") - request.ctx._log_extra = " ".join(extras) if extras else None - path = PurePosixPath(rel_name) - watching.notify_change(path, *path.parents) - return json( - { - "status": "ack", - "req": { - "name": rel_name, - "size": total, - "start": start, - "end": end, - }, - } - ) - - bp.static( - "/files/", - config.config.path, - use_content_range=True, - stream_large_files=True, - directory_view=True, - ) - app.blueprint(bp) - - www = {} -_CONTENT_RANGE_RE = re.compile(r"^bytes (\d+)-(\d+)/(\d+)$") - - -def _parse_content_range(header: str, body_len: int) -> tuple[int, int, int]: - m = _CONTENT_RANGE_RE.fullmatch(header.strip()) - if m is None: - raise BadRequest("Invalid Content-Range format") - start, end_inclusive, total = (int(v) for v in m.groups()) - if total <= 0: - raise BadRequest("Invalid Content-Range total size") - if start > end_inclusive: - raise BadRequest("Invalid Content-Range range") - if end_inclusive >= total: - raise BadRequest("Content-Range exceeds total size") - expected_len = end_inclusive - start + 1 - if expected_len != body_len: - raise BadRequest( - f"Content length mismatch for range: expected {expected_len}, got {body_len}" - ) - return start, end_inclusive + 1, total - - -def _to_mib_int(value_bytes: int) -> int: - return round(value_bytes / (1 << 20)) def _load_wwwroot(www): diff --git a/cista/fileserver.py b/cista/fileserver.py new file mode 100644 index 0000000..931e108 --- /dev/null +++ b/cista/fileserver.py @@ -0,0 +1,415 @@ +import asyncio +import mimetypes +import os +import re +import shutil +from pathlib import Path, PurePosixPath +from urllib.parse import unquote +from wsgiref.handlers import format_date_time + +from sanic import Blueprint, empty, json +from sanic.exceptions import BadRequest, NotFound + +from cista import auth, config, watching +from cista.api import fileserver +from cista.util import filename + +bp = Blueprint("fileserver", url_prefix="/files") + +_CONTENT_RANGE_RE = re.compile(r"^bytes (\d+)-(\d+)/(\d+)$") +_RANGE_RE = re.compile(r"^bytes=(\d*)-(\d*)$") +_FILE_CHUNK_SIZE = 1 << 20 + + +@bp.on_request +async def verify_fileserver(request): + """Verify access to file server routes.""" + await auth.verify(request) + + +@bp.put("/") +async def upload_file_chunk(request, name): + body = request.body + header = request.headers.get("content-range") + if header: + start, end, total = _parse_content_range(header, len(body)) + else: + start = 0 + end = len(body) + total = end + + rel, _ = _safe_relpath(name) + rel_name = rel.as_posix() + upload_info = await asyncio.to_thread( + fileserver.upload_info, + rel_name, + start, + body, + total, + ) + extras = [] + chunk_len = end - start + whole_file = start == 0 and end == total + if not whole_file: + start_mib = _to_mib_int(start) + chunk_mib = _to_mib_int(chunk_len) + # Keep range logs compact for fixed-size upload blocks. + if chunk_mib == 16: + extras.append(f"{start_mib}MiB") + else: + extras.append(f"{start_mib}+{chunk_mib}MiB") + if upload_info.get("created"): + extras.append(f"created {_to_mib_int(total)}MiB") + size_before = upload_info.get("size_before") + size_after = upload_info.get("size_after") + if size_before is not None and size_after is not None and size_before != size_after: + extras.append("resized") + request.ctx._log_extra = " ".join(extras) if extras else None + watching.notify_change(rel, *rel.parents) + return json( + { + "status": "ack", + "req": { + "name": rel_name, + "size": total, + "start": start, + "end": end, + }, + } + ) + + +@bp.delete("/") +async def delete_file(request, name): + rel, path = _safe_relpath(name) + if not rel.parts: + raise BadRequest("Refusing to delete root folder") + + def _delete(): + if not path.exists(): + raise NotFound(f"File not found: {name}") + if path.is_dir(): + shutil.rmtree(path) + else: + path.unlink() + + await asyncio.to_thread(_delete) + watching.notify_change(rel, *rel.parents) + return empty(status=204) + + +@bp.route("/", methods=["MKCOL"]) +async def create_folder(request, name): + rel, path = _safe_relpath(name) + if not rel.parts: + raise BadRequest("Refusing to create root folder") + await asyncio.to_thread(path.mkdir, parents=True, exist_ok=False) + watching.notify_change(rel, *rel.parents) + return empty(status=201) + + +@bp.post("/") +async def copy_or_move(request, name=""): + provided_args = set(request.args.keys()) + if not provided_args: + raise BadRequest("No query arguments passed") + + allowed_args = {"cp", "mv"} + unknown_args = sorted(provided_args - allowed_args) + if unknown_args: + raise BadRequest(f"Unknown query parameter(s): {', '.join(unknown_args)}") + + mv_vals = request.args.getlist("mv") + cp_vals = request.args.getlist("cp") + + mv_keys: list[str] = [] + for value in mv_vals: + mv_keys.extend(k for k in value.split() if k) + + cp_keys: list[str] = [] + for value in cp_vals: + cp_keys.extend(k for k in value.split() if k) + + if not mv_keys and not cp_keys: + raise BadRequest("No keys given") + + dst_rel, dst_abs = _safe_relpath(name) + + dst_exists = dst_abs.exists() + dst_is_dir = dst_exists and dst_abs.is_dir() + + ordered_keys = cp_keys + mv_keys + key_paths = _get_key_paths(set(ordered_keys)) + missing = [key for key in ordered_keys if key not in key_paths] + if missing: + raise NotFound("Files not found", context={"missing": missing}) + + # Validate target shape/type before mutating anything. + for op_name, op_keys in (("cp", cp_keys), ("mv", mv_keys)): + if len(op_keys) > 1 and not dst_is_dir: + raise BadRequest("Destination must be an existing directory for multiple keys") + if not op_keys: + continue + if not dst_is_dir: + if not dst_rel.parts: + raise BadRequest("Destination file path is required") + parent_abs = dst_abs.parent + if not parent_abs.is_dir(): + raise BadRequest("Destination parent folder does not exist") + if dst_exists and dst_abs.is_file(): + for key in op_keys: + src_abs = _resolve_from_relpath(key_paths[key]) + if src_abs.is_dir(): + raise BadRequest("Cannot move/copy a directory to an existing file") + + changed: set[PurePosixPath] = set() + completed: list[dict[str, str]] = [] + + class _FileOpFailed(Exception): + def __init__(self, op_name: str, key: str, error: Exception): + self.op_name = op_name + self.key = key + self.error = error + super().__init__(str(error)) + + def _apply(): + for op_name, op_keys in (("cp", cp_keys), ("mv", mv_keys)): + op_multi = len(op_keys) > 1 + for key in op_keys: + try: + src_rel = key_paths[key] + src_abs = _resolve_from_relpath(src_rel) + + if op_multi: + if not dst_is_dir: + raise BadRequest( + "Destination must be an existing directory for multiple keys" + ) + dst_item_rel = ( + dst_rel / src_rel.name if dst_rel.parts else PurePosixPath(src_rel.name) + ) + elif dst_is_dir: + dst_item_rel = ( + dst_rel / src_rel.name if dst_rel.parts else PurePosixPath(src_rel.name) + ) + else: + if not dst_rel.parts: + raise BadRequest("Destination file path is required") + parent_abs = dst_abs.parent + if not parent_abs.is_dir(): + raise BadRequest("Destination parent folder does not exist") + if src_abs.is_dir() and dst_exists and dst_abs.is_file(): + raise BadRequest( + "Cannot move/copy a directory to an existing file" + ) + dst_item_rel = dst_rel + + dst_item_abs = _resolve_from_relpath(dst_item_rel) + + if op_name == "mv": + # A no-op rename should still return success. + if src_abs != dst_item_abs: + shutil.move(src_abs, dst_item_abs) + changed.add(src_rel) + changed.add(src_rel.parent) + elif src_abs.is_dir(): + shutil.copytree( + src_abs, + dst_item_abs, + dirs_exist_ok=True, + ignore_dangling_symlinks=True, + ) + else: + shutil.copy2(src_abs, dst_item_abs) + + changed.add(dst_item_rel) + changed.add(dst_item_rel.parent) + completed.append({"op": op_name, "key": key}) + except Exception as e: + raise _FileOpFailed(op_name, key, e) from e + + try: + await asyncio.to_thread(_apply) + except _FileOpFailed as e: + raise BadRequest( + "File operation failed after partial progress", + context={ + "failed_op": e.op_name, + "failed_key": e.key, + "error": str(e.error), + "completed": completed, + }, + ) from e + + notify_paths = [p for p in changed if p.parts] + if notify_paths: + watching.notify_change(*notify_paths) + + return json( + { + "status": "ack", + "counts": {"cp": len(cp_keys), "mv": len(mv_keys)}, + } + ) + + +@bp.get("/") +async def get_file(request, name=""): + return await _send_static_file(request, name, head_only=False) + + +@bp.head("/") +async def head_file(request, name=""): + return await _send_static_file(request, name, head_only=True) + + +def _parse_content_range(header: str, body_len: int) -> tuple[int, int, int]: + m = _CONTENT_RANGE_RE.fullmatch(header.strip()) + if m is None: + raise BadRequest("Invalid Content-Range format") + start, end_inclusive, total = (int(v) for v in m.groups()) + if total <= 0: + raise BadRequest("Invalid Content-Range total size") + if start > end_inclusive: + raise BadRequest("Invalid Content-Range range") + if end_inclusive >= total: + raise BadRequest("Content-Range exceeds total size") + expected_len = end_inclusive - start + 1 + if expected_len != body_len: + raise BadRequest( + f"Content length mismatch for range: expected {expected_len}, got {body_len}" + ) + return start, end_inclusive + 1, total + + +def _to_mib_int(value_bytes: int) -> int: + return round(value_bytes / (1 << 20)) + + +def _safe_relpath(path: str) -> tuple[PurePosixPath, Path]: + """Resolve a user path under storage root and enforce containment.""" + base = config.config.path.resolve() + try: + sanitized = filename.sanitize(unquote(path)) + except ValueError as e: + raise BadRequest(f"Invalid path: {e}") from e + resolved = (base / sanitized).resolve() + if not resolved.is_relative_to(base): + raise BadRequest("Invalid path") + rel = PurePosixPath(resolved.relative_to(base).as_posix()) + return rel, resolved + + +def _resolve_from_relpath(rel: PurePosixPath) -> Path: + """Resolve a relative path under storage root and enforce containment.""" + base = config.config.path.resolve() + resolved = (base / rel).resolve() + if not resolved.is_relative_to(base): + raise BadRequest("Invalid path") + return resolved + + +async def _send_static_file(request, name: str, *, head_only: bool): + _, path = _safe_relpath(name) + + st = await asyncio.to_thread(path.stat) + if path.is_dir(): + raise NotFound(f"Not a file: {name}") + + size = st.st_size + start = 0 + end_excl = size + status = 200 + + range_header = request.headers.get("range") + if range_header is not None: + parsed = _parse_range_header(range_header, size) + if parsed is None: + return empty( + status=416, + headers={ + "accept-ranges": "bytes", + "content-range": f"bytes */{size}", + }, + ) + start, end_excl = parsed + status = 206 + + length = end_excl - start + mime = mimetypes.guess_type(path.name)[0] or "application/octet-stream" + headers = { + "accept-ranges": "bytes", + "cache-control": "no-cache", + "content-length": str(length), + "content-type": mime, + "last-modified": format_date_time(st.st_mtime), + } + if status == 206: + headers["content-range"] = f"bytes {start}-{end_excl - 1}/{size}" + + if head_only: + return empty(status=status, headers=headers) + + res = await request.respond(status=status, headers=headers) + fd = await asyncio.to_thread(os.open, path, os.O_RDONLY) + try: + pos = start + while pos < end_excl: + chunk = await asyncio.to_thread( + os.pread, + fd, + min(_FILE_CHUNK_SIZE, end_excl - pos), + pos, + ) + if not chunk: + break + pos += len(chunk) + await res.send(chunk) + finally: + await asyncio.to_thread(os.close, fd) + + +def _parse_range_header(header: str, size: int) -> tuple[int, int] | None: + value = header.strip() + if "," in value: + return None + m = _RANGE_RE.fullmatch(value) + if m is None: + return None + + start_s, end_s = m.groups() + if not start_s and not end_s: + return None + + if start_s: + start = int(start_s) + if start >= size: + return None + end_inclusive = int(end_s) if end_s else (size - 1) + if end_inclusive < start: + return None + end_inclusive = min(end_inclusive, size - 1) + return start, end_inclusive + 1 + + suffix_len = int(end_s) + if suffix_len <= 0: + return None + if suffix_len >= size: + return 0, size + start = size - suffix_len + return start, size + + +def _get_key_paths(wanted: set[str]) -> dict[str, PurePosixPath]: + """Map file keys to their current relative filesystem paths.""" + loc = PurePosixPath() + ret: dict[str, PurePosixPath] = {} + with watching.state.lock: + root = watching.state.root + for f in root: + loc = PurePosixPath(*loc.parts[: f.level - 1]) / f.name + if f.key in wanted and f.key not in ret: + ret[f.key] = loc + if len(ret) == len(wanted): + break + return ret diff --git a/cista/preview.py b/cista/preview.py index d586440..1b74963 100644 --- a/cista/preview.py +++ b/cista/preview.py @@ -221,9 +221,7 @@ class _PreviewWorkerPool: logger.warning( "Preview worker protocol failure for %s: %s", filepath.name, e ) - raise PreviewError( - f"worker protocol failure for {filepath.name}: {e}" - ) + raise PreviewError(f"worker protocol failure for {filepath.name}: {e}") finally: if replace: await self._replace_worker(worker) @@ -470,9 +468,7 @@ def process_pdf(path, *, maxsize, maxzoom, quality, page_number=0): img = pyvips.Image.new_from_memory( pix.samples_mv, pix.width, pix.height, pix.n, "uchar" ) - ret = img.write_to_buffer( - ".avif", Q=quality, effort=AVIF_FAST_EFFORT, strip=True - ) + ret = img.write_to_buffer(".avif", Q=quality, effort=AVIF_FAST_EFFORT, strip=True) backend = "pdf+pyvips" t_save_end = perf_counter() diff --git a/cista/protocol.py b/cista/protocol.py index 220e887..18b3391 100644 --- a/cista/protocol.py +++ b/cista/protocol.py @@ -1,125 +1,10 @@ from __future__ import annotations -import shutil -from pathlib import PurePosixPath from typing import Any import msgspec -from sanic import BadRequest from cista import config -from cista.util import filename - -## Control commands - -class ControlBase(msgspec.Struct, tag_field="op", tag=str.lower): - def __call__(self): - raise NotImplementedError - - def affected_paths(self) -> list[str]: - """Return list of paths affected by this operation for change notification.""" - return [] - - -class MkDir(ControlBase): - path: str - - def __call__(self): - path = config.config.path / filename.sanitize(self.path) - path.mkdir(parents=True, exist_ok=False) - - def affected_paths(self) -> list[str]: - return [filename.sanitize(self.path)] - - -class Rename(ControlBase): - path: str - to: str - - def __call__(self): - to = filename.sanitize(self.to) - if "/" in to: - raise BadRequest("Rename 'to' name should only contain filename, not path") - path = config.config.path / filename.sanitize(self.path) - path.rename(path.with_name(to)) - - def affected_paths(self) -> list[str]: - sanitized = filename.sanitize(self.path) - new_path = str(PurePosixPath(sanitized).with_name(filename.sanitize(self.to))) - return [sanitized, new_path] - - -class Rm(ControlBase): - sel: list[str] - - def __call__(self): - root = config.config.path - sel = [root / filename.sanitize(p) for p in self.sel] - for p in sel: - if p.is_dir(): - shutil.rmtree(p) - else: - p.unlink() - - def affected_paths(self) -> list[str]: - return [filename.sanitize(p) for p in self.sel] - - -class Mv(ControlBase): - sel: list[str] - dst: str - - def __call__(self): - root = config.config.path - sel = [root / filename.sanitize(p) for p in self.sel] - dst = root / filename.sanitize(self.dst) - if not dst.is_dir(): - raise BadRequest("The destination must be a directory") - for p in sel: - shutil.move(p, dst) - - def affected_paths(self) -> list[str]: - dst = filename.sanitize(self.dst) - paths = [filename.sanitize(p) for p in self.sel] - # Include new locations in dst - paths.extend(f"{dst}/{PurePosixPath(p).name}" for p in self.sel) - return paths - - -class Cp(ControlBase): - sel: list[str] - dst: str - - def __call__(self): - root = config.config.path - sel = [root / filename.sanitize(p) for p in self.sel] - dst = root / filename.sanitize(self.dst) - if not dst.is_dir(): - raise BadRequest("The destination must be a directory") - for p in sel: - if p.is_dir(): - # Note: copies as dst rather than in dst unless name is appended. - shutil.copytree( - p, - dst / p.name, - dirs_exist_ok=True, - ignore_dangling_symlinks=True, - ) - else: - shutil.copy2(p, dst) - - def affected_paths(self) -> list[str]: - dst = filename.sanitize(self.dst) - # Only destinations are new (sources unchanged) - return [f"{dst}/{PurePosixPath(filename.sanitize(p)).name}" for p in self.sel] - - -ControlTypes = MkDir | Rename | Rm | Mv | Cp - - -class StatusMsg(msgspec.Struct): - status: str - req: Any class ErrorMsg(msgspec.Struct): diff --git a/cista/sanic_logging.py b/cista/sanic_logging.py index 0325d4a..7283922 100644 --- a/cista/sanic_logging.py +++ b/cista/sanic_logging.py @@ -8,18 +8,18 @@ from ipaddress import IPv6Address logger = logging.getLogger("cista.access") _RESET = "\033[0m" -_STATUS_INFO = "\033[32m" # 1xx (green) -_STATUS_OK = "\033[1;92m" # 2xx (bright green) +_STATUS_INFO = "\033[32m" # 1xx (green) +_STATUS_OK = "\033[1;92m" # 2xx (bright green) _STATUS_REDIRECT = "\033[32m" # 3xx (green) -_STATUS_CLIENT_ERR = "\033[0;31m" # 4xx (red) -_STATUS_SERVER_ERR = "\033[1;91m" # 5xx (bold bright red) -_METHOD_READ = "\033[0;34m" # GET, HEAD, OPTIONS (blue) -_METHOD_WRITE = "\033[1;94m" # POST, PUT, DELETE, PATCH (bold bright blue) -_HOST = "\033[38;5;242m" # hostname (dark grey) -_PATH = "\033[38;5;250m" # path (light grey) -_TIMING = "\033[38;5;242m" # timing (dark grey) -_WS_OPEN = "\033[1;93m" # WebSocket connect (bold bright yellow) -_WS_CLOSE = "\033[33m" # WebSocket disconnect (yellow) +_STATUS_CLIENT_ERR = "\033[0;31m" # 4xx (red) +_STATUS_SERVER_ERR = "\033[1;91m" # 5xx (bold bright red) +_METHOD_READ = "\033[0;34m" # GET, HEAD, OPTIONS (blue) +_METHOD_WRITE = "\033[1;94m" # POST, PUT, DELETE, PATCH (bold bright blue) +_HOST = "\033[38;5;242m" # hostname (dark grey) +_PATH = "\033[38;5;250m" # path (light grey) +_TIMING = "\033[38;5;242m" # timing (dark grey) +_WS_OPEN = "\033[1;93m" # WebSocket connect (bold bright yellow) +_WS_CLOSE = "\033[33m" # WebSocket disconnect (yellow) _WS_STATUS = "\033[38;5;250m" # WebSocket close status (normal white) @@ -113,7 +113,12 @@ def _format_method_label(label: str, *, color: str | None = None) -> str: def format_access_log( - client: str, status: int, method: str, host: str, path: str, duration_ms: float, + client: str, + status: int, + method: str, + host: str, + path: str, + duration_ms: float, extra: str | None = None, ) -> str: ip = _format_left(format_client_ip(client)) @@ -123,7 +128,9 @@ def format_access_log( path_str = f"{_PATH}{path}{_RESET}" timing_str = f"{_TIMING}{format_duration_ms(duration_ms)}{_RESET}" extra_str = f" {_TIMING}{extra}{_RESET}" if extra else "" - return f"{ip} {status_str} {method_str} {host_str}{path_str}{extra_str} {timing_str}" + return ( + f"{ip} {status_str} {method_str} {host_str}{path_str}{extra_str} {timing_str}" + ) _ws_counter = 1 diff --git a/frontend/src/components/FileExplorer.vue b/frontend/src/components/FileExplorer.vue index 0060b91..d1c8113 100644 --- a/frontend/src/components/FileExplorer.vue +++ b/frontend/src/components/FileExplorer.vue @@ -76,7 +76,7 @@ import { ref, computed, watchEffect, shallowRef, onMounted, onUnmounted, nextTic import { useMainStore } from '@/stores/main' import { Doc } from '@/repositories/Document' import FileRenameInput from './FileRenameInput.vue' -import { connect, controlUrl } from '@/repositories/WS' +import { apiFetch } from '@/repositories/Client' import { formatSize } from '@/utils' import { useRouter } from 'vue-router' import ContextMenu from '@imengyu/vue3-context-menu' @@ -87,31 +87,36 @@ const props = defineProps<{ }>() const store = useMainStore() const router = useRouter() + +const filesUrl = (path: string) => + '/files/' + path.split('/').map(part => encodeURIComponent(part)).join('/') + +const parseErrorMessage = async (res: Response) => { + try { + const data = await res.json() + return data.message || data.detail || `${res.status} ${res.statusText}` + } catch { + return `${res.status} ${res.statusText}` + } +} + // File rename const editing = shallowRef(null) -const rename = (doc: Doc, newName: string) => { +const rename = async (doc: Doc, newName: string) => { const oldName = doc.name - const control = connect(controlUrl, { - message(ev: MessageEvent) { - const msg = JSON.parse(ev.data) - if ('error' in msg) { - console.error('Rename failed', msg.error.message, msg.error) - doc.name = oldName - } else { - console.log('Rename succeeded', msg) - } - } - }) - control.onopen = () => { - control.send( - JSON.stringify({ - op: 'rename', - path: `${doc.loc}/${oldName}`, - to: newName - }) - ) - } doc.name = newName // We should get an update from watch but this is quicker + try { + const dstUrl = doc.loc ? filesUrl(doc.loc) : '/files/' + const res = await apiFetch( + `${dstUrl}?mv=${doc.key}&to=${encodeURIComponent(newName)}`, + { method: 'POST' } + ) + if (!res.ok) throw new Error(await parseErrorMessage(res)) + } catch (err) { + console.error('Rename failed', err) + doc.name = oldName + store.showToast(err instanceof Error ? err.message : 'Rename failed') + } } defineExpose({ newFolder() { @@ -253,31 +258,20 @@ onMounted(() => { } }) onUnmounted(() => { clearInterval(modifiedTimer) }) -const mkdir = (doc: Doc, name: string) => { - const control = connect(controlUrl, { - open() { - control.send( - JSON.stringify({ - op: 'mkdir', - path: `${doc.loc}/${name}` - }) - ) - }, - message(ev: MessageEvent) { - const msg = JSON.parse(ev.data) - if ('error' in msg) { - console.error('Mkdir failed', msg.error.message, msg.error) - editing.value = null - } else { - console.log('mkdir', msg) - router.push(doc.urlrouter) - } - } - }) +const mkdir = async (doc: Doc, name: string) => { doc.name = name doc.key = crypto.randomUUID() store.addGhost(doc) editing.value = null + const path = doc.loc ? `${doc.loc}/${name}` : name + try { + const res = await apiFetch(filesUrl(path), { method: 'MKCOL' }) + if (!res.ok) throw new Error(await parseErrorMessage(res)) + router.push(doc.urlrouter) + } catch (err) { + console.error('Mkdir failed', err) + store.showToast(err instanceof Error ? err.message : 'Mkdir failed') + } } const showFolderBreadcrumb = (i: number) => { const docs = props.documents @@ -373,24 +367,17 @@ const copyImage = async (doc: Doc) => { } } -const deleteFile = (doc: Doc) => { +const deleteFile = async (doc: Doc) => { const path = doc.loc ? `${doc.loc}/${doc.name}` : doc.name store.hideDoc(path) - const control = connect(controlUrl, { - message(ev: MessageEvent) { - const res = JSON.parse(ev.data) - if ('error' in res) { - console.error('Delete failed', res.error) - store.unhideDoc(path) - store.showToast(res.error.message || 'Delete failed') - } else if (res.status === 'ack') { - store.showToast(`🗑️ Deleted ${doc.name}`) - control.close() - } - } - }) - control.onopen = () => { - control.send(JSON.stringify({ op: 'rm', sel: [path] })) + try { + const res = await apiFetch(filesUrl(path), { method: 'DELETE' }) + if (!res.ok) throw new Error(await parseErrorMessage(res)) + store.showToast(`🗑️ Deleted ${doc.name}`) + } catch (err) { + console.error('Delete failed', err) + store.unhideDoc(path) + store.showToast(err instanceof Error ? err.message : 'Delete failed') } } diff --git a/frontend/src/components/Gallery.vue b/frontend/src/components/Gallery.vue index f1ca5dc..8083b47 100644 --- a/frontend/src/components/Gallery.vue +++ b/frontend/src/components/Gallery.vue @@ -12,7 +12,7 @@ import { ref, computed, watchEffect, shallowRef, onMounted, onUnmounted, nextTick } from 'vue' import { useMainStore } from '@/stores/main' import { Doc } from '@/repositories/Document' -import { connect, controlUrl } from '@/repositories/WS' +import { apiFetch } from '@/repositories/Client' import { useRouter } from 'vue-router' import ContextMenu from '@imengyu/vue3-context-menu' import type { SortOrder } from '@/utils/docsort' @@ -23,32 +23,37 @@ const props = defineProps<{ }>() const store = useMainStore() const router = useRouter() + +const filesUrl = (path: string) => + '/files/' + path.split('/').map(part => encodeURIComponent(part)).join('/') + +const parseErrorMessage = async (res: Response) => { + try { + const data = await res.json() + return data.message || data.detail || `${res.status} ${res.statusText}` + } catch { + return `${res.status} ${res.statusText}` + } +} + // File rename const editing = shallowRef(null) const exit = () => { editing.value = null } -const rename = (doc: Doc, newName: string) => { +const rename = async (doc: Doc, newName: string) => { const oldName = doc.name - const control = connect(controlUrl, { - message(ev: MessageEvent) { - const msg = JSON.parse(ev.data) - if ('error' in msg) { - console.error('Rename failed', msg.error.message, msg.error) - doc.name = oldName - } else { - console.log('Rename succeeded', msg) - } - } - }) - control.onopen = () => { - control.send( - JSON.stringify({ - op: 'rename', - path: `${doc.loc}/${oldName}`, - to: newName - }) - ) - } doc.name = newName // We should get an update from watch but this is quicker + try { + const dstUrl = doc.loc ? filesUrl(doc.loc) : '/files/' + const res = await apiFetch( + `${dstUrl}?mv=${doc.key}&to=${encodeURIComponent(newName)}`, + { method: 'POST' } + ) + if (!res.ok) throw new Error(await parseErrorMessage(res)) + } catch (err) { + console.error('Rename failed', err) + doc.name = oldName + store.showToast(err instanceof Error ? err.message : 'Rename failed') + } } const gallery = ref() const columnCount = ref(1) @@ -202,31 +207,20 @@ onMounted(() => { onUnmounted(() => { resizeObserver?.disconnect() }) -const mkdir = (doc: Doc, name: string) => { - const control = connect(controlUrl, { - open() { - control.send( - JSON.stringify({ - op: 'mkdir', - path: `${doc.loc}/${name}` - }) - ) - }, - message(ev: MessageEvent) { - const msg = JSON.parse(ev.data) - if ('error' in msg) { - console.error('Mkdir failed', msg.error.message, msg.error) - editing.value = null - } else { - console.log('mkdir', msg) - router.push(doc.urlrouter) - } - } - }) +const mkdir = async (doc: Doc, name: string) => { doc.name = name doc.key = crypto.randomUUID() store.addGhost(doc) editing.value = null + const path = doc.loc ? `${doc.loc}/${name}` : name + try { + const res = await apiFetch(filesUrl(path), { method: 'MKCOL' }) + if (!res.ok) throw new Error(await parseErrorMessage(res)) + router.push(doc.urlrouter) + } catch (err) { + console.error('Mkdir failed', err) + store.showToast(err instanceof Error ? err.message : 'Mkdir failed') + } } const showFolderBreadcrumb = (i: number) => { const docs = props.documents @@ -312,24 +306,17 @@ const copyImage = async (doc: Doc) => { } } -const deleteFile = (doc: Doc) => { +const deleteFile = async (doc: Doc) => { const path = doc.loc ? `${doc.loc}/${doc.name}` : doc.name store.hideDoc(path) - const control = connect(controlUrl, { - message(ev: MessageEvent) { - const res = JSON.parse(ev.data) - if ('error' in res) { - console.error('Delete failed', res.error) - store.unhideDoc(path) - store.showToast(res.error.message || 'Delete failed') - } else if (res.status === 'ack') { - store.showToast(`🗑️ Deleted ${doc.name}`) - control.close() - } - } - }) - control.onopen = () => { - control.send(JSON.stringify({ op: 'rm', sel: [path] })) + try { + const res = await apiFetch(filesUrl(path), { method: 'DELETE' }) + if (!res.ok) throw new Error(await parseErrorMessage(res)) + store.showToast(`🗑️ Deleted ${doc.name}`) + } catch (err) { + console.error('Delete failed', err) + store.unhideDoc(path) + store.showToast(err instanceof Error ? err.message : 'Delete failed') } } diff --git a/frontend/src/components/SelectionToolbar.vue b/frontend/src/components/SelectionToolbar.vue index 57476b5..ce032c0 100644 --- a/frontend/src/components/SelectionToolbar.vue +++ b/frontend/src/components/SelectionToolbar.vue @@ -29,7 +29,7 @@ + + diff --git a/frontend/src/repositories/User.ts b/frontend/src/repositories/User.ts index b2f6cc5..7fc6aad 100644 --- a/frontend/src/repositories/User.ts +++ b/frontend/src/repositories/User.ts @@ -65,3 +65,20 @@ export async function getServerConfig() { const data = await Client.get('/api/config') return data as { name: string, public: boolean } } + +export const url_tokens = '/api/tokens' + +export async function listTokens() { + const data = await Client.get(url_tokens) + return data +} + +export async function createToken(name: string) { + const data = await Client.post(url_tokens, { name }) + return data +} + +export async function deleteToken(tokenId: string) { + const data = await Client.delete(`${url_tokens}/${tokenId}`) + return data +} diff --git a/frontend/src/stores/main.ts b/frontend/src/stores/main.ts index 060aeb2..7438be9 100644 --- a/frontend/src/stores/main.ts +++ b/frontend/src/stores/main.ts @@ -80,7 +80,7 @@ export const useMainStore = defineStore('main', { authInProgress: false, cursor: '' as string, server: {} as Record & { public?: boolean, paskia?: boolean }, - dialog: '' as '' | 'settings' | 'usermgmt' | 'accessdenied', + dialog: '' as '' | 'settings' | 'usermgmt' | 'accessdenied' | 'tokens', uprogress: {} as any, dprogress: {} as any, prefs: { diff --git a/scripts/devserver.py b/scripts/devserver.py index 43ee766..22c79e5 100755 --- a/scripts/devserver.py +++ b/scripts/devserver.py @@ -44,7 +44,9 @@ def setup_sanic_backend( port = opts.get("port", DEFAULT_BACKEND_PORT) host = opts.get("host", "localhost") or "localhost" - cmd = ["cista", "--dev", "-l", listen] + extra_args + # Use the current interpreter/module path so devserver always runs + # workspace source code instead of a potentially stale installed script. + cmd = [sys.executable, "-m", "cista", "--dev", "-l", listen] + extra_args return f"http://{host}:{port}", cmd diff --git a/tests/test_files_auth.py b/tests/test_files_auth.py new file mode 100644 index 0000000..76533eb --- /dev/null +++ b/tests/test_files_auth.py @@ -0,0 +1,207 @@ +import base64 +import hashlib +import hmac +import re +import struct +from pathlib import Path +from time import time +from uuid import uuid4 + +import jwt +import pytest +import pytest_asyncio +from sanic import Sanic + +from cista import auth, config, session, watching +from cista.app import use_session +from cista.fileserver import bp as fileserver_bp + + +def _basic_auth(username: str, password: str) -> dict[str, str]: + creds = base64.b64encode(f"{username}:{password}".encode()).decode() + return {"Authorization": f"Basic {creds}"} + + +def _ntlm_type1() -> dict[str, str]: + msg = b"NTLMSSP\x00" + struct.pack(" dict[str, str]: + """Build an NTLMv2 Type 3 message for testing.""" + from Crypto.Hash import MD4 + + # NT hash + nt_hash = MD4.new(password.encode("utf-16le")).digest() + # NTLMv2 hash + ntlmv2_hash = hmac.new(nt_hash, (username.upper() + domain).encode("utf-16le"), hashlib.md5).digest() + + # Build a minimal blob + timestamp = struct.pack(" dict[str, str]: + token = jwt.encode( + {"exp": int(time()) + session.max_age, "username": username}, + session.session_secret(), + algorithm="HS256", + ) + return {"Cookie": f"s={token}"} + + +@pytest.fixture() +def setup_storage(tmp_path: Path): + user = config.User() + auth.set_password(user, "secret") + token = config.Token(key="test_token_123", username="alice") + config.config = config.Config( + path=tmp_path, + listen=":0", + public=False, + users={"alice": user}, + tokens={"test_token_123": token}, + ) + watching.state.root = [] + watching.rootpath = tmp_path + (tmp_path / "hello.txt").write_text("hello", encoding="utf-8") + yield tmp_path + watching.state.root = [] + + +@pytest_asyncio.fixture() +async def client(setup_storage: Path): + app = Sanic(f"files-auth-test-{uuid4().hex}", strict_slashes=True) + app.router.ALLOWED_METHODS = ( + *app.router.ALLOWED_METHODS, + "MKCOL", + "MOVE", + "COPY", + "PROPFIND", + ) + + @app.on_request + async def load_auth_context(request): + await use_session(request) + + app.blueprint(fileserver_bp) + yield app.asgi_client + + +@pytest.mark.asyncio +async def test_basic_auth_allows_private_file_access(client): + _, res = await client.get("/files/hello.txt", headers=_basic_auth("alice", "secret")) + + assert res.status_code == 200 + assert res.body == b"hello" + assert "set-cookie" not in res.headers + + +@pytest.mark.asyncio +async def test_basic_auth_with_invalid_creds_falls_back_to_session_cookie(client): + _, res = await client.get( + "/files/hello.txt", + headers={**_basic_auth("alice", "wrong"), **_session_cookie_header("alice")}, + ) + + assert res.status_code == 200 + + +@pytest.mark.asyncio +async def test_options_unauthenticated_allowed(client): + _, res = await client.options("/files/") + + assert res.status_code == 200 + + +@pytest.mark.asyncio +async def test_unauthenticated_sends_no_auth_challenge(client): + _, res = await client.request("PROPFIND", "/files/") + + assert res.status_code == 401 + assert "www-authenticate" not in res.headers + + +@pytest.mark.asyncio +async def test_basic_auth_with_token(client): + _, res = await client.get("/files/hello.txt", headers=_basic_auth("token", "test_token_123")) + + assert res.status_code == 200 + assert res.body == b"hello" + + +@pytest.mark.asyncio +async def test_browser_unauthenticated_sends_cookie_challenge(client): + _, res = await client.get("/files/", headers={"Accept": "text/html,application/xhtml+xml"}) + + assert res.status_code == 401 + assert res.headers.get("www-authenticate", "").lower().startswith("cookie") + + +@pytest.mark.asyncio +async def test_ntlm_auth_with_token(client): + # Step 1: request without auth should NOT advertise NTLM + # (we prefer clients use BASIC; NTLM still works if client initiates it) + _, res1 = await client.get("/files/hello.txt") + assert res1.status_code == 401 + assert "ntlm" not in res1.headers.get("www-authenticate", "").lower() + + # Step 2: client proactively sends Type 1, gets Type 2 challenge + _, res2 = await client.get("/files/hello.txt", headers=_ntlm_type1()) + assert res2.status_code == 401 + auth_hdr = res2.headers.get("www-authenticate", "") + assert auth_hdr.lower().startswith("ntlm ") + type2_data = base64.b64decode(auth_hdr.split(" ", 1)[1]) + challenge = type2_data[24:32] + + # Step 3: send Type 3 with token as password + _, res3 = await client.get( + "/files/hello.txt", + headers=_ntlm_type3("anyuser", "test_token_123", "WORKGROUP", challenge), + ) + assert res3.status_code == 200 + assert res3.body == b"hello" diff --git a/tests/test_tokens.py b/tests/test_tokens.py new file mode 100644 index 0000000..738cb40 --- /dev/null +++ b/tests/test_tokens.py @@ -0,0 +1,192 @@ +from pathlib import Path +from time import time +from uuid import uuid4 + +import os + +import pytest +import pytest_asyncio +from sanic import Sanic + +from cista import auth, config, watching +from cista.auth import bp as auth_bp + + +def _persist_config(): + import msgspec + from pathlib import PurePath + + def enc_hook(obj): + if isinstance(obj, PurePath): + return obj.as_posix() + raise TypeError + + raw = msgspec.to_builtins(config.config, enc_hook=enc_hook) + config.conffile.write_bytes(msgspec.toml.encode(raw)) + + +@pytest.fixture() +def setup_storage(tmp_path: Path): + os.environ["CISTA_HOME"] = str(tmp_path) + config.init_confdir() + user = config.User() + auth.set_password(user, "secret") + admin = config.User(privileged=True) + auth.set_password(admin, "secret") + config.config = config.Config( + path=tmp_path, + listen=":0", + public=False, + users={"alice": user, "admin": admin}, + ) + _persist_config() + watching.state.root = [] + watching.rootpath = tmp_path + yield tmp_path + watching.state.root = [] + + +@pytest_asyncio.fixture() +async def client(setup_storage: Path): + app = Sanic(f"token-test-{uuid4().hex}", strict_slashes=True) + app.router.ALLOWED_METHODS = ( + *app.router.ALLOWED_METHODS, + "MKCOL", + "MOVE", + "COPY", + "PROPFIND", + ) + app.blueprint(auth_bp) + yield app.asgi_client + + +def _basic_auth(username: str, password: str) -> str: + return f"Basic {__import__('base64').b64encode(f'{username}:{password}'.encode()).decode()}" + + +@pytest.mark.asyncio +async def test_token_crud(client): + # Admin creates a token without specifying username (auto-assigned) + _, res = await client.post( + "/auth/tokens", + json={"name": "test"}, + headers={"Authorization": _basic_auth("admin", "secret")}, + ) + assert res.status_code == 200 + data = res.json + assert "id" in data + assert "key" in data + assert data["username"] == "admin" + assert data["name"] == "test" + token_id = data["id"] + token_key = data["key"] + + # List tokens - admin sees only their own + _, res = await client.get( + "/auth/tokens", + headers={"Authorization": _basic_auth("admin", "secret")}, + ) + assert res.status_code == 200 + tokens = res.json["tokens"] + assert len(tokens) == 1 + assert tokens[0]["id"] == token_id + assert tokens[0]["username"] == "admin" + + # Use token via Basic auth (token:) + _, res = await client.get( + "/auth/tokens", + headers={"Authorization": _basic_auth("token", token_key)}, + ) + assert res.status_code == 200 + + # Delete token + _, res = await client.delete( + f"/auth/tokens/{token_id}", + headers={"Authorization": _basic_auth("admin", "secret")}, + ) + assert res.status_code == 200 + + # List should be empty + _, res = await client.get( + "/auth/tokens", + headers={"Authorization": _basic_auth("admin", "secret")}, + ) + assert res.status_code == 200 + assert len(res.json["tokens"]) == 0 + + +@pytest.mark.asyncio +async def test_token_user_scoped(client): + # Alice creates a token for herself (no username specified) + _, res = await client.post( + "/auth/tokens", + json={"name": "alice-token"}, + headers={"Authorization": _basic_auth("alice", "secret")}, + ) + assert res.status_code == 200 + alice_token_id = res.json["id"] + alice_token_key = res.json["key"] + + # Admin creates a token for themselves + _, res = await client.post( + "/auth/tokens", + json={"name": "admin-token"}, + headers={"Authorization": _basic_auth("admin", "secret")}, + ) + assert res.status_code == 200 + admin_token_id = res.json["id"] + + # Alice lists tokens - sees only her own + _, res = await client.get( + "/auth/tokens", + headers={"Authorization": _basic_auth("alice", "secret")}, + ) + assert res.status_code == 200 + tokens = res.json["tokens"] + assert len(tokens) == 1 + assert tokens[0]["id"] == alice_token_id + assert tokens[0]["username"] == "alice" + + # Admin lists tokens - sees only their own + _, res = await client.get( + "/auth/tokens", + headers={"Authorization": _basic_auth("admin", "secret")}, + ) + assert res.status_code == 200 + tokens = res.json["tokens"] + assert len(tokens) == 1 + assert tokens[0]["id"] == admin_token_id + assert tokens[0]["username"] == "admin" + + # Alice cannot create a token for admin + _, res = await client.post( + "/auth/tokens", + json={"username": "admin", "name": "impersonation"}, + headers={"Authorization": _basic_auth("alice", "secret")}, + ) + assert res.status_code == 403 + + # Alice cannot delete admin's token + _, res = await client.delete( + f"/auth/tokens/{admin_token_id}", + headers={"Authorization": _basic_auth("alice", "secret")}, + ) + assert res.status_code == 403 + + # Alice can delete her own token + _, res = await client.delete( + f"/auth/tokens/{alice_token_id}", + headers={"Authorization": _basic_auth("alice", "secret")}, + ) + assert res.status_code == 200 + + # Alice's token auth still works until deletion is processed + # Verify token auth worked during the test + _, res = await client.get( + "/auth/tokens", + headers={"Authorization": _basic_auth("token", alice_token_key)}, + ) + # Token was deleted above, so this should now be unauthenticated + # Actually the token key lookup will fail, and since there's no session fallback... + # With auth header present but invalid, it should return 401 + assert res.status_code == 401 -- 2.55.0 From f7ffc3f8bc810b4668941a8f8acfe33aab247970 Mon Sep 17 00:00:00 2001 From: Leo Vasanko Date: Sun, 26 Apr 2026 05:13:37 +0000 Subject: [PATCH 4/6] Restore UA-aware auth header advertisement Revert accidental removal of WWW-Authenticate headers. Windows WebDAV clients receive Basic + Negotiate; all other clients receive Basic only. --- cista/auth.py | 9 ++++++++- tests/test_files_auth.py | 4 ++-- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/cista/auth.py b/cista/auth.py index 9074513..6c7788f 100644 --- a/cista/auth.py +++ b/cista/auth.py @@ -279,7 +279,14 @@ def _log_webdav_user_agent_once(request, user_agent: str): def _build_ua_auth_headers(request, *, include_hint=False) -> dict[str, str]: - return {} + user_agent = request.headers.get("user-agent", "") + _log_webdav_user_agent_once(request, user_agent) + if _is_windows_auth_client(user_agent): + challenge = f'Basic realm="{_AUTH_REALM}", Negotiate' + else: + challenge = f'Basic realm="{_AUTH_REALM}"' + headers = {"WWW-Authenticate": challenge} + return headers def _cleanup_ntlm_challenges(): diff --git a/tests/test_files_auth.py b/tests/test_files_auth.py index 76533eb..29fdf80 100644 --- a/tests/test_files_auth.py +++ b/tests/test_files_auth.py @@ -159,11 +159,11 @@ async def test_options_unauthenticated_allowed(client): @pytest.mark.asyncio -async def test_unauthenticated_sends_no_auth_challenge(client): +async def test_unauthenticated_sends_basic_auth_challenge(client): _, res = await client.request("PROPFIND", "/files/") assert res.status_code == 401 - assert "www-authenticate" not in res.headers + assert res.headers.get("www-authenticate", "").lower().startswith('basic realm="cista"') @pytest.mark.asyncio -- 2.55.0 From 747ae7a8d50bd79b2af4616dbdce45b26ba88b93 Mon Sep 17 00:00:00 2001 From: Leo Vasanko Date: Sun, 26 Apr 2026 05:15:55 +0000 Subject: [PATCH 5/6] Document WebDAV access and compatible clients in README MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Add WebDAV Access section with client setup instructions - Explain Basic auth and API token authentication for WebDAV - Document Windows NTLM limitation and token-based workaround - Fix typo: authenticatioon → authentication --- README.md | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 23dd327..edb4d20 100644 --- a/README.md +++ b/README.md @@ -45,7 +45,7 @@ The server remembers its settings in the config folder (default `~/.local/share/ ## Authentication -Cista supports two authenticatioon mode, each of which supporting ordinary and privileged users. Either one can be combined with the public mode. +Cista supports two authentication modes, each supporting ordinary and privileged users. Either one can be combined with the public mode. ### Public Mode @@ -83,6 +83,28 @@ In Paskia mode: - Users with `cista:login` permission can access files - Users with `cista:admin` permission get privileged access (Admin Settings) +## WebDAV Access + +Cista supports WebDAV, so you can mount it as a network drive or browse it directly from your operating system's file manager. + +Connect to `http://cista.example.com/files/` (or `https://...`). + +### Authentication + +- **Standard users:** Use your username and password with Basic auth. +- **API tokens:** For scripts, backup tools, or when your client requires NTLM (e.g. Windows File Explorer), create a token in the web interface via **🔑 API Tokens**. Authenticate with username `token` and the token secret as the password. + +### Supported clients + +| Client | Setup | +|--------|-------| +| **Windows File Explorer** | Map Network Drive → `http://cista.example.com/files/` (or Add a network location). Windows may try NTLM first; API tokens are recommended. | +| **macOS Finder** | Go → Connect to Server (⌘K) → `http://cista.example.com/files/` | +| **Linux (GNOME/KDE)** | Enter `dav://cista.example.com/files/` or `webdav://cista.example.com/files/` in the location bar | +| **Cyberduck, WinSCP, rclone** | Standard WebDAV profile with Basic auth | + +**Note on Windows NTLM:** Windows WebDAV clients often require NTLM authentication, which is incompatible with Cista's Argon2 password hashes. API tokens solve this — Cista uses the token secret as the NTLM password. + ### Internet Access Most admins find the [Caddy](https://caddyserver.com/) web server convenient for its auto TLS certificates and all. A proxy also allows running multiple web services or Cista instances on the same IP address but different (sub)domains. -- 2.55.0 From 4fd166b93439c599c0974e533af541a9fec1c1ae Mon Sep 17 00:00:00 2001 From: Leo Vasanko Date: Sun, 26 Apr 2026 05:18:19 +0000 Subject: [PATCH 6/6] Use https in WebDAV examples and add Android clients - Replace all http:// example URLs with https:// in WebDAV section - Add Solid Explorer and CX File Explorer Android setup instructions - Use davs:// and webdavs:// for Linux HTTPS WebDAV URLs --- README.md | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index edb4d20..1d49a2e 100644 --- a/README.md +++ b/README.md @@ -87,7 +87,7 @@ In Paskia mode: Cista supports WebDAV, so you can mount it as a network drive or browse it directly from your operating system's file manager. -Connect to `http://cista.example.com/files/` (or `https://...`). +Connect to `https://cista.example.com/files/`. ### Authentication @@ -98,9 +98,11 @@ Connect to `http://cista.example.com/files/` (or `https://...`). | Client | Setup | |--------|-------| -| **Windows File Explorer** | Map Network Drive → `http://cista.example.com/files/` (or Add a network location). Windows may try NTLM first; API tokens are recommended. | -| **macOS Finder** | Go → Connect to Server (⌘K) → `http://cista.example.com/files/` | -| **Linux (GNOME/KDE)** | Enter `dav://cista.example.com/files/` or `webdav://cista.example.com/files/` in the location bar | +| **Windows File Explorer** | Map Network Drive → `https://cista.example.com/files/` (or Add a network location). Windows may try NTLM first; API tokens are recommended. | +| **macOS Finder** | Go → Connect to Server (⌘K) → `https://cista.example.com/files/` | +| **Linux (GNOME/KDE)** | Enter `davs://cista.example.com/files/` or `webdavs://cista.example.com/files/` in the location bar | +| **Android — Solid Explorer** | Tap **+** → New Cloud Connection → **WebDAV** → enter `https://cista.example.com/files/` and your credentials. | +| **Android — CX File Explorer** | Open the **Network** tab → **New location** → **WebDAV** → enter `https://cista.example.com/files/` and your credentials. | | **Cyberduck, WinSCP, rclone** | Standard WebDAV profile with Basic auth | **Note on Windows NTLM:** Windows WebDAV clients often require NTLM authentication, which is incompatible with Cista's Argon2 password hashes. API tokens solve this — Cista uses the token secret as the NTLM password. -- 2.55.0