diff --git a/api/auth.py b/api/auth.py index 1b6d3da..c7fc0ef 100644 --- a/api/auth.py +++ b/api/auth.py @@ -13,7 +13,7 @@ def verify_password(username, password): """Verify password.""" user = ( User.query.filter_by(username=username) - .filter(User.login_disabled is not True) + .filter(User.login_disabled.is_(False)) .first() ) if user and user.check_password(password): diff --git a/api/media.py b/api/media.py new file mode 100644 index 0000000..a8530d3 --- /dev/null +++ b/api/media.py @@ -0,0 +1,86 @@ +"""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 pathlib import Path +from flask import current_app + + +class MediaDenied(ValueError): + 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 assigned_root(value): + if not isinstance(value, str) or not value.startswith("/"): + raise MediaDenied() + parts = value[1:].split("/") if value != "/" else [] + if any(part in ("", ".", "..") or "\\" in part or "%" in part or "\x00" in part for part in parts): + raise MediaDenied() + 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 + + +def file_tree(root): + """List using anchored directory descriptors; never follow swapped links.""" + tree = [] + flags = os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW + + def visit(descriptor, virtual): + dirs, files, children = [], [], [] + with os.scandir(descriptor) as entries: + names = sorted(entry.name for entry in entries) + for name in names: + metadata = os.stat(name, dir_fd=descriptor, follow_symlinks=False) + if stat.S_ISDIR(metadata.st_mode): + dirs.append(name) + children.append(name) + elif stat.S_ISREG(metadata.st_mode): + files.append({"name": name, "size": metadata.st_size}) + tree.append({"root": virtual, "dirs": dirs, "files": files}) + for name in children: + child_fd = os.open(name, flags, dir_fd=descriptor) + try: + visit(child_fd, virtual.rstrip("/") + "/" + name) + finally: + os.close(child_fd) + + descriptor = None + try: + base = media_root() + parts = root.relative_to(base).parts + descriptor = os.open(base, flags) + for part in parts: + child_fd = os.open(part, flags, dir_fd=descriptor) + os.close(descriptor) + descriptor = child_fd + visit(descriptor, "/") + except (OSError, RuntimeError, ValueError): + raise MediaDenied() from None + finally: + if descriptor is not None: + os.close(descriptor) + return tree diff --git a/api/models/user.py b/api/models/user.py index 3047faf..2b26c40 100644 --- a/api/models/user.py +++ b/api/models/user.py @@ -1,6 +1,6 @@ from sqlalchemy_serializer import SerializerMixin from werkzeug.security import generate_password_hash, check_password_hash -from settings import db, root_path +from settings import db import base64 from datetime import datetime, timedelta import os @@ -67,7 +67,12 @@ class User(db.Model, SerializerMixin): @staticmethod def check_token(token): 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 user @@ -78,21 +83,11 @@ class User(db.Model, SerializerMixin): return None return user - def get_file_list(self) -> dict: - if self.root is None: + def get_file_list(self) -> list: + 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 [] - - 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 diff --git a/api/routes/file_routes.py b/api/routes/file_routes.py index 9e3b55d..d1ff33c 100644 --- a/api/routes/file_routes.py +++ b/api/routes/file_routes.py @@ -1,49 +1,22 @@ -from settings import app, root_path -from flask import request, send_from_directory -import os -import mime +"""Media routes. Legacy client-directed downloads are deliberately disabled.""" +from settings import app from auth import token_auth from errors import error_response +from media import media_root, file_tree, MediaDenied @app.route("/api/file/root") @token_auth.login_required -def get_root_path() -> list: - user = token_auth.current_user() - if not user.is_admin: +def get_root_path(): + if not token_auth.current_user().is_admin: return error_response(403) - file_list = [] - for root, dirs, files in os.walk(root_path, topdown=False): - files = list( - map( - lambda file: { - "name": file, - "size": os.path.getsize(root + "/" + file), - }, - files, - ) - ) - file_list.append( - { - "root": "/" + "/".join(root.split("/")[1:]), - "dirs": dirs, - "files": files, - } - ) - return file_list[::-1] + try: + return file_tree(media_root()) + except MediaDenied: + return error_response(503, "Media unavailable") @app.route("/api/file", methods=["POST"]) @token_auth.login_required -def get_file() -> dict: - req = request.get_json() - 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"]}") +def get_file(): + return error_response(410, "Downloads unavailable pending secure download grants") diff --git a/api/routes/token_routes.py b/api/routes/token_routes.py index 64b90c8..d65810a 100644 --- a/api/routes/token_routes.py +++ b/api/routes/token_routes.py @@ -16,10 +16,11 @@ basic_auth.realm = "Incorrect Credentials" def get_token(): """Get token.""" user = basic_auth.current_user() + user.get_token() refresh_token = user.get_refresh_token() db.session.commit() response = make_response( - jsonify(user.to_dict(rules=("is_admin", "token"))) + jsonify({**user.to_dict(rules=("is_admin", "token")), "user_id": user.id}) ) response.set_cookie("refresh_token", value=refresh_token, httponly=True) return response @@ -41,10 +42,12 @@ def refresh_token(): if refresh_token is None: return error_response(400, "Bad request, no refresh token") 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() db.session.commit() return { "token": access_token, "user_id": user.id, } + + return error_response(401) diff --git a/api/routes/user_routes.py b/api/routes/user_routes.py index b343e16..efb9f5d 100644 --- a/api/routes/user_routes.py +++ b/api/routes/user_routes.py @@ -4,6 +4,7 @@ from settings import app, db from models.user import User from errors import error_response, bad_request from auth import token_auth +from media import assigned_root, MediaDenied from flask import request from sqlalchemy import select from werkzeug.security import generate_password_hash @@ -28,13 +29,26 @@ def get_user(user_id) -> list: return error_response(403) stmt = select(User).filter(User.id == user_id) user = db.session.scalars(stmt).first() + if user is None: + return error_response(404) return user.to_dict() @app.route("/api/user/", methods=["PATCH"]) @token_auth.login_required 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) user = db.session.scalars(stmt).first() if user is None: @@ -45,6 +59,8 @@ def update_user(user_id) -> dict: if user.is_admin: return bad_request(f"User is admin: {user.username}") user.login_disabled = req["login_disabled"] + if user.login_disabled: + user.revoke_tokens() db.session.commit() return user.to_dict() @@ -52,15 +68,19 @@ def update_user(user_id) -> dict: @app.route("/api/user", methods=["POST"]) @token_auth.login_required def add_user() -> dict: - model = request.get_json() - if "username" not in model or model["username"] is None: + if not token_auth.current_user().is_admin: + 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") username = model["username"] stmt = select(User).filter(User.username == username) user = db.session.scalars(stmt).first() if user is not None: 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") password_hash = generate_password_hash(model["password"]) user = User(username=username, password_hash=password_hash) @@ -72,6 +92,8 @@ def add_user() -> dict: @app.route("/api/user/", methods=["DELETE"]) @token_auth.login_required 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) user = db.session.scalars(stmt).first() if user is None: diff --git a/api/settings.py b/api/settings.py index a58727e..2021d98 100644 --- a/api/settings.py +++ b/api/settings.py @@ -11,7 +11,7 @@ app = Flask(__name__, static_folder="static") app.config.update( { "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_TRACK_MODIFICATIONS": bool( 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") if root_path is None: root_path = "share" + +app.config["MEDIA_ROOT"] = os.path.abspath(root_path) diff --git a/api/tests/test_security.py b/api/tests/test_security.py new file mode 100644 index 0000000..3dfdaa5 --- /dev/null +++ b/api/tests/test_security.py @@ -0,0 +1,170 @@ +"""Run: /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_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_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() diff --git a/docs/CURRENT_STATE.md b/docs/CURRENT_STATE.md index ea2d052..d30463a 100644 --- a/docs/CURRENT_STATE.md +++ b/docs/CURRENT_STATE.md @@ -1,8 +1,8 @@ # Foldershare current state -- Updated: 2026-11-04 +- Updated: 2026-11-25 for TASK-002 integration - Inspected worktree: `/home/rob/projects/foldershare` -- Branch and HEAD at inspection: `codex` at `767b424` +- TASK-002 integration base: `codex` at `cd6d6b3` ## Verified repository state @@ -34,3 +34,14 @@ 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. 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's manual-test adapter awaits separate Captain validation in its own worktree. diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md index 5c7a77c..f79613d 100644 --- a/docs/DECISIONS.md +++ b/docs/DECISIONS.md @@ -68,3 +68,18 @@ Until approved, brief the concrete convention choice before creating later task ## 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. + +## 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. diff --git a/docs/HANDOFF.md b/docs/HANDOFF.md index 6f66072..26ea0ff 100644 --- a/docs/HANDOFF.md +++ b/docs/HANDOFF.md @@ -1,26 +1,9 @@ # Foldershare handoff -This is a replaceable snapshot. Live repository/Git and maintained context take precedence. +Updated 2026-11-25. Captain accepted TASK-002 on 2026-11-07 and authorized committing it from `.worktrees/TASK-002` and integrating it locally into `codex` on 2026-11-25. -- Updated: 2026-11-04 (planning reconciliation from `foldershare-20261104-160824-012796.zip`) -- 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. +TASK-002 supplies the authorization and filesystem boundaries. Integration checks passed for ten API tests, Python syntax, the frontend production build and whitespace. The frontend lint script requires a missing ESLint configuration. Existing accounts with a `NULL` login flag are denied access, and existing host-absolute assignments need admin reassignment. -## Current outcome +Captain selected TASK-003 for briefing. It remains Accepted. Use the merged `codex` tip as the proposed base for `task/TASK-003-secure-browsing` in `.worktrees/TASK-003`, subject to approval when Captain engages the task. Reuse TASK-002's virtual roots and media containment for authenticated browsing. Preserve the admin-only folder picker and existing browser styling. Define the browse response and its stable file reference for TASK-004 during implementation. -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. - -## Major static-source risks to address - -`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. - -## Next Codex action - -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. -2. Apply documentation-only patch, review diff and report conflicts. Do **not** quietly replace newer state or start any implementation task. -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. -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. - -## Validation - -Patch was generated from the exact supplied ZIP. No live Git or application validation can be claimed from the archive alone. +Validate browse access and failure states with disposable media and user fixtures, then verify the browser flow for assigned, unassigned and admin users. TASK-007 has a separate manual-test adapter awaiting Captain validation. Its integration or use for a later handoff is a separate decision. diff --git a/docs/TASKS.md b/docs/TASKS.md index 213efbc..3da18b8 100644 --- a/docs/TASKS.md +++ b/docs/TASKS.md @@ -35,7 +35,7 @@ The scopes below translate Captain's explicit product requirements into implemen ### 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. - 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. @@ -44,6 +44,9 @@ 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). - 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. +- 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 diff --git a/react/src/views/User/User.jsx b/react/src/views/User/User.jsx index 48aacf0..9629425 100644 --- a/react/src/views/User/User.jsx +++ b/react/src/views/User/User.jsx @@ -68,10 +68,10 @@ const User = () => {
- {user?.username} + Username: {user?.username} - {user?.root || "No root set"} + Assigned folder: {user?.root || "None — no media access"} diff --git a/react/src/views/Users/Users.jsx b/react/src/views/Users/Users.jsx index e417532..3df14a7 100644 --- a/react/src/views/Users/Users.jsx +++ b/react/src/views/Users/Users.jsx @@ -1,4 +1,5 @@ import { + Alert, Col, Container, ListGroup, @@ -22,7 +23,22 @@ const Users = () => { const [addUserOpen, setAddUserOpen] = 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(() => { getUsers(); @@ -106,6 +122,9 @@ const Users = () => { + {loadingUsers &&

Loading users…

} + {loadError && {loadError}} + {!loadingUsers && !loadError && users.length === 0 &&

No users found.

} {users.map((user, index) => (