Compare commits

..
4 Commits
27 changed files with 1229 additions and 346 deletions
+6
View File
@@ -1,2 +1,8 @@
/docs/snapshots/ /docs/snapshots/
/.worktrees/ /.worktrees/
# Disposable manual-test snapshots
/.test-worktrees/
# Python validation caches
__pycache__/
+6
View File
@@ -0,0 +1,6 @@
#!/usr/bin/env bash
set -Eeuo pipefail
COMMON="$(git -C "$ROBORTO_PROJECT_ROOT" rev-parse --path-format=absolute --git-common-dir)"
SHARED="$(dirname "$COMMON")"
PYTHON="${FOLDERSHARE_TEST_PYTHON:-$SHARED/api/.venv/bin/python}"
exec "$PYTHON" "$ROBORTO_PROJECT_ROOT/scripts/testtask_adapter.py" "$@"
+7
View File
@@ -0,0 +1,7 @@
ROBORTO_PROJECT_SLUG="foldershare"
ROBORTO_TASK_ID_PATTERN='^[0-9]{3}$'
ROBORTO_WORKTREE="${ROBORTO_PROJECT_ROOT}/.test-worktrees/task-${ROBORTO_TASK_ID}"
ROBORTO_HOOK="${ROBORTO_PROJECT_ROOT}/.roborto/testtask-hook"
ROBORTO_BROWSER_URL="http://127.0.0.1:5503/"
ROBORTO_READY_PORTS=(5502 5503)
ROBORTO_READY_LABELS=(API Web)
+1 -1
View File
@@ -16,7 +16,7 @@ Verify and report the current worktree path, branch, Git status, existing uncomm
For implementation, use one accepted numbered task per isolated task branch/worktree by default. Concurrent tasks use separate worktrees; do not mix unrelated task changes or edit a manual-test snapshot. Derive the task branch from the repository-approved integration branch. This repository has **no approved branch naming, worktree path, merge strategy, or release branch convention yet**; proposed defaults are in `docs/DECISIONS.md`. Resolve those conventions with Captain before first use rather than treating proposals as established rules. Never switch a branch used by another console or check one branch out in two worktrees. For implementation, use one accepted numbered task per isolated task branch/worktree by default. Concurrent tasks use separate worktrees; do not mix unrelated task changes or edit a manual-test snapshot. Derive the task branch from the repository-approved integration branch. This repository has **no approved branch naming, worktree path, merge strategy, or release branch convention yet**; proposed defaults are in `docs/DECISIONS.md`. Resolve those conventions with Captain before first use rather than treating proposals as established rules. Never switch a branch used by another console or check one branch out in two worktrees.
Do not commit, push, merge, rebase, reset, deploy, or perform destructive operations without repository workflow authority or Captain's explicit authorization. Leave merge and release authority with Captain unless explicitly delegated. The repository has no discovered manual-test/testtask adapter; if one is later added, use it for test evidence and keep implementation in the task worktree. Do not commit, push, merge, rebase, reset, deploy, or perform destructive operations without repository workflow authority or Captain's explicit authorization. Leave merge and release authority with Captain unless explicitly delegated. Use `scripts/testtask.sh NNN` for isolated manual testing; see `scripts/README.md` for prerequisites and invocation. Implementation stays in its task worktree; `.test-worktrees/` contains disposable test copies only. Refresh by stopping and rerunning after source changes. Never copy live environment, databases or media into a snapshot.
## Task lifecycle and handoff ## Task lifecycle and handoff
+1 -1
View File
@@ -13,7 +13,7 @@ def verify_password(username, password):
"""Verify password.""" """Verify password."""
user = ( user = (
User.query.filter_by(username=username) User.query.filter_by(username=username)
.filter(User.login_disabled is not True) .filter(User.login_disabled.is_(False))
.first() .first()
) )
if user and user.check_password(password): if user and user.check_password(password):
+152
View File
@@ -0,0 +1,152 @@
"""Server-owned, deny-by-default media boundaries.
Virtual roots start with / and are relative to the configured media directory.
Symlinks are excluded entirely; media mounts must also be read-only in deployment.
"""
import os
import stat
from contextlib import contextmanager, ExitStack
from pathlib import Path
from flask import current_app
class MediaDenied(ValueError):
pass
class InvalidFolderPath(MediaDenied):
pass
class FolderNotFound(MediaDenied):
pass
class MediaUnavailable(MediaDenied):
pass
def media_root():
try:
root = Path(current_app.config["MEDIA_ROOT"]).resolve(strict=True)
if not root.is_dir():
raise MediaDenied()
return root
except (OSError, RuntimeError, TypeError):
raise MediaDenied() from None
def virtual_parts(value):
if not isinstance(value, str) or not value.startswith("/"):
raise InvalidFolderPath()
parts = value[1:].split("/") if value != "/" else []
if any(part in ("", ".", "..") or "\x00" in part for part in parts):
raise InvalidFolderPath()
return parts
def _assignment_parts(value):
try:
parts = virtual_parts(value)
except InvalidFolderPath:
raise MediaDenied() from None
if "\\" in value or "%" in value:
raise MediaDenied()
return parts
def assigned_root(value):
parts = _assignment_parts(value)
root = media_root()
path = root
try:
for part in parts:
path = path / part
if path.is_symlink():
raise MediaDenied()
path = path.resolve(strict=True)
if not path.is_relative_to(root) or not path.is_dir():
raise MediaDenied()
return path
except (OSError, RuntimeError, ValueError):
raise MediaDenied() from None
@contextmanager
def _open_directory(root, parts=()):
flags = os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW
descriptor = os.dup(root) if isinstance(root, int) else os.open(root, flags)
try:
for part in parts:
child_fd = os.open(part, flags, dir_fd=descriptor)
os.close(descriptor)
descriptor = child_fd
yield descriptor
finally:
os.close(descriptor)
def _folder_entries(descriptor):
dirs, files = [], []
with os.scandir(descriptor) as entries:
names = sorted(entry.name for entry in entries)
for name in names:
try:
metadata = os.stat(name, dir_fd=descriptor, follow_symlinks=False)
except FileNotFoundError:
# The entry was removed between enumeration and the metadata read.
continue
if stat.S_ISDIR(metadata.st_mode):
dirs.append(name)
elif stat.S_ISREG(metadata.st_mode):
files.append({"name": name, "size": metadata.st_size})
return dirs, files
def list_assigned_folder(assignment, virtual):
"""List direct children within an assigned root, using virtual references."""
assignment_parts = _assignment_parts(assignment)
parts = virtual_parts(virtual)
try:
root = media_root()
except MediaDenied:
raise MediaUnavailable() from None
try:
with ExitStack() as stack:
base = stack.enter_context(_open_directory(root))
try:
assigned = stack.enter_context(_open_directory(base, assignment_parts))
except (FileNotFoundError, NotADirectoryError):
raise MediaDenied() from None
try:
folder = stack.enter_context(_open_directory(assigned, parts))
except (FileNotFoundError, NotADirectoryError):
raise FolderNotFound() from None
dirs, files = _folder_entries(folder)
except OSError:
raise MediaUnavailable() from None
for file in files:
file["ref"] = f"{virtual.rstrip('/')}/{file['name']}"
return {"root": virtual, "dirs": dirs, "files": files}
def file_tree(root):
"""List using anchored directory descriptors; never follow swapped links."""
tree = []
def visit(descriptor, virtual):
dirs, files = _folder_entries(descriptor)
tree.append({"root": virtual, "dirs": dirs, "files": files})
for name in dirs:
with _open_directory(descriptor, (name,)) as child_fd:
visit(child_fd, virtual.rstrip("/") + "/" + name)
try:
base = media_root()
with _open_directory(base, root.relative_to(base).parts) as descriptor:
visit(descriptor, "/")
except (OSError, RuntimeError, ValueError):
raise MediaDenied() from None
return tree
+14 -19
View File
@@ -1,6 +1,6 @@
from sqlalchemy_serializer import SerializerMixin from sqlalchemy_serializer import SerializerMixin
from werkzeug.security import generate_password_hash, check_password_hash from werkzeug.security import generate_password_hash, check_password_hash
from settings import db, root_path from settings import db
import base64 import base64
from datetime import datetime, timedelta from datetime import datetime, timedelta
import os import os
@@ -67,7 +67,12 @@ class User(db.Model, SerializerMixin):
@staticmethod @staticmethod
def check_token(token): def check_token(token):
user = User.query.filter_by(token=token).first() user = User.query.filter_by(token=token).first()
if user is None or user.token_expiration < datetime.utcnow(): if (
user is None
or user.login_disabled is not False
or user.token_expiration is None
or user.token_expiration < datetime.utcnow()
):
return None return None
return user return user
@@ -78,21 +83,11 @@ class User(db.Model, SerializerMixin):
return None return None
return user return user
def get_file_list(self) -> dict: def get_file_list(self) -> list:
if self.root is None: from media import assigned_root, file_tree, MediaDenied
if self.login_disabled is not False or self.root is None:
return []
try:
return file_tree(assigned_root(self.root))
except MediaDenied:
return [] return []
root = f"{root_path}{self.root}"
file_list = []
for root, dirs, files in os.walk(root, topdown=True):
files = list(
map(
lambda file: {
"name": file,
"size": os.path.getsize(root + "/" + file),
},
files,
)
)
file_list.append({"root": root, "dirs": dirs, "files": files})
return file_list
+41 -38
View File
@@ -1,49 +1,52 @@
from settings import app, root_path """Media routes. Legacy client-directed downloads are deliberately disabled."""
from flask import request, send_from_directory from flask import request
import os from settings import app
import mime
from auth import token_auth from auth import token_auth
from errors import error_response from errors import error_response
from media import (
FolderNotFound,
InvalidFolderPath,
MediaDenied,
MediaUnavailable,
file_tree,
list_assigned_folder,
media_root,
)
@app.route("/api/file/root") @app.route("/api/file/root")
@token_auth.login_required @token_auth.login_required
def get_root_path() -> list: def get_root_path():
user = token_auth.current_user() if not token_auth.current_user().is_admin:
if not user.is_admin:
return error_response(403) return error_response(403)
file_list = [] try:
for root, dirs, files in os.walk(root_path, topdown=False): return file_tree(media_root())
files = list( except MediaDenied:
map( return error_response(503, "Media unavailable")
lambda file: {
"name": file,
"size": os.path.getsize(root + "/" + file), @app.route("/api/file/browse")
}, @token_auth.login_required
files, def browse_files():
) user = token_auth.current_user()
) if user.root is None:
file_list.append( return error_response(403, "No assigned folder")
{
"root": "/" + "/".join(root.split("/")[1:]), try:
"dirs": dirs, folder = list_assigned_folder(user.root, request.args.get("path", "/"))
"files": files, except InvalidFolderPath:
} return error_response(400, "Invalid folder path")
) except FolderNotFound:
return file_list[::-1] return error_response(404, "Folder unavailable")
except MediaUnavailable:
return error_response(503, "Media unavailable")
except MediaDenied:
return error_response(403, "Assigned folder unavailable")
return folder, 200, {"Cache-Control": "no-store"}
@app.route("/api/file", methods=["POST"]) @app.route("/api/file", methods=["POST"])
@token_auth.login_required @token_auth.login_required
def get_file() -> dict: def get_file():
req = request.get_json() return error_response(410, "Downloads unavailable pending secure download grants")
path = req["path"]
mimetype = str(mime.Types.of(path + "/" + req["filename"])[0])
if not os.path.exists(path):
return {"error": "file not found"}
try:
return send_from_directory(
path, req["filename"], as_attachment=True, mimetype=mimetype
)
except FileNotFoundError:
return error_response(404, f"File not found: {path}/{req["filename"]}")
+5 -2
View File
@@ -16,10 +16,11 @@ basic_auth.realm = "Incorrect Credentials"
def get_token(): def get_token():
"""Get token.""" """Get token."""
user = basic_auth.current_user() user = basic_auth.current_user()
user.get_token()
refresh_token = user.get_refresh_token() refresh_token = user.get_refresh_token()
db.session.commit() db.session.commit()
response = make_response( response = make_response(
jsonify(user.to_dict(rules=("is_admin", "token"))) jsonify({**user.to_dict(rules=("-root", "is_admin", "token")), "user_id": user.id})
) )
response.set_cookie("refresh_token", value=refresh_token, httponly=True) response.set_cookie("refresh_token", value=refresh_token, httponly=True)
return response return response
@@ -41,10 +42,12 @@ def refresh_token():
if refresh_token is None: if refresh_token is None:
return error_response(400, "Bad request, no refresh token") return error_response(400, "Bad request, no refresh token")
user = User.query.filter_by(refresh_token=refresh_token).first() user = User.query.filter_by(refresh_token=refresh_token).first()
if user is not None: if user is not None and user.login_disabled is False:
access_token = user.get_token() access_token = user.get_token()
db.session.commit() db.session.commit()
return { return {
"token": access_token, "token": access_token,
"user_id": user.id, "user_id": user.id,
} }
return error_response(401)
+26 -4
View File
@@ -4,6 +4,7 @@ from settings import app, db
from models.user import User from models.user import User
from errors import error_response, bad_request from errors import error_response, bad_request
from auth import token_auth from auth import token_auth
from media import assigned_root, MediaDenied
from flask import request from flask import request
from sqlalchemy import select from sqlalchemy import select
from werkzeug.security import generate_password_hash from werkzeug.security import generate_password_hash
@@ -28,13 +29,26 @@ def get_user(user_id) -> list:
return error_response(403) return error_response(403)
stmt = select(User).filter(User.id == user_id) stmt = select(User).filter(User.id == user_id)
user = db.session.scalars(stmt).first() user = db.session.scalars(stmt).first()
if user is None:
return error_response(404)
return user.to_dict() return user.to_dict()
@app.route("/api/user/<user_id>", methods=["PATCH"]) @app.route("/api/user/<user_id>", methods=["PATCH"])
@token_auth.login_required @token_auth.login_required
def update_user(user_id) -> dict: def update_user(user_id) -> dict:
req = request.get_json() if not token_auth.current_user().is_admin:
return error_response(403)
req = request.get_json(silent=True)
if not isinstance(req, dict) or set(req) - {"root", "login_disabled"}:
return bad_request("Invalid user update")
if "login_disabled" in req and type(req["login_disabled"]) is not bool:
return bad_request("Invalid disabled flag")
if req.get("root") is not None:
try:
assigned_root(req["root"])
except MediaDenied:
return bad_request("Invalid media root")
stmt = select(User).filter(User.id == user_id) stmt = select(User).filter(User.id == user_id)
user = db.session.scalars(stmt).first() user = db.session.scalars(stmt).first()
if user is None: if user is None:
@@ -45,6 +59,8 @@ def update_user(user_id) -> dict:
if user.is_admin: if user.is_admin:
return bad_request(f"User is admin: {user.username}") return bad_request(f"User is admin: {user.username}")
user.login_disabled = req["login_disabled"] user.login_disabled = req["login_disabled"]
if user.login_disabled:
user.revoke_tokens()
db.session.commit() db.session.commit()
return user.to_dict() return user.to_dict()
@@ -52,15 +68,19 @@ def update_user(user_id) -> dict:
@app.route("/api/user", methods=["POST"]) @app.route("/api/user", methods=["POST"])
@token_auth.login_required @token_auth.login_required
def add_user() -> dict: def add_user() -> dict:
model = request.get_json() if not token_auth.current_user().is_admin:
if "username" not in model or model["username"] is None: return error_response(403)
model = request.get_json(silent=True)
if not isinstance(model, dict) or set(model) - {"username", "password"}:
return bad_request("Invalid user creation")
if not isinstance(model.get("username"), str) or not model["username"].strip():
return bad_request("No username") return bad_request("No username")
username = model["username"] username = model["username"]
stmt = select(User).filter(User.username == username) stmt = select(User).filter(User.username == username)
user = db.session.scalars(stmt).first() user = db.session.scalars(stmt).first()
if user is not None: if user is not None:
return error_response(409, f"User exists: {user.id}, {username}") return error_response(409, f"User exists: {user.id}, {username}")
if "password" not in model or model["password"] is None: if not isinstance(model.get("password"), str) or not model["password"]:
return bad_request("No password") return bad_request("No password")
password_hash = generate_password_hash(model["password"]) password_hash = generate_password_hash(model["password"])
user = User(username=username, password_hash=password_hash) user = User(username=username, password_hash=password_hash)
@@ -72,6 +92,8 @@ def add_user() -> dict:
@app.route("/api/user/<user_id>", methods=["DELETE"]) @app.route("/api/user/<user_id>", methods=["DELETE"])
@token_auth.login_required @token_auth.login_required
def delete_user(user_id) -> dict: def delete_user(user_id) -> dict:
if not token_auth.current_user().is_admin:
return error_response(403)
stmt = select(User).filter(User.id == user_id) stmt = select(User).filter(User.id == user_id)
user = db.session.scalars(stmt).first() user = db.session.scalars(stmt).first()
if user is None: if user is None:
+3 -1
View File
@@ -11,7 +11,7 @@ app = Flask(__name__, static_folder="static")
app.config.update( app.config.update(
{ {
"DEBUG": bool(os.environ.get("DEBUG") == "True"), "DEBUG": bool(os.environ.get("DEBUG") == "True"),
"SQLALCHEMY_DATABASE_URI": "sqlite:///foldershare.sqlite", "SQLALCHEMY_DATABASE_URI": os.environ.get("FOLDERSHARE_DATABASE_URI", "sqlite:///foldershare.sqlite"),
"SQLALCHEMY_ECHO": bool(os.environ.get("SQLALCHEMY_ECHO") == "True"), "SQLALCHEMY_ECHO": bool(os.environ.get("SQLALCHEMY_ECHO") == "True"),
"SQLALCHEMY_TRACK_MODIFICATIONS": bool( "SQLALCHEMY_TRACK_MODIFICATIONS": bool(
os.environ.get("SQLALCHEMY_TRACK_MODIFICATIONS") == "True" os.environ.get("SQLALCHEMY_TRACK_MODIFICATIONS") == "True"
@@ -24,3 +24,5 @@ migrate = Migrate(app, db, render_as_batch=True)
root_path = os.environ.get("ROOT_PATH") root_path = os.environ.get("ROOT_PATH")
if root_path is None: if root_path is None:
root_path = "share" root_path = "share"
app.config["MEDIA_ROOT"] = os.path.abspath(root_path)
+244
View File
@@ -0,0 +1,244 @@
"""Run: <venv>/bin/python -m unittest discover -s api/tests -v (task root)."""
import base64
import os
from pathlib import Path
import sys
import tempfile
import unittest
from unittest.mock import patch
sandbox = tempfile.TemporaryDirectory()
os.environ['FOLDERSHARE_DATABASE_URI'] = 'sqlite:///' + sandbox.name + '/test.sqlite'
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from api import app, db
from models.user import User
from media import assigned_root, MediaDenied
class SecurityTests(unittest.TestCase):
def setUp(self):
self.ctx = app.app_context()
self.ctx.push()
app.config.update(TESTING=True, MEDIA_ROOT=sandbox.name + '/media')
self.root = Path(app.config['MEDIA_ROOT'])
(self.root / 'alice' / 'nested').mkdir(parents=True, exist_ok=True)
(self.root / 'bob').mkdir(exist_ok=True)
(self.root / 'alice' / 'movie.mp4').write_bytes(b'movie')
(self.root / 'alice' / 'nested' / 'other.mp4').write_bytes(b'other')
outside = Path(sandbox.name) / 'private'
outside.mkdir(exist_ok=True)
for name, target in [('escape', outside), ('sibling', self.root / 'bob')]:
link = self.root / 'alice' / name
if not link.is_symlink():
link.symlink_to(target, target_is_directory=True)
db.create_all()
self.tokens = {}
self.refresh = {}
for name in ['admin', 'alice', 'empty', 'disabled']:
user = User(username=name, is_admin=name == 'admin', login_disabled=name == 'disabled', root='/alice' if name == 'alice' else None)
user.set_password('test-password')
db.session.add(user)
self.tokens[name] = user.get_token()
self.refresh[name] = user.get_refresh_token()
db.session.commit()
self.client = app.test_client()
self.alice_id = User.query.filter_by(username='alice').first().id
def tearDown(self):
db.session.remove()
db.drop_all()
self.ctx.pop()
def headers(self, name):
return {'Authorization': 'Bearer ' + self.tokens[name]}
def test_login_after_logout_renews_admin_session(self):
headers = self.headers('admin')
self.assertEqual(self.client.delete('/api/auth/tokens', headers=headers).status_code, 200)
basic = base64.b64encode(b'admin:test-password').decode()
response = self.client.post('/api/auth/token', headers={'Authorization': 'Basic ' + basic})
self.assertEqual(response.status_code, 200)
data = response.get_json()
listed = self.client.get('/api/user', headers={'Authorization': 'Bearer ' + data['token']})
self.assertEqual(listed.status_code, 200)
self.assertEqual(len(listed.get_json()), 4)
self.assertEqual(data['user_id'], data['id'])
self.assertEqual(self.client.get('/api/auth/refresh').get_json()['user_id'], data['user_id'])
def test_sign_in_keeps_stored_folder_assignment_on_server(self):
alice = db.session.get(User, self.alice_id)
alice.root = str(self.root / 'alice')
db.session.commit()
basic = base64.b64encode(b'alice:test-password').decode()
response = self.client.post('/api/auth/token', headers={'Authorization': 'Basic ' + basic})
self.assertEqual(response.status_code, 200)
self.assertNotIn('root', response.get_json())
def test_first_login_issues_usable_token(self):
user = User(username='new-admin', is_admin=True, login_disabled=False)
user.set_password('test-password')
db.session.add(user)
db.session.commit()
basic = base64.b64encode(b'new-admin:test-password').decode()
data = self.client.post('/api/auth/token', headers={'Authorization': 'Basic ' + basic}).get_json()
self.assertTrue(data['token'])
self.assertEqual(self.client.get('/api/user', headers={'Authorization': 'Bearer ' + data['token']}).status_code, 200)
def test_mutation_authorization(self):
for method, path, payload in [('POST', '/api/user', {'username':'new','password':'pw'}), ('PATCH', f'/api/user/{self.alice_id}', {'root':'/bob'}), ('DELETE', f'/api/user/{self.alice_id}', {})]:
for name, status in [(None,401), ('alice',403), ('empty',403), ('disabled',401)]:
with self.subTest(method=method, name=name):
response = self.client.open(path, method=method, json=payload, headers=self.headers(name) if name else {})
self.assertEqual(response.status_code, status)
self.assertIsNotNone(db.session.get(User, self.alice_id))
def test_admin_updates_and_revocation(self):
url = f'/api/user/{self.alice_id}'
self.assertEqual(self.client.patch(url, json={'root':'/bob'}, headers=self.headers('admin')).status_code,200)
self.assertEqual(self.client.patch(url, json={'root':None}, headers=self.headers('admin')).status_code,200)
self.assertEqual(db.session.get(User,self.alice_id).get_file_list(), [])
self.assertEqual(self.client.patch(url, json={'login_disabled':True}, headers=self.headers('admin')).status_code,200)
self.assertEqual(self.client.get('/api/file/root',headers=self.headers('alice')).status_code,401)
self.client.set_cookie('refresh_token', self.refresh['alice'])
self.assertEqual(self.client.get('/api/auth/refresh').status_code,401)
self.client.patch(url,json={'login_disabled':False},headers=self.headers('admin'))
self.assertEqual(self.client.get('/api/file/root',headers=self.headers('alice')).status_code,401)
def test_login_refresh_deleted_and_disabled(self):
for name in ['alice','disabled']:
credentials = base64.b64encode(f'{name}:test-password'.encode()).decode()
response = self.client.post('/api/auth/token', headers={'Authorization':'Basic ' + credentials})
self.assertEqual(response.status_code,200 if name == 'alice' else 401)
self.client.set_cookie('refresh_token', self.refresh[name])
self.assertEqual(self.client.get('/api/auth/refresh').status_code,200 if name == 'alice' else 401)
self.client.delete(f'/api/user/{self.alice_id}', headers=self.headers('admin'))
self.assertEqual(self.client.get('/api/file/root',headers=self.headers('alice')).status_code,401)
self.client.set_cookie('refresh_token',self.refresh['alice'])
self.assertEqual(self.client.get('/api/auth/refresh').status_code,401)
def test_root_validation(self):
for root in ['/../private', '/alice/../bob', '/alice/escape', '/alice/sibling', '/alice//nested', '/alice/%2e%2e/bob', '/alice\\nested', '/missing', str(self.root / 'alice'), '', 42]:
with self.subTest(root=root):
with self.assertRaises(MediaDenied):
assigned_root(root)
self.assertEqual(self.client.patch(f'/api/user/{self.alice_id}', json={'root':root}, headers=self.headers('admin')).status_code,400)
self.assertEqual(assigned_root('/alice/nested'), self.root / 'alice/nested')
self.assertEqual(assigned_root('/'), self.root)
def test_listing_boundaries(self):
self.assertEqual(User.query.filter_by(username='empty').first().get_file_list(), [])
alice = db.session.get(User,self.alice_id)
tree = alice.get_file_list()
self.assertEqual([item['root'] for item in tree], ['/', '/nested'])
self.assertEqual(tree[0]['dirs'],['nested'])
self.assertNotIn(str(self.root), str(tree))
for root in [None, '/missing', '/../private', '/alice/escape']:
alice.root = root
self.assertEqual(alice.get_file_list(),[])
self.assertEqual(self.client.get('/api/file/root',headers=self.headers('alice')).status_code,403)
response = self.client.get('/api/file/root',headers=self.headers('admin'))
self.assertEqual(response.status_code,200)
self.assertNotIn(str(self.root),response.get_data(as_text=True))
app.config['MEDIA_ROOT'] = str(self.root / 'unavailable')
self.assertEqual(self.client.get('/api/file/root',headers=self.headers('admin')).status_code,503)
def test_symlink_swap_during_listing(self):
from media import file_tree
original_open = os.open
nested = self.root / 'alice' / 'nested'
saved = self.root / 'alice' / 'saved'
def swap(name, flags, *args, **kwargs):
if name == 'nested' and kwargs.get('dir_fd') is not None:
nested.rename(saved)
nested.symlink_to(Path(sandbox.name) / 'private', target_is_directory=True)
return original_open(name, flags, *args, **kwargs)
try:
with patch('media.os.open', side_effect=swap):
with self.assertRaises(MediaDenied):
file_tree(assigned_root('/alice'))
finally:
if nested.is_symlink():
nested.unlink()
saved.rename(nested)
def test_browse_lists_one_folder_with_virtual_references(self):
url = '/api/file/browse'
headers = self.headers('alice')
response = self.client.get(url, headers=headers)
self.assertEqual(response.status_code, 200)
self.assertTrue(response.cache_control.no_store)
self.assertEqual(response.get_json(), {
'root': '/',
'dirs': ['nested'],
'files': [{'name': 'movie.mp4', 'size': 5, 'ref': '/movie.mp4'}],
})
response = self.client.get(url, query_string={'path': '/nested'}, headers=headers)
self.assertEqual(response.status_code, 200)
self.assertEqual(response.get_json(), {
'root': '/nested',
'dirs': [],
'files': [{'name': 'other.mp4', 'size': 5, 'ref': '/nested/other.mp4'}],
})
with tempfile.TemporaryDirectory(prefix='Clips & 100% café ', dir=self.root / 'alice') as empty:
virtual = '/' + Path(empty).name
response = self.client.get(url, query_string={'path': virtual}, headers=headers)
self.assertEqual(response.status_code, 200)
self.assertEqual(response.get_json(), {'root': virtual, 'dirs': [], 'files': []})
def test_browse_requires_a_current_enabled_account_and_assignment(self):
url = '/api/file/browse'
self.assertEqual(self.client.get(url).status_code, 401)
for account, status in [('disabled', 401), ('empty', 403), ('admin', 403)]:
with self.subTest(account=account):
self.assertEqual(self.client.get(url, headers=self.headers(account)).status_code, status)
self.client.patch(f'/api/user/{self.alice_id}', json={'root': '/bob'}, headers=self.headers('admin'))
response = self.client.get(url, headers=self.headers('alice'))
self.assertEqual(response.get_json(), {'root': '/', 'dirs': [], 'files': []})
self.client.patch(f'/api/user/{self.alice_id}', json={'root': None}, headers=self.headers('admin'))
self.assertEqual(self.client.get(url, headers=self.headers('alice')).status_code, 403)
def test_browse_keeps_navigation_inside_the_assigned_root(self):
url = '/api/file/browse'
headers = self.headers('alice')
for path in ['', 'nested', '//nested', '/nested/', '/nested/.', '/nested/..']:
with self.subTest(path=path):
response = self.client.get(url, query_string={'path': path}, headers=headers)
self.assertEqual(response.status_code, 400)
for path in ['/bob', '/sibling', '/escape', '/movie.mp4']:
with self.subTest(path=path):
response = self.client.get(url, query_string={'path': path}, headers=headers)
self.assertEqual(response.status_code, 404)
self.assertEqual(response.get_json()['message'], 'Folder unavailable')
def test_browse_reports_unavailable_media_without_path_details(self):
url = '/api/file/browse'
headers = self.headers('alice')
with patch('media.os.scandir', side_effect=OSError('Internal storage detail')):
response = self.client.get(url, headers=headers)
self.assertEqual(response.status_code, 503)
self.assertEqual(response.get_json()['message'], 'Media unavailable')
app.config['MEDIA_ROOT'] = str(self.root / 'unavailable')
response = self.client.get(url, headers=headers)
self.assertEqual(response.status_code, 503)
self.assertNotIn(str(self.root), response.get_data(as_text=True))
def test_old_download_never_serves_files(self):
for payload in [{'path':str(self.root / 'alice'),'filename':'movie.mp4'}, {'path':'/etc','filename':'passwd'}, {}, None]:
self.assertEqual(self.client.post('/api/file',json=payload,headers=self.headers('alice')).status_code,410)
self.assertEqual(self.client.post('/api/file',json={}).status_code,401)
def test_input_and_privilege_escalation(self):
for payload in [{'is_admin':True}, {'login_disabled':'false'}, {'root':{}}, []]:
self.assertEqual(self.client.patch(f'/api/user/{self.alice_id}',json=payload,headers=self.headers('admin')).status_code,400)
self.assertEqual(self.client.post('/api/user',json={'username':'new','password':'pw','is_admin':True},headers=self.headers('admin')).status_code,400)
self.assertEqual(self.client.post('/api/user',json={'username':'new','password':'pw'},headers=self.headers('admin')).status_code,200)
self.assertFalse(User.query.filter_by(username='new').first().is_admin)
self.assertEqual(self.client.get('/api/user/99999',headers=self.headers('admin')).status_code,404)
if __name__ == '__main__':
unittest.main()
+27 -4
View File
@@ -1,8 +1,8 @@
# Foldershare current state # Foldershare current state
- Updated: 2026-11-04 - Updated: 2026-11-25 for TASK-003 acceptance and integration
- Inspected worktree: `/home/rob/projects/foldershare` - Inspected worktree: `/home/rob/projects/foldershare/.worktrees/TASK-003`
- Branch and HEAD at inspection: `codex` at `767b424` - TASK-003 base: `codex` at `549f11d`
## Verified repository state ## Verified repository state
@@ -15,7 +15,7 @@ This reconciliation adds Context System 1.0 and Workflow 2.0 documentation only.
- TASK-001 is Complete. Captain accepted the snapshot script on 2026-11-04 after running it from the project root. The script writes ZIPs to ignored `docs/snapshots/`; `.worktrees/` is also ignored. - TASK-001 is Complete. Captain accepted the snapshot script on 2026-11-04 after running it from the project root. The script writes ZIPs to ignored `docs/snapshots/`; `.worktrees/` is also ignored.
- No application tests, lint, build, or runtime checks were run as part of this documentation reconciliation. - No application tests, lint, build, or runtime checks were run as part of this documentation reconciliation.
- Captain approved TASK-001's branch/worktree convention. Future-task, general merge, and release conventions remain pending in `DECISIONS.md`. - Captain approved TASK-001's branch/worktree convention. Future-task, general merge, and release conventions remain pending in `DECISIONS.md`.
- No manual-test/testtask adapter was found in tracked repository files. - The initial reconciliation predated the manual-test adapter.
## Known limitations of this record ## Known limitations of this record
@@ -34,3 +34,26 @@ These observations are based on the supplied ZIP source, **not runtime exploit t
- Tests and production deployment are still unverified. The ZIP is not a live Git repository; its HEAD/branch are historical snapshot metadata. - Tests and production deployment are still unverified. The ZIP is not a live Git repository; its HEAD/branch are historical snapshot metadata.
No source-code security fixes or runtime validation are part of this reconciliation patch. No source-code security fixes or runtime validation are part of this reconciliation patch.
## TASK-002 authorization and filesystem boundaries
Captain accepted TASK-002 on 2026-11-07 and authorized its local integration into `codex` on 2026-11-25. These verified changes supersede the corresponding snapshot observations above.
- User mutations require an admin. Disabled accounts are denied Basic, access-token and refresh authentication. Disabling an account revokes its credentials. A missing user detail returns 404 and an invalid refresh identity returns 401.
- The media helper validates virtual assigned roots and uses directory descriptors to keep listings within those roots, excluding symlinks. `GET /api/file/root` is admin-only and returns virtual paths. The old download route returns 410.
- Login issues access tokens on first sign-in and after logout, and the login and refresh responses agree on user identity. The Users page now shows loading, empty and request-error states.
- The authentication checks require `login_disabled = false`. Rows left `NULL` by the old nullable migration are denied authentication. Existing invalid or host-absolute folder assignments require admin reassignment to virtual paths. TASK-002 includes no data migration, and local account and assignment data were not inspected.
- On 2026-11-25, all ten API tests passed with disposable SQLite and media fixtures. Python syntax checks, frontend production build and diff checks passed. Frontend lint could not run because ESLint configuration is missing. Python datetime and Sass deprecation warnings remain.
- TASK-003 covers ordinary-user browsing, TASK-004 covers download grants and resume, and TASK-005 covers the rest of the admin workflow. Target-Pi deployment and cookie/TLS configuration remain unverified. TASK-007 records the manual-test adapter separately.
## TASK-003 assigned-folder browsing
- Implemented in `task/TASK-003-secure-browsing`. Captain accepted the task and authorized its local integration into `codex` on 2026-11-25.
- Signed-in users can browse within their current assigned root. The homepage renders folder navigation, file metadata, and distinct messages for empty, unassigned and unavailable media. The admin folder picker continues to use the admin-only root API. Stored assignments are omitted from the sign-in response.
- The API returns one directory at a time and verifies the current assignment on each call. The server reports a missing media root or storage I/O errors as unavailable. Detecting a disconnected mount that still looks like a readable local directory requires deployment-level mount checks under TASK-006.
- All 15 API tests, Python syntax, production build and diff checks passed. Frontend lint is still blocked by the absent ESLint configuration. Chromium exercised the isolated snapshot at 1280 × 800 and 375 × 812. The existing header references a missing `/logo.png` asset in both views.
- The TASK-007 adapter produced and verified the snapshot. Its readiness HTTP check timed out on concurrent cold frontend and browser startup, so the successful QA run delayed the adapter's Firefox launch. The candidate passed Chromium browser QA and the disposable session cleaned up. The TASK-003 snapshot was absent at integration preflight.
## TASK-007 isolated manual testing
Captain accepted the graphical Firefox test with TASK-002 on 2026-11-25. The adapter verified snapshot hashes and HTTP readiness. Shutdown removed the owned snapshot. All six adapter tests passed. The integrated entry point is `./scripts/testtask.sh NNN`. See `scripts/README.md` for prerequisites and the session lifecycle.
+33
View File
@@ -68,3 +68,36 @@ Until approved, brief the concrete convention choice before creating later task
## Pending: Git integration branch convention ## Pending: Git integration branch convention
The 2026-11-04 snapshot references work on `codex` while the existing proposal suggests `main`. There is no evidence that a general integration branch choice was approved. Before creating a task worktree, Codex must inspect live Git state and ask Captain to approve the integration base, worktree path, and eventual merge destination. A task branch is not authority to merge or deploy. The 2026-11-04 snapshot references work on `codex` while the existing proposal suggests `main`. There is no evidence that a general integration branch choice was approved. Before creating a task worktree, Codex must inspect live Git state and ask Captain to approve the integration base, worktree path, and eventual merge destination. A task branch is not authority to merge or deploy.
## WF-003: TASK-002 implementation location
- Status: Accepted by Captain's “engage task-002” response to the concrete proposal, 2026-11-04.
- Use `codex` at `cd6d6b3` as TASK-002 base and intended merge destination, branch `task/TASK-002-authorization`, worktree `.worktrees/TASK-002`.
- This approves TASK-002 only. Merge/deployment authority remains with Captain; future-task/release conventions remain pending. The earlier main-base proposal is not used for this task.
## TASK-002 API/security implementation contract
- Implements PRD-002: stored assigned roots are virtual `/` or `/folder/descendant`, relative to configured `ROOT_PATH`; `null` grants no access. Existing malformed/host-absolute assignments fail closed and require admin reassignment. No automatic conversion of old assignments.
- Symlinks inside the media tree are omitted/rejected entirely (including links within the tree). Descriptor-relative directory opens with `O_NOFOLLOW` prevent listing redirection during link swaps; Linux/Pi is the target runtime.
- Admin `GET /api/file/root` retains tree entries `{root, dirs, files}` with virtual roots, filename/size metadata; unavailable media returns generic 503. The model's user listing rebases its assigned directory to `/` and returns `[]` when unassigned/invalid/unavailable. TASK-003 supplies the user-facing browse route/UI.
- `POST /api/file` returns authenticated 410 without reading its payload or filesystem until TASK-004 replaces downloads with authorized grants. Anonymous requests remain 401.
- User POST/PATCH/DELETE require admin (authenticated non-admin 403); POST accepts username/password only, PATCH root/login_disabled only with validated types. Disabled/missing users cannot use Basic/access/refresh authentication; disabling revokes credentials so re-enabling does not restore them.
- `FOLDERSHARE_DATABASE_URI` optionally overrides SQLite configuration for isolated tests; default database remains unchanged. `ROOT_PATH` still configures media, resolved from process working directory at startup.
## WF-004: TASK-003 implementation location
- Captain engaged the briefed task from `codex` at `549f11d`, using branch `task/TASK-003-secure-browsing` and worktree `.worktrees/TASK-003`.
## TASK-003 browse API contract
- `GET /api/file/browse?path=/folder` uses bearer authentication. The `path` query value defaults to `/` and is relative to the current user's assigned root. This applies to admin accounts on the browsing endpoint as well. The admin-only `GET /api/file/root` retains the existing assignable tree and response shape.
- Success returns `{root, dirs, files}` for the requested folder's direct children. `root` is the requested virtual path. `dirs` contains directory names. `files` contains `{name, size, ref}` entries with byte sizes and slash-delimited virtual references such as `/folder/video.mp4`. The client URL-encodes the query value once. The server resolves the assigned root and requested directory on each call without following symlinks. Success responses specify `Cache-Control: no-store`.
- The endpoint returns 401 for invalid authentication, 403 for a missing or unusable assignment, 400 for invalid virtual path structure, 404 for a folder missing within the assignment, and 503 for unavailable media or storage errors. A readable empty folder returns 200 with empty arrays. Sign-in omits the stored assignment from the session payload.
- TASK-004 may use `ref` as a file reference in its grant request body. The download-grant endpoint must recheck current ownership, containment and file existence. The opaque download URL follows PRD-003.
## WF-005: TASK-007 testtask implementation
- Accepted by Captain on 2026-11-05: codex base at cd6d6b3, task/TASK-007-testtask, .worktrees/TASK-007. Merge and deployment remain Captain authority.
- Use the existing standalone roborto-testtask engine with a project adapter. Safe source copies are disposable testing snapshots, not Git checkouts or development sources. The adapter discovers a unique checked-out task/TASK-###-* branch and includes current tracked/permitted untracked source.
- Flask/Vite bind only 127.0.0.1:5502/5503, with an isolated Vite proxy. Reuse existing dependency installations without installs or runtime source changes. Mutable Vite cache goes into run state.
- SQLite, accounts and sample media are generated per session; no live state is copied. Candidate must support FOLDERSHARE_DATABASE_URI. No application code is patched to make the harness work.
+19 -14
View File
@@ -1,26 +1,31 @@
# Foldershare handoff # Foldershare handoff
This is a replaceable snapshot. Live repository/Git and maintained context take precedence. Updated 2026-11-25. **TASK-003 is Complete.** Captain accepted the task and authorized a local commit and merge into `codex`.
- Updated: 2026-11-04 (planning reconciliation from `foldershare-20261104-160824-012796.zip`) The implementation came from `.worktrees/TASK-003` on `task/TASK-003-secure-browsing`, based on `codex` at `549f11d`. It adds assigned-folder browsing, preserves the admin-only picker, and publishes virtual file references for TASK-004. See `DECISIONS.md` for the API contract.
- Snapshot documents report `codex` / `767b424` at the earlier inspection; live Git worktree, branch, status and HEAD **have not been checked** in this archive-only reconciliation.
- Files changed by patch: `docs/PROJECT_OVERVIEW.md`, `docs/DECISIONS.md`, `docs/CURRENT_STATE.md`, `docs/TASKS.md`, `docs/HANDOFF.md` only. No application code, no tests executed, no merge or deployment.
## Current outcome ## Repeatable browser check
Captain defined FolderShare as a private Pi-hosted, read-only browser/download service for named friends. V1: single assigned root per user, admin-controlled accounts, browse and single-file download using opaque filename-free URLs. Future: multi-select ZIP downloads. The patch records PRD-001 through PRD-004 and DEP-001, plus TASK-002 through TASK-006; security/auth fixes must precede exposure. From the primary repository root, launch the exact candidate with the integrated TASK-007 adapter. Both loopback ports 5502 and 5503 must be free.
## Major static-source risks to address ```bash
PATH="$HOME/.local/bin:$PATH" ./scripts/testtask.sh 003
```
`POST /api/file` trusts client path; user mutation routes lack admin checks; listing exposes host paths; download click is not wired; token/disabled behavior needs tests. See `CURRENT_STATE.md`. Do not expose this snapshot implementation to untrusted users. Choose Firefox and use the disposable accounts and password printed by the launcher at `http://127.0.0.1:5503/`. The adapter starts with `sample.txt` at the assigned root. To exercise nested and empty-folder navigation, add fixtures in a second terminal from the primary root after the adapter reports readiness.
## Next Codex action ```bash
task_run=$(cat .test-worktrees/task-003/.testtask-owner) &&
mkdir -p -- "$task_run/media/friends/Series/Season 1" "$task_run/media/friends/Empty" &&
printf 'Disposable QA fixture\n' > "$task_run/media/friends/Series/Season 1/episode.txt"
```
1. In the **live repository**, read AGENTS/context documents and inspect branch, HEAD, git status, worktrees and existing changes before applying this patch. Check patch with `git apply --check`; do not overwrite later edits. 1. Sign in as `friend`. Open `Series`, then `Season 1`. Check that the file appears, use the breadcrumb and parent button, then open `Empty` and confirm the empty message.
2. Apply documentation-only patch, review diff and report conflicts. Do **not** quietly replace newer state or start any implementation task. 2. Sign in as `unassigned` and confirm the no-access message.
3. Ask Captain to select TASK-002 as first implementation task and approve concrete integration branch/worktree conventions (live `codex` vs proposal `main`). Keep TASK-006 blocked pending remote access and target Pi choice. 3. Sign in as `captain`, open **Users**, select `friend`, and verify that the assignable-folder tree opens at the assigned folder and navigates back to the media root.
4. Once authorized, create one isolated worktree for TASK-002, implement/test there, and submit a Captain-validation handoff. Do not merge or deploy without authority.
Stop the owned test session using Ctrl-C in its terminal. The adapter removes the disposable snapshot and fixtures. A new run captures the current task changes.
## Validation ## Validation
Patch was generated from the exact supplied ZIP. No live Git or application validation can be claimed from the archive alone. All 15 API tests, Python syntax, production frontend build and whitespace checks passed again before integration. The build and tests retain existing Sass and datetime deprecation warnings. ESLint configuration is absent. Headless Chromium previously verified the disposable candidate at widths of 1280 and 375 pixels, including keyboard navigation, share outage and retry, a removed folder, unassigned access, and admin folder navigation. The header's existing `/logo.png` asset is missing. The adapter's cold startup can time out while Vite and Firefox start together. Agent QA delayed Firefox startup and verified adapter readiness and cleanup. Captain separately accepted TASK-007 after the graphical TASK-002 test on 2026-11-25.
+7 -3
View File
@@ -1,6 +1,6 @@
# Foldershare project overview # Foldershare project overview
Stable facts here are based on repository source and configuration as inspected on 2026-11-04. This is not a runtime or deployment verification record. Stable facts here are based on repository source and configuration. Runtime and deployment evidence belongs in `CURRENT_STATE.md`.
## Product and architecture ## Product and architecture
@@ -17,8 +17,8 @@ The repository contains a folder-sharing web application. `react/` is a React 18
- `react/package.json` defines `npm run dev`, `npm run build`, `npm run lint`, and `npm run preview`. - `react/package.json` defines `npm run dev`, `npm run build`, `npm run lint`, and `npm run preview`.
- `react/vite.config.js` defines the development API proxy. - `react/vite.config.js` defines the development API proxy.
- `api/config/requirements.txt` lists Python dependencies. No repository-defined API test command or test suite is tracked. - `api/config/requirements.txt` lists Python dependencies. Run `python -m unittest discover -s api/tests -v` from the repository root with the API environment to exercise the tracked API regression suite.
- No tracked CI, container, deployment, Git workflow, or manual-test/testtask documentation was found during reconciliation. - No tracked CI, container or deployment configuration was found during initial reconciliation. The installed manual-test adapter is described below.
- Existing UI styling references are `react/src/styles/` and component `*.module.scss` files; no separate style guide is tracked. - Existing UI styling references are `react/src/styles/` and component `*.module.scss` files; no separate style guide is tracked.
Local environment files and runtime data under `api/` are ignored by Git. Their contents are not part of this overview. Local environment files and runtime data under `api/` are ignored by Git. Their contents are not part of this overview.
@@ -33,3 +33,7 @@ Local environment files and runtime data under `api/` are ignored by Git. Their
## Product direction accepted 2026-11-04 (requirements; not verified implementation) ## Product direction accepted 2026-11-04 (requirements; not verified implementation)
FolderShare is intended as a private, read-only, authenticated file browser and downloader for selected friends, hosted on a Raspberry Pi on Captain's LAN. The Pi will access an existing video library through a shared/mounted folder. Captain administers accounts and each account's accessible folder. An intended hostname is `share.roborto.net` (subject to DNS/network-access design). V1 permits browsing and single-file downloads; multi-select file/folder ZIP downloads are deferred. These are product requirements, not claims that the current application implements them safely. FolderShare is intended as a private, read-only, authenticated file browser and downloader for selected friends, hosted on a Raspberry Pi on Captain's LAN. The Pi will access an existing video library through a shared/mounted folder. Captain administers accounts and each account's accessible folder. An intended hostname is `share.roborto.net` (subject to DNS/network-access design). V1 permits browsing and single-file downloads; multi-select file/folder ZIP downloads are deferred. These are product requirements, not claims that the current application implements them safely.
## Manual testing adapter
`scripts/testtask.sh`, `.roborto/testtask.conf` and `.roborto/testtask-hook` adapt the installed `roborto-testtask` engine using `scripts/testtask_adapter.py`. The adapter uses disposable source copies, SQLite/accounts/media and loopback Flask/Vite services. See `scripts/README.md`; existing local Python/Node installations are prerequisites, not bundled dependencies.
+23 -2
View File
@@ -35,7 +35,7 @@ The scopes below translate Captain's explicit product requirements into implemen
### TASK-002: Enforce authorization and safe filesystem boundaries ### TASK-002: Enforce authorization and safe filesystem boundaries
- Status: Accepted; not started. **Release blocker; first implementation priority.** - Status: Complete — Captain accepted on 2026-11-07 with “task complete”, following manual testing.
- Objective: Make user management and media access deny-by-default, including existing endpoints. - Objective: Make user management and media access deny-by-default, including existing endpoints.
- Scope: Require admin for create/update/delete user; block privilege escalation and self-service root changes; ensure disabled/deleted accounts cannot keep using access/refresh credentials; centralize server-side canonical media root/assigned-root containment; reject path traversal, symlinks escaping the media tree, malformed roots and missing files; remove client-controlled download path trust or disable old route pending TASK-004; ensure no server absolute paths leak in ordinary browsing responses. - Scope: Require admin for create/update/delete user; block privilege escalation and self-service root changes; ensure disabled/deleted accounts cannot keep using access/refresh credentials; centralize server-side canonical media root/assigned-root containment; reject path traversal, symlinks escaping the media tree, malformed roots and missing files; remove client-controlled download path trust or disable old route pending TASK-004; ensure no server absolute paths leak in ordinary browsing responses.
- Non-goals: New media UI, multi-root authorization, ZIP downloads or internet deployment. - Non-goals: New media UI, multi-root authorization, ZIP downloads or internet deployment.
@@ -44,10 +44,13 @@ The scopes below translate Captain's explicit product requirements into implemen
- Dependencies: Verify live config/runtime behavior and decide API response contract. Retain one-root permission model (PRD-002). - Dependencies: Verify live config/runtime behavior and decide API response contract. Retain one-root permission model (PRD-002).
- Validation: API syntax/import check, automated endpoint/path-security tests with temporary fixtures and user roles, inspect returned error messages for path leaks. Review diff; no real media used in tests. - Validation: API syntax/import check, automated endpoint/path-security tests with temporary fixtures and user roles, inspect returned error messages for path leaks. Review diff; no real media used in tests.
- Recommended specialist: Webapp Debug followed by Webapp Feature and Code Review. - Recommended specialist: Webapp Debug followed by Webapp Feature and Code Review.
- Implementation: Admin checks on user mutations, disabled-account checks and credential revocation, descriptor-anchored virtual media listings, and HTTP 410 for the old download route. Login now issues a usable access token on first sign-in and after logout, with a `user_id` matching the refresh response. Admin user detail labels identify the username and assigned folder, and the Users page reports loading, empty and error states. No database migration was added.
- Validation on 2026-11-25: Ten API tests with temporary SQLite and media fixtures, Python syntax checks, frontend production build and diff checks passed. Frontend lint could not run because the repository lacks ESLint configuration. Python datetime and Sass deprecation warnings remain.
- Captain acceptance: 2026-11-07. Confirmed that a disabled friend could not sign in and an enabled friend could. Ordinary-user browsing remains TASK-003. On 2026-11-25, Captain authorized committing and merging TASK-002 into its documented destination, `codex`.
### TASK-003: Secure folder browsing for assigned users ### TASK-003: Secure folder browsing for assigned users
- Status: Accepted; not started. - Status: Complete. Captain accepted TASK-003 on 2026-11-25 and authorized the local commit and merge into `codex`.
- Objective: Provide a usable browser rooted in each user's authorized directory without exposing real server paths. - Objective: Provide a usable browser rooted in each user's authorized directory without exposing real server paths.
- Scope: Replace/adjust browsing API to return virtual paths or opaque IDs, list only authorized child folders/files and their safe metadata; wire navigation/breadcrumbs, empty/error states, and denied/unavailable-share behavior. Retain existing visual patterns unless specifically approved to redesign. - Scope: Replace/adjust browsing API to return virtual paths or opaque IDs, list only authorized child folders/files and their safe metadata; wire navigation/breadcrumbs, empty/error states, and denied/unavailable-share behavior. Retain existing visual patterns unless specifically approved to redesign.
- Non-goals: Upload, rename, delete, global search, multiple roots, ZIP selection. - Non-goals: Upload, rename, delete, global search, multiple roots, ZIP selection.
@@ -56,6 +59,8 @@ The scopes below translate Captain's explicit product requirements into implemen
- Dependencies: TASK-002 shared authorization utilities; API shape documented during task. - Dependencies: TASK-002 shared authorization utilities; API shape documented during task.
- Validation: API tests plus `npm run lint`, `npm run build`, manual navigation for admin/standard/no-root users. - Validation: API tests plus `npm run lint`, `npm run build`, manual navigation for admin/standard/no-root users.
- Recommended specialist: Webapp Feature, Frontend Visual QA, Code Review. - Recommended specialist: Webapp Feature, Frontend Visual QA, Code Review.
- Implementation: Authenticated one-folder listings use the current assignment as `/`. The homepage provides breadcrumbs, parent navigation, and loading, empty, no-access, unavailable and retry states. The admin-only folder picker retains its separate tree. See `DECISIONS.md` for virtual file references and API statuses.
- Evidence: All 15 API tests, Python syntax, production build, and diff checks passed again before integration on 2026-11-25. Chromium previously verified keyboard navigation, responsive desktop and mobile layouts, share failure and recovery, unassigned access, and the admin picker using the exact task snapshot. Lint could not run because ESLint configuration is absent.
### TASK-004: Opaque single-file downloading with resume ### TASK-004: Opaque single-file downloading with resume
@@ -96,3 +101,19 @@ The scopes below translate Captain's explicit product requirements into implemen
## Future feature concept (no numbered task yet) ## Future feature concept (no numbered task yet)
- Batch file/folder selection and prepared or streamed ZIP download (PRD-004). Scope a task only when Captain schedules it. ZIP entries must reuse V1 path/permission protections; no compression-heavy default for large existing videos. - Batch file/folder selection and prepared or streamed ZIP download (PRD-004). Scope a task only when Captain schedules it. ZIP entries must reuse V1 path/permission protections; no compression-heavy default for large existing videos.
## TASK-007: Configure testtask
- Status: Complete. Captain confirmed the graphical test worked on 2026-11-25 and authorized commit and merge into codex.
- Objective: Make the installed roborto-testtask engine usable for isolated FolderShare manual testing.
- Scope: Wrapper, engine configuration, project lifecycle hook, exact safe snapshots of checked-out task branches including uncommitted/permitted untracked files, disposable SQLite/accounts/media, loopback Flask/Vite services, readiness, cleanup and documentation.
- Non-goals: Application changes, copying live databases/media/secrets, dependency installation, containerization, merge or deployment; do not modify TASK-002.
- Acceptance: One documented command prepares TASK-002, verifies snapshot hashes, starts isolated API/frontend, passes HTTP smoke checks, prints disposable credentials, and removes only owned state on exit. Repeated runs work; occupied ports and existing snapshots fail safely; malformed IDs/unknown sources are rejected. Captain manual browser validation required.
- Dependencies: Installed roborto-testtask, Firefox, Python API environment, Node >=18 and existing react/node_modules; candidate must support FOLDERSHARE_DATABASE_URI (TASK-002).
- Branch/worktree: Captain approved codex base, task/TASK-007-testtask and .worktrees/TASK-007. Captain authorized local integration into codex on 2026-11-25.
- Risks: Snapshot omissions, stale source, secret inclusion, unsafe cleanup, port conflicts and dependency drift. Use hash manifests, exclusions, ownership markers and loopback binding.
- Validation: Shell/Python syntax, adapter safety tests and engine lifecycle smoke using TASK-002; record graphical-browser limitations honestly.
- Specialist: Roborto Project Context and Webapp Feature; bounded diff review.
- TASK-007 evidence: Six adapter safety tests pass; shell/Python syntax and diff checks pass. Repeated real-server lifecycle runs pass, including headless Firefox startup, frontend/API HTTP readiness, proxy logins and disabled-login denial; snapshots removed on exit. Occupied-port refusal preserves an unrelated listener. The adapter uses existing dependencies and leaves the source application intact.
- Captain accepted the graphical Firefox run using TASK-002. Six adapter tests passed again and the owned snapshot was removed on shutdown.
+102 -160
View File
@@ -1,199 +1,141 @@
import { useState, useEffect } from "react"; import { useState } from "react";
import styles from "./FileBrowser.module.scss"; import styles from "./FileBrowser.module.scss";
import { ListGroup, Breadcrumb } from "react-bootstrap"; import { ListGroup, Breadcrumb } from "react-bootstrap";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { import { faFolder, faFile, faFileVideo, faSquare, faSquareCheck } from "@fortawesome/free-solid-svg-icons";
faFolder,
faFile,
faFileVideo,
faDownload,
faSquare,
faSquareCheck,
} from "@fortawesome/free-solid-svg-icons";
const videoExtensions = ["mkv", "avi", "mp4"]; const videoExtensions = ["mkv", "avi", "mp4"];
const apiBaseUrl = "http://localhost:5173";
const FileIcon = ({ fileName }) => const FileIcon = ({ fileName }) => (
videoExtensions.some((ext) => fileName.endsWith(`.${ext}`)) ? ( <FontAwesomeIcon
<FontAwesomeIcon icon={faFileVideo} className={styles.icon} /> icon={videoExtensions.some((ext) => fileName.endsWith(`.${ext}`)) ? faFileVideo : faFile}
) : ( />
<FontAwesomeIcon icon={faFile} className={styles.icon} /> );
);
const FileSize = ({ file }) => ( const FileSize = ({ size }) => (
<div className={styles.size}> <div className={styles.size}>
{parseInt(file.size / (1024 * 1024))} {Math.floor(size / (1024 * 1024))}
<span>MB</span> <span>MB</span>
</div> </div>
); );
const FileBrowser = ({ const FileBrowser = ({ path, folder, onNavigate, assignedPath, onSetRootFolder, onUnsetRootFolder, children }) => {
tree, const segments = path === "/" ? [] : path.slice(1).split("/");
defaultPath, const breadcrumbs = [
onDownloadFile, { name: "Shared Folder", target: "/" },
onSetRootFolder, ...segments.map((name, index) => ({
onUnsetRootFolder name,
}) => { target: `/${segments.slice(0, index + 1).join("/")}`,
const [currentPath, setCurrentPath] = useState(null); })),
];
const isUserRoot = () => { const parent = breadcrumbs.at(-2);
return true;
};
console.log(currentPath, defaultPath, tree);
useEffect(() => {
if (!currentPath && tree) {
if (defaultPath) {
setCurrentPath(tree.find((p) => p.root === defaultPath));
} else if (tree.length) {
setCurrentPath(tree[0]);
}
}
}, [tree, currentPath, defaultPath]);
const handleSelectParentFolder = () => {
const pathArray = currentPath.root.split("/");
pathArray.pop();
const path = tree.find(
(f) =>
f.root === (pathArray.length == 1 ? "/" : pathArray.join("/"))
);
setCurrentPath(path);
};
const getDirPath = (dir) =>
tree.find(
(f) =>
f.root ===
`${currentPath.root}${
currentPath.root === "/" ? "" : "/"
}${dir}`
);
const handleSelectFolder = (dir) => {
const path = getDirPath(dir);
if (path) {
setCurrentPath(path);
}
};
const handleSelectFolderByDepth = (depth) => {
const newPath = `/${currentPath.root
.split("/")
.slice(1, depth + 1)
.join("/")}`;
const path = tree.find((f) => f.root === newPath);
setCurrentPath(path);
};
return ( return (
<div className={styles.fileBrowser}> <div className={styles.fileBrowser}>
<Breadcrumb> <Breadcrumb label="Folder path">
<Breadcrumb.Item {breadcrumbs.map(({ name, target }) => (
active={currentPath?.root === "/"} <Breadcrumb.Item
onClick={() => handleSelectFolderByDepth(0)} key={target}
> active={target === path}
Shared Folder linkAs="button"
</Breadcrumb.Item> linkProps={{
{currentPath?.root.split("/").map((bc, index) => type: "button",
index > 0 ? ( className: `btn btn-link p-0 align-baseline ${styles.breadcrumbButton}`,
<Breadcrumb.Item onClick: () => onNavigate(target),
key={index} }}
active={ >
index === {name}
currentPath?.root.split("/").length - 1 </Breadcrumb.Item>
} ))}
onClick={() => handleSelectFolderByDepth(index)}
>
{bc}
</Breadcrumb.Item>
) : (
""
)
)}
</Breadcrumb> </Breadcrumb>
<ListGroup className={styles.fileList}> {children}
{tree && currentPath?.root !== tree[0].root && ( <ListGroup>
{parent && (
<ListGroup.Item <ListGroup.Item
action action
onClick={handleSelectParentFolder} type="button"
onClick={() => onNavigate(parent.target)}
className={styles.listItem} className={styles.listItem}
aria-label="Parent folder"
> >
.. ..
</ListGroup.Item> </ListGroup.Item>
)} )}
{folder?.dirs.map((name) => {
{currentPath?.dirs?.map((dir, index) => { const target = `${path === "/" ? "" : path}/${name}`;
const isSelected = getDirPath(dir).root === defaultPath; const isAssigned = target === assignedPath;
const label = (
<>
<FontAwesomeIcon icon={faFolder} />
<span className={styles.name}>{name}</span>
</>
);
if (onSetRootFolder) {
return (
<ListGroup.Item
className={`${styles.listItem} ${isAssigned ? styles.selected : ""}`}
variant="dark"
key={name}
>
<button
type="button"
className={styles.folderButton}
onClick={() => onNavigate(target)}
>
{label}
</button>
<button
type="button"
className={styles.assignmentButton}
aria-label={isAssigned ? `Unassign ${name}` : `Assign ${name}`}
onClick={isAssigned ? onUnsetRootFolder : () => onSetRootFolder(target)}
>
<FontAwesomeIcon icon={isAssigned ? faSquareCheck : faSquare} />
</button>
</ListGroup.Item>
);
}
return ( return (
<ListGroup.Item <ListGroup.Item
action action
className={`${styles.listItem} ${styles.dir} ${ type="button"
isSelected ? styles.selected : "" className={styles.listItem}
}`} onClick={() => onNavigate(target)}
onClick={() => handleSelectFolder(dir)}
variant="dark" variant="dark"
key={index} key={name}
> >
<div className={styles.iconHolder}> {label}
<FontAwesomeIcon
icon={faFolder}
className={styles.icon}
/>
</div>
<div className={styles.name}>{dir}</div>
<div className={styles.action}>
{onSetRootFolder && isSelected && (
<FontAwesomeIcon
icon={faSquareCheck}
className={`${styles.icon} ${styles.setRoot}`}
onClick={(e) => onUnsetRootFolder(e)}
/>
)}
{onSetRootFolder && !isSelected && (
<FontAwesomeIcon
icon={faSquare}
className={`${styles.icon} ${styles.setRoot}`}
onClick={(e) =>
onSetRootFolder(
e,
currentPath.root,
dir
)
}
/>
)}
</div>
</ListGroup.Item> </ListGroup.Item>
); );
})} })}
{folder?.files.map((file) => (
{currentPath?.files?.map((file, index) => ( <ListGroup.Item className={styles.listItem} variant="secondary" key={file.name}>
<ListGroup.Item <FileIcon fileName={file.name} />
className={`${styles.listItem} ${styles.file}`} <span className={styles.name}>{file.name}</span>
variant="secondary" <FileSize size={file.size} />
key={index}
>
<div className={styles.iconHolder}>
<FileIcon fileName={file.name} />
</div>
<div className={styles.name}>{file.name}</div>
<div className={styles.action}>
<FileSize file={file} />
{onDownloadFile && (
<FontAwesomeIcon
icon={faDownload}
className={`${styles.icon} ${styles.dload}`}
/>
)}
</div>
</ListGroup.Item> </ListGroup.Item>
))} ))}
</ListGroup> </ListGroup>
{folder && folder.dirs.length === 0 && folder.files.length === 0 && (
<p className="mt-3" role="status">This folder is empty.</p>
)}
</div> </div>
); );
}; };
export const FolderTreeBrowser = ({ tree, assignedPath, onSetRootFolder, onUnsetRootFolder }) => {
const [path, setPath] = useState(assignedPath);
const folder = tree.find((entry) => entry.root === path) ?? tree[0];
return (
<FileBrowser
folder={folder}
path={folder.root}
assignedPath={assignedPath}
onNavigate={setPath}
onSetRootFolder={onSetRootFolder}
onUnsetRootFolder={onUnsetRootFolder}
/>
);
};
export default FileBrowser; export default FileBrowser;
@@ -1,47 +1,59 @@
@import "/src/styles/colors.scss"; @import "/src/styles/colors.scss";
.fileBrowser { .fileBrowser {
//background-color: map-get($theme-colors, primary);
padding-top: 30px; padding-top: 30px;
//border-radius: 5px; }
.fileList {
.listItem { .listItem,
display: flex; .folderButton {
flex-direction: row; display: flex;
gap: 20px; align-items: center;
.icon { gap: 20px;
&.dload, min-width: 0;
&.setRoot { }
cursor: pointer;
&:hover { .name {
color: #2d3dd4; flex: 1;
} min-width: 0;
} overflow: hidden;
} white-space: nowrap;
.name { text-overflow: ellipsis;
width: 100%; }
overflow: hidden;
white-space: nowrap; .size {
text-overflow: ellipsis; flex-shrink: 0;
}
.action { span {
width: 100px; margin-left: 5px;
display: flex;
justify-content: flex-end;
gap: 10px;
.size {
span {
margin-left: 5px;
}
}
}
&.selected {
background-color: map-get($theme-colors, primary);
}
}
.disabled {
pointer-events: none;
cursor: auto;
}
} }
} }
.folderButton,
.assignmentButton {
color: inherit;
background: none;
border: 0;
padding: 0;
}
.folderButton {
flex: 1;
text-align: left;
}
.assignmentButton:hover {
color: #2d3dd4;
}
.selected {
background-color: map-get($theme-colors, primary);
}
.fileBrowser :global(.breadcrumb-item) {
overflow-wrap: anywhere;
}
.breadcrumbButton {
text-align: left;
overflow-wrap: anywhere;
}
+29 -33
View File
@@ -1,5 +1,5 @@
/* eslint-disable react-refresh/only-export-components */ /* eslint-disable react-refresh/only-export-components */
import { createContext, useContext, useReducer, useEffect } from "react"; import { createContext, useContext, useReducer, useEffect, useCallback } from "react";
import PropTypes from "prop-types"; import PropTypes from "prop-types";
import { encode as base64_encode } from "base-64"; import { encode as base64_encode } from "base-64";
import { useLocalStorage } from "../hooks/useLocalStorage"; import { useLocalStorage } from "../hooks/useLocalStorage";
@@ -41,6 +41,21 @@ function reducer(state, action) {
} }
} }
function requestWithToken(url, token, options) {
if (!token) {
throw new Error("No bearer token");
}
return fetch(`${BASE_URL}/${url}`, {
...options,
credentials: "include",
headers: {
Authorization: `Bearer ${token}`,
"X-Requested-With": "XMLHttpRequest",
"Content-Type": "application/json",
},
});
}
function AuthProvider({ children }) { function AuthProvider({ children }) {
const [{ user, isAuthenticated, isLoading, error }, dispatch] = useReducer( const [{ user, isAuthenticated, isLoading, error }, dispatch] = useReducer(
reducer, reducer,
@@ -52,7 +67,7 @@ function AuthProvider({ children }) {
useEffect(() => { useEffect(() => {
const user = getLSItems(["user_id", "token", "username", "is_admin"]); const user = getLSItems(["user_id", "token", "username", "is_admin"]);
if (!!user.token && !!user.username) { if (!!user.token && !!user.username) {
dispatch({ type: "auth/login", payload: user }); dispatch({ type: "auth/login", payload: { ...user, is_admin: user.is_admin === "true" } });
} }
}, []); }, []);
@@ -89,31 +104,14 @@ function AuthProvider({ children }) {
dispatch({ type: "auth/logout" }); dispatch({ type: "auth/logout" });
} }
async function requestWithToken(url, token, options = {}) { const request = useCallback(async function request(url, options = {}, reauth = false) {
const headers = new Headers();
if (!token || token === "") {
throw new Error("No bearer token");
}
headers.append("authorization", `Bearer ${token}`);
headers.append("X-Requested-With", "XMLHttpRequest");
headers.append("Content-Type", "application/json");
const res = await fetch(
`${BASE_URL}/${url}`,
{
...options,
credentials: "include",
headers,
},
true
);
return res;
}
async function request(url, options = {}, reauth = false) {
let token = user.token; let token = user.token;
if (reauth) { if (reauth) {
const res = await fetch(`${BASE_URL}/auth/refresh`); const res = await fetch(`${BASE_URL}/auth/refresh`, { signal: options.signal });
const data = await res.json(); const data = await res.json();
if (options.signal?.aborted) {
throw options.signal.reason;
}
if ( if (
res.status == 400 && res.status == 400 &&
data.message === "Bad request, no refresh token" data.message === "Bad request, no refresh token"
@@ -131,18 +129,16 @@ function AuthProvider({ children }) {
} }
} }
const res = await requestWithToken(url, token, options); const res = await requestWithToken(url, token, options);
if (res.status == 401) { if (res.status === 401 && !reauth) {
if (reauth) {
throw new Error("Unauthorized");
}
return request(url, options, true); return request(url, options, true);
} }
if (!res.ok && !reauth) { if (!res.ok) {
throw new Error("Error fetching data"); const failure = new Error("Error fetching data");
failure.status = res.status;
throw failure;
} }
const data = await res.json(); return res.json();
return data; }, [user, navigate]);
}
return ( return (
<AuthContext.Provider <AuthContext.Provider
+56 -5
View File
@@ -1,19 +1,69 @@
import styles from "./Homepage.module.scss"; import styles from "./Homepage.module.scss";
import { useAuth } from "../../contexts/AuthContext"; import { useAuth } from "../../contexts/AuthContext";
import { useNavigate } from "react-router"; import { useNavigate } from "react-router";
import { useEffect } from "react"; import { useEffect, useState } from "react";
import { Container, Row, Col } from "react-bootstrap"; import { Alert, Button, Container, Row, Col } from "react-bootstrap";
import FileBrowser from "../../components/FileBrowser/FileBrowser"; import FileBrowser from "../../components/FileBrowser/FileBrowser";
const loadErrors = {
404: "This folder is no longer available.",
503: "The shared folder is temporarily unavailable.",
};
const AssignedFolderBrowser = ({ request }) => {
const [location, setLocation] = useState({ path: "/" });
const [result, setResult] = useState(null);
const current = result?.location === location ? result : null;
useEffect(() => {
const controller = new AbortController();
const query = new URLSearchParams({ path: location.path });
async function loadFolder() {
try {
const folder = await request(`file/browse?${query}`, { signal: controller.signal });
if (!controller.signal.aborted) {
setResult({ location, folder });
}
} catch (error) {
if (!controller.signal.aborted) {
setResult({ location, error });
}
}
}
loadFolder();
return () => controller.abort();
}, [location, request]);
if (current?.error?.status === 403) {
return <Alert variant="secondary" className="mt-4">You don’t have access to a shared folder.</Alert>;
}
return (
<FileBrowser path={location.path} folder={current?.folder} onNavigate={(path) => setLocation({ path })}>
{!current && <p role="status">Loading folder…</p>}
{current?.error && (
<Alert variant="danger">
{loadErrors[current.error.status] ?? "Unable to load this folder."}{" "}
<Button variant="link" className="p-0" onClick={() => setLocation({ path: location.path })}>
Try again
</Button>
</Alert>
)}
</FileBrowser>
);
};
const Homepage = () => { const Homepage = () => {
const { user } = useAuth(); const { user, request } = useAuth();
const navigate = useNavigate(); const navigate = useNavigate();
useEffect(() => { useEffect(() => {
if (!user) { if (!user) {
navigate("/login"); navigate("/login");
} }
}, [user]); }, [user, navigate]);
if (user) { if (user) {
return ( return (
@@ -21,13 +71,14 @@ const Homepage = () => {
<Container> <Container>
<Row> <Row>
<Col> <Col>
<FileBrowser /> <AssignedFolderBrowser key={user.user_id ?? user.username} request={request} />
</Col> </Col>
</Row> </Row>
</Container> </Container>
</main> </main>
); );
} }
return null;
}; };
export default Homepage; export default Homepage;
+21 -15
View File
@@ -1,22 +1,28 @@
import styles from "./User.module.scss"; import styles from "./User.module.scss";
import { useNavigate, useParams } from "react-router"; import { useNavigate, useParams } from "react-router";
import { useState, useEffect } from "react"; import { useState, useEffect } from "react";
import { Row, Col, Container, Button, Form } from "react-bootstrap"; import { Alert, Row, Col, Container, Button, Form } from "react-bootstrap";
import FileBrowser from "../../components/FileBrowser/FileBrowser"; import { FolderTreeBrowser } from "../../components/FileBrowser/FileBrowser";
import { useAPI } from "../../hooks/useAPI"; import { useAPI } from "../../hooks/useAPI";
const User = () => { const User = () => {
const [user, setUser] = useState(null); const [user, setUser] = useState(null);
const { get, patch, remove, isLoading } = useAPI(); const { get, patch, remove, isLoading } = useAPI();
const [rootPath, setRootPath] = useState(null); const [rootPath, setRootPath] = useState(null);
const [rootError, setRootError] = useState(false);
const { userId } = useParams(null); const { userId } = useParams(null);
const navigate = useNavigate() const navigate = useNavigate()
useEffect(() => { useEffect(() => {
const getRootPath = async () => { const getRootPath = async () => {
const rootPath = await get("file/root"); try {
if (rootPath) { const tree = await get("file/root");
setRootPath(rootPath); if (!Array.isArray(tree) || !tree.length) {
throw new Error("Invalid folder tree");
}
setRootPath(tree);
} catch {
setRootError(true);
} }
}; };
const getUser = async () => { const getUser = async () => {
@@ -29,17 +35,14 @@ const User = () => {
getRootPath(); getRootPath();
}, []); }, []);
const handleSetRootFolder = async (e, path, dir) => { const handleSetRootFolder = async (root) => {
e.stopPropagation();
const root = `${path}${path === "/" ? "" : "/"}${dir}`;
const patchedUser = await patch("user", userId, { root }); const patchedUser = await patch("user", userId, { root });
if (patchedUser) { if (patchedUser) {
setUser(patchedUser); setUser(patchedUser);
} }
}; };
const handleUnsetRootFolder = async (e) => { const handleUnsetRootFolder = async () => {
e.stopPropagation();
const patchedUser = await patch("user", userId, { root: null }); const patchedUser = await patch("user", userId, { root: null });
if (patchedUser) { if (patchedUser) {
setUser(patchedUser); setUser(patchedUser);
@@ -68,10 +71,10 @@ const User = () => {
<main> <main>
<Container> <Container>
<Row> <Row>
<Col>{user?.username}</Col> <Col><strong>Username:</strong> {user?.username}</Col>
</Row> </Row>
<Row> <Row>
<Col>{user?.root || "No root set"}</Col> <Col><strong>Assigned folder:</strong> {user?.root || "None — no media access"}</Col>
</Row> </Row>
<Row> <Row>
<Col> <Col>
@@ -96,10 +99,13 @@ const User = () => {
</Row> </Row>
<Row> <Row>
<Col> <Col>
{user && ( {user && rootError && <Alert variant="danger">Unable to load assignable folders.</Alert>}
<FileBrowser {user && !rootPath && !rootError && <p role="status">Loading assignable folders…</p>}
{user && rootPath && (
<FolderTreeBrowser
key={userId}
tree={rootPath} tree={rootPath}
defaultPath={user?.root} assignedPath={user.root}
onSetRootFolder={handleSetRootFolder} onSetRootFolder={handleSetRootFolder}
onUnsetRootFolder={handleUnsetRootFolder} onUnsetRootFolder={handleUnsetRootFolder}
/> />
+20 -1
View File
@@ -1,4 +1,5 @@
import { import {
Alert,
Col, Col,
Container, Container,
ListGroup, ListGroup,
@@ -22,7 +23,22 @@ const Users = () => {
const [addUserOpen, setAddUserOpen] = useState(false); const [addUserOpen, setAddUserOpen] = useState(false);
const [showPassword, setShowPassword] = useState(false); const [showPassword, setShowPassword] = useState(false);
const getUsers = () => get("user").then((users) => setUsers(users)); const [loadError, setLoadError] = useState("");
const [loadingUsers, setLoadingUsers] = useState(true);
const getUsers = async () => {
setLoadingUsers(true);
setLoadError("");
try {
const result = await get("user");
if (!Array.isArray(result)) throw new Error("Invalid user response");
setUsers(result);
} catch {
setLoadError("Unable to load users. Please log out and sign in again.");
} finally {
setLoadingUsers(false);
}
};
useEffect(() => { useEffect(() => {
getUsers(); getUsers();
@@ -106,6 +122,9 @@ const Users = () => {
</Row> </Row>
<Row> <Row>
<Col> <Col>
{loadingUsers && <p role="status">Loading users…</p>}
{loadError && <Alert variant="danger">{loadError}</Alert>}
{!loadingUsers && !loadError && users.length === 0 && <p>No users found.</p>}
<ListGroup> <ListGroup>
{users.map((user, index) => ( {users.map((user, index) => (
<ListGroupItem <ListGroupItem
+45
View File
@@ -9,3 +9,48 @@ python3 scripts/create_snapshot.py
The script writes a timestamped ZIP into `docs/snapshots/`. It includes the application source, `AGENTS.md`, `docs/`, and `scripts/`, including safe untracked files. It omits Git metadata, task worktrees, dependency directories, local environment files, local databases, shared files, caches, generated builds, prior snapshots, symlinks, and common key/credential files. The root `.gitignore` ignores `docs/snapshots/` and `.worktrees/`. The script writes a timestamped ZIP into `docs/snapshots/`. It includes the application source, `AGENTS.md`, `docs/`, and `scripts/`, including safe untracked files. It omits Git metadata, task worktrees, dependency directories, local environment files, local databases, shared files, caches, generated builds, prior snapshots, symlinks, and common key/credential files. The root `.gitignore` ignores `docs/snapshots/` and `.worktrees/`.
Inspect the ZIP contents before uploading it if you have added new local data or sensitive file types to the project. Inspect the ZIP contents before uploading it if you have added new local data or sensitive file types to the project.
## Manual task testing (`testtask`)
From the primary project root, run:
```sh
./scripts/testtask.sh 002
```
Supply the three-digit task number.
The adapter locates a unique checked-out `task/TASK-002-*` branch, captures its
current tracked changes and permitted untracked files, then starts an isolated
copy at http://127.0.0.1:5503 with API at 127.0.0.1:5502. Both ports must be free.
The candidate must support `FOLDERSHARE_DATABASE_URI` (provided by TASK-002).
Prerequisites: installed `roborto-testtask`, Firefox/display, existing Python API
venv and frontend node_modules in the primary worktree, and Node >=18. No packages
are installed automatically. Python defaults to primary `api/.venv/bin/python`;
set `FOLDERSHARE_TEST_PYTHON` to override. Node uses PATH, otherwise the latest
installed nvm version; set `FOLDERSHARE_TEST_NODE` to choose explicitly. Dependencies
are reused; this verifies the local environment, not a clean dependency install.
Choose Firefox at the prompt. The launcher prints fresh disposable credentials:
`captain` (admin), `friend` (assigned `/friends`), `unassigned`, and `disabled`
(which must fail login). Each run has a new shared test password. Only a generated
sample file is available; live media/databases/environment files are excluded.
Snapshots live below the adapter checkout's ignored `.test-worktrees/`. Source
hashes are verified before startup and again before readiness; rerun after any
candidate edit. Do not develop in a snapshot. A running session is not refreshed
in place. Ctrl-C stops the owned processes and removes that session's snapshot,
database, credentials and cache. Foreign/existing snapshots are never replaced;
after an abrupt machine/launcher failure, inspect ownership and remaining
processes before manually clearing a leftover snapshot. Do not run broad cleanup.
Test credentials have initial access tokens so existing login rendering can be
exercised; this is test fixture setup, not a fix to application token issuance.
Secure downloads are tracked in TASK-004.
Adapter checks:
```sh
python3 -m unittest discover -s scripts/tests -v
bash -n scripts/testtask.sh .roborto/testtask-hook .roborto/testtask.conf
```
+78
View File
@@ -0,0 +1,78 @@
"""Safety checks: python3 -m unittest discover -s scripts/tests -v."""
import importlib.util
import os
from pathlib import Path
import subprocess
import tempfile
import unittest
from unittest.mock import patch
ROOT = Path(__file__).resolve().parents[2]
os.environ.update(ROBORTO_PROJECT_ROOT=str(ROOT), ROBORTO_RUN_DIR='/tmp/testtask-unit-run', ROBORTO_TASK_ID='002', ROBORTO_WORKTREE=str(ROOT / '.test-worktrees/task-002'))
spec = importlib.util.spec_from_file_location('adapter', ROOT / 'scripts/testtask_adapter.py')
adapter = importlib.util.module_from_spec(spec)
spec.loader.exec_module(adapter)
class AdapterTests(unittest.TestCase):
def test_snapshot_excludes_local_data_and_links(self):
with tempfile.TemporaryDirectory() as temporary:
root = Path(temporary)
subprocess.run(['git', 'init', '-q', str(root)], check=True)
for name in ['api/source.py', 'api/new_test.py', 'api/.env', 'api/accounts.sqlite', 'api/share/movie.mp4', 'react/node_modules/package/code.js', 'docs/snapshots/old.zip', 'api/id_rsa', '.roborto/testtask.conf']:
path = root / name
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text('fixture')
(root / 'api/link.py').symlink_to(root / 'api/source.py')
subprocess.run(['git', '-C', str(root), 'add', 'api/source.py'], check=True)
(root / 'api/source.py').write_text('unstaged change')
files = adapter.safe_files(root)
self.assertEqual(set(files), {'api/source.py', 'api/new_test.py', '.roborto/testtask.conf'})
(root / 'api/new_test.py').write_text('updated')
self.assertNotEqual(files, adapter.safe_files(root))
def test_cleanup_preserves_foreign_snapshot(self):
with tempfile.TemporaryDirectory() as temporary:
root = Path(temporary)
snapshot = root / '.test-worktrees/task-002'
snapshot.mkdir(parents=True)
marker = snapshot / adapter.MARKER
marker.write_text('/other/session')
with patch.object(adapter, 'ROOT', root), patch.object(adapter, 'SNAPSHOT', snapshot):
adapter.cleanup()
self.assertTrue(snapshot.exists())
marker.write_text(str(adapter.RUN))
adapter.cleanup()
adapter.cleanup()
self.assertFalse(snapshot.exists())
def test_cleanup_rejects_unexpected_path(self):
with patch.object(adapter, 'SNAPSHOT', Path('/tmp/unowned')):
with self.assertRaises(RuntimeError):
adapter.cleanup()
def test_existing_snapshot_is_never_replaced(self):
with tempfile.TemporaryDirectory() as temporary:
root = Path(temporary)
snapshot = root / '.test-worktrees/task-002'
snapshot.mkdir(parents=True)
with patch.object(adapter, 'ROOT', root), patch.object(adapter, 'SNAPSHOT', snapshot):
with self.assertRaisesRegex(RuntimeError, 'already exists'):
adapter.validate()
def test_malformed_task_rejected(self):
with patch.object(adapter, 'TASK', '../002'):
with self.assertRaises(RuntimeError):
adapter.validate()
def test_task_discovery(self):
output = b'worktree /tmp/TASK-002\0HEAD abc\0branch refs/heads/task/TASK-002-authorization\0\0'
with patch.object(adapter.subprocess, 'check_output', return_value=output):
self.assertEqual(adapter.source(), Path('/tmp/TASK-002'))
with patch.object(adapter, 'TASK', '999'):
with self.assertRaisesRegex(RuntimeError, 'found 0'):
adapter.source()
if __name__ == '__main__':
unittest.main()
+5
View File
@@ -0,0 +1,5 @@
#!/usr/bin/env bash
set -Eeuo pipefail
cd "$(dirname "${BASH_SOURCE[0]}")/.."
command -v roborto-testtask >/dev/null || { echo 'Install roborto-testtask first.' >&2; exit 127; }
exec roborto-testtask "$@"
+203
View File
@@ -0,0 +1,203 @@
#!/usr/bin/env python3
"""Local testtask hook: exact safe source copy, isolated state, foreground servers."""
import base64
import hashlib
import json
import os
from pathlib import Path
import re
import secrets
import shutil
import subprocess
import sys
ROOT = Path(os.environ['ROBORTO_PROJECT_ROOT']).resolve()
RUN = Path(os.environ['ROBORTO_RUN_DIR']).resolve()
TASK = os.environ['ROBORTO_TASK_ID']
SNAPSHOT = Path(os.environ['ROBORTO_WORKTREE'])
COMMON = Path(subprocess.check_output(['git', '-C', str(ROOT), 'rev-parse', '--path-format=absolute', '--git-common-dir'], text=True).strip())
SHARED = COMMON.parent
MARKER = '.testtask-owner'
EXCLUDED_DIRS = {'.git', '.worktrees', '.test-worktrees', '.venv', 'venv', 'node_modules', 'share', 'instance', '__pycache__', '.pytest_cache', 'dist', 'dist-ssr', 'build', 'coverage', 'snapshots', 'logs'}
SUFFIXES = ('.pyc', '.pyo', '.log', '.zip', '.db', '.sqlite', '.sqlite3', '.pem', '.key', '.p12', '.pfx')
def fail(message):
raise RuntimeError(message)
def source():
entries = subprocess.check_output(['git', '-C', str(ROOT), 'worktree', 'list', '--porcelain', '-z']).decode().split('\0')
found, path = [], None
for entry in entries:
if entry.startswith('worktree '):
path = Path(entry[9:])
if entry.startswith('branch refs/heads/') and re.fullmatch(r'(?:task/TASK-' + TASK + r'-[\w-]+)', entry[18:]):
found.append(path)
if len(found) != 1:
fail(f'Expected exactly one checked-out task/TASK-{TASK}-* branch; found {len(found)}')
return found[0]
def safe_files(src):
names = subprocess.check_output(['git', '-C', str(src), 'ls-files', '-z', '--cached', '--others', '--exclude-standard']).split(b'\0')
result = {}
for raw in names:
if not raw:
continue
relative = Path(os.fsdecode(raw))
path = src / relative
if any(part in EXCLUDED_DIRS for part in relative.parts):
continue
if any(part.startswith('.') and part not in {'.gitignore', '.roborto'} for part in relative.parts):
continue
if relative.name.lower().startswith(('credentials', 'id_rsa', 'id_ed25519')) or relative.name.lower().endswith(SUFFIXES):
continue
if any(parent.is_symlink() for parent in [path, *path.parents]) or not path.is_file():
continue
result[relative.as_posix()] = hashlib.sha256(path.read_bytes()).hexdigest()
return result
def dependencies():
node = os.environ.get('FOLDERSHARE_TEST_NODE') or shutil.which('node')
if not node:
candidates = list((Path.home() / '.nvm/versions/node').glob('v*/bin/node'))
candidates.sort(key=lambda p: tuple(int(n) for n in p.parents[1].name[1:].split('.')))
node = str(candidates[-1]) if candidates else None
vite = SHARED / 'react/node_modules/vite/bin/vite.js'
if not node or not Path(node).is_file() or not vite.is_file():
fail('Need Node >=18 and existing react/node_modules; install dependencies separately')
version = subprocess.check_output([node, '-p', 'process.versions.node'], text=True)
if int(version.split('.')[0]) < 18:
fail('Node >=18 required; set FOLDERSHARE_TEST_NODE')
return node, vite
def validate():
if not re.fullmatch(r'\d{3}', TASK):
fail('Task ID must contain three digits')
expected = ROOT / '.test-worktrees' / ('task-' + TASK)
if SNAPSHOT != expected or SNAPSHOT.parent.is_symlink() or SNAPSHOT.is_symlink():
fail('Unexpected or symlinked snapshot path')
if SNAPSHOT.exists():
fail('Snapshot already exists; preserve it and stop its owning session first')
src = source()
# Older application settings must never silently fall back to a local DB.
if 'FOLDERSHARE_DATABASE_URI' not in (src / 'api/settings.py').read_text():
fail('Candidate lacks isolated database configuration (TASK-002 prerequisite)')
dependencies()
import flask, flask_sqlalchemy, flask_httpauth, flask_migrate, sqlalchemy_serializer # noqa: F401
print(f'Validated source {src}', file=sys.stderr)
def prepare():
validate()
src = source()
manifest = safe_files(src)
SNAPSHOT.parent.mkdir(exist_ok=True)
SNAPSHOT.mkdir(mode=0o700)
(SNAPSHOT / MARKER).write_text(str(RUN))
for name in manifest:
dest = SNAPSHOT / name
dest.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(src / name, dest)
copied = {name: hashlib.sha256((SNAPSHOT / name).read_bytes()).hexdigest() for name in manifest}
if copied != manifest or safe_files(src) != manifest:
fail('Source changed during snapshot creation; rerun with a stable candidate')
(RUN / 'manifest.json').write_text(json.dumps({'source': str(src), 'files': manifest}, indent=2))
(SNAPSHOT / 'react/node_modules').symlink_to(SHARED / 'react/node_modules', target_is_directory=True)
(SNAPSHOT / 'react/testtask.vite.config.mjs').write_text('''import base from './vite.config.js';
export default {...base, cacheDir: process.env.FOLDERSHARE_TEST_CACHE,
server: {...base.server, host: '127.0.0.1', port: 5503, strictPort: true,
proxy: {'/api': 'http://127.0.0.1:5502'}}};
''')
media = RUN / 'media'
(media / 'friends').mkdir(parents=True)
(media / 'friends/sample.txt').write_text('Disposable test media only.\n')
(RUN / 'password').write_text(secrets.token_urlsafe(18))
print(f'Snapshot verified: {len(manifest)} source files from {src}', file=sys.stderr)
def start_backend():
env = os.environ.copy()
env.update(FOLDERSHARE_DATABASE_URI='sqlite:///' + str(RUN / 'accounts.sqlite'), ROOT_PATH=str(RUN / 'media'), PYTHON_DOTENV_DISABLED='1', DEBUG='False', SQLALCHEMY_ECHO='False', PYTHONPATH=str(SNAPSHOT / 'api'))
bootstrap = '''from pathlib import Path
from settings import app, db
from models.user import User
import os
assert app.config['SQLALCHEMY_DATABASE_URI'] == os.environ['FOLDERSHARE_DATABASE_URI'], 'Unsafe database configuration'
with app.app_context():
db.create_all()
for name, admin, root in [('captain', True, None), ('friend', False, '/friends'), ('unassigned', False, None), ('disabled', False, '/friends')]:
user = User(username=name, is_admin=admin, root=root, login_disabled=name == 'disabled')
user.set_password(Path(os.environ['ROBORTO_RUN_DIR'], 'password').read_text())
db.session.add(user)
user.get_token()
db.session.commit()
import api
app.run(host='127.0.0.1', port=5502, debug=False, use_reloader=False)
'''
os.chdir(SNAPSHOT / 'api')
os.execve(sys.executable, [sys.executable, '-c', bootstrap], env)
def start_frontend():
node, vite = dependencies()
env = os.environ.copy()
env['FOLDERSHARE_TEST_CACHE'] = str(RUN / 'vite-cache')
os.chdir(SNAPSHOT / 'react')
os.execve(node, [node, str(vite), '--config', 'testtask.vite.config.mjs'], env)
def credentials():
# Real HTTP checks, in addition to engine port checks.
from urllib.request import Request, urlopen
from urllib.error import HTTPError
for base in ['http://127.0.0.1:5502', 'http://127.0.0.1:5503']:
try:
urlopen(base + '/api/file/root', timeout=5)
fail('Protected API unexpectedly allowed an anonymous request')
except HTTPError as error:
if error.code != 401:
raise
password = (RUN / 'password').read_text()
for name in ['captain', 'friend', 'unassigned', 'disabled']:
basic = base64.b64encode(f'{name}:{password}'.encode()).decode()
request = Request('http://127.0.0.1:5503/api/auth/token', method='POST', headers={'Authorization': 'Basic ' + basic})
try:
with urlopen(request, timeout=5) as response:
data = json.load(response)
if name == 'disabled' or not data.get('token'):
fail('Disposable login fixture failed')
except HTTPError as error:
if name != 'disabled' or error.code != 401:
raise
manifest = json.loads((RUN / 'manifest.json').read_text())
if safe_files(Path(manifest['source'])) != manifest['files']:
fail('Candidate changed since snapshot creation; stop and rerun before testing')
with urlopen('http://127.0.0.1:5503', timeout=5) as response:
if response.status != 200:
fail('Frontend HTTP check failed')
print('HTTP readiness passed. Disposable accounts: captain (admin), friend, unassigned, disabled.')
print('Shared session password:', (RUN / 'password').read_text())
print('Candidate snapshot:', SNAPSHOT)
print('Source must remain unchanged while testing; Ctrl-C stops servers and removes this snapshot.')
def cleanup():
expected = ROOT / '.test-worktrees' / ('task-' + TASK)
if SNAPSHOT != expected or SNAPSHOT.parent.is_symlink():
fail('Refusing cleanup outside the owned snapshot path')
marker = SNAPSHOT / MARKER
if not SNAPSHOT.is_symlink() and marker.is_file() and marker.read_text() == str(RUN):
shutil.rmtree(SNAPSHOT)
if __name__ == '__main__':
try:
actions = {'validate': validate, 'prepare': prepare, 'start-backend': start_backend, 'start-frontend': start_frontend, 'credentials': credentials, 'cleanup': cleanup}
actions[sys.argv[1]]()
except Exception as error:
print(f'testtask: {error}', file=sys.stderr)
sys.exit(1)