a43f9fbf0d
P0 — Broken functionality: - Fix 12+ endpoints with wrong manager method signatures (email/calendar/file/routing) - Fix email_manager.delete_email_user() missing domain arg - Fix cell-link DNS forwarding wiped on every peer change (generate_corefile now accepts cell_links param; add/remove_cell_dns_forward no longer clobber the file) - Fix Flask SECRET_KEY regenerating on every restart (persisted to DATA_DIR) - Fix _next_peer_ip exhaustion returning 500 instead of 409 - Fix ConfigManager Caddyfile path (/app/config-caddy/) - Fix UI double-add and wrong-key peer bugs in Peers.jsx / WireGuard.jsx - Remove hardcoded credentials from Dashboard.jsx P1 — Security: - CSRF token validation on all POST/PUT/DELETE/PATCH to /api/* (double-submit pattern) - enforce_auth: 503 only when users file readable but empty; never bypass on IOError - WireGuard add_cell_peer: validate pubkey, name, endpoint against strict regexes - DNS add_cell_dns_forward: validate IP and domain; reject injection chars - DNS zone write: realpath containment + record content validation - iptables comment /32 suffix prevents substring match deleting wrong peer rules - is_local_request() trusts only loopback + 172.16.0.0/12 (Docker bridge) - POST /api/containers: volume allow-list prevents arbitrary host mounts - file_manager: bcrypt ($2b→$2y) for WebDAV; realpath containment in delete_user - email/calendar: stop persisting plaintext passwords in user records - routing_manager: validate IPs, networks, and interface names - peer_registry: write peers.json at mode 0o600 - vault_manager: Fernet key file at mode 0o600 - CORS: lock down to explicit origin list - domain/cell_name validation: reject newline, brace, semicolon injection chars P2 — Architecture: - Peer add: rollback registry entry if firewall rules fail post-add - restart_service(): base class now calls _restart_container(); email and calendar managers call cell-mail / cell-radicale respectively - email/calendar managers sync user list (no passwords) to cell_config.json - Pending-restart flag cleared only after helper subprocess exits with code 0 - docker-compose.yml: add config-caddy volume to API container P3 — Tests (854 → 1020): - Fill test_email_endpoints.py, test_calendar_endpoints.py, test_network_endpoints.py, test_routing_endpoints.py - New: test_peer_management_update.py, test_peer_management_edge_cases.py, test_input_validation.py, test_enforce_auth_configured.py, test_cell_link_dns.py, test_logs_endpoints.py, test_cells_endpoints.py, test_is_local_request_per_endpoint.py, test_caddy_routing.py - E2E conftest: skip WireGuard suite when wg-quick absent - Update existing tests to match fixed signatures and comment formats Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
165 lines
5.8 KiB
Python
165 lines
5.8 KiB
Python
#!/usr/bin/env python3
|
|
"""
|
|
Auth-related Flask routes (login, logout, change-password, etc).
|
|
|
|
The Blueprint expects ``auth_manager`` (an instance of
|
|
``auth_manager.AuthManager``) to be assigned at module level by app.py
|
|
after instantiation. A ``require_auth(role=None)`` decorator is also
|
|
exported so individual routes can opt-in to specific role requirements.
|
|
"""
|
|
|
|
import secrets
|
|
from functools import wraps
|
|
|
|
from flask import Blueprint, request, jsonify, session
|
|
|
|
|
|
# Set by app.py after AuthManager is constructed.
|
|
auth_manager = None # type: ignore
|
|
|
|
auth_bp = Blueprint('auth', __name__, url_prefix='/api/auth')
|
|
|
|
|
|
def require_auth(role=None):
|
|
"""Decorator that enforces session authentication and an optional role."""
|
|
def deco(fn):
|
|
@wraps(fn)
|
|
def wrapper(*args, **kwargs):
|
|
username = session.get('username')
|
|
if not username:
|
|
return jsonify({'error': 'Not authenticated'}), 401
|
|
if role == 'admin' and session.get('role') != 'admin':
|
|
return jsonify({'error': 'Forbidden'}), 403
|
|
if role == 'peer' and session.get('role') != 'peer':
|
|
return jsonify({'error': 'Forbidden'}), 403
|
|
request.auth_user = {
|
|
'username': username,
|
|
'role': session.get('role'),
|
|
'peer_name': session.get('peer_name'),
|
|
}
|
|
return fn(*args, **kwargs)
|
|
return wrapper
|
|
return deco
|
|
|
|
|
|
@auth_bp.route('/login', methods=['POST'])
|
|
def login():
|
|
if auth_manager is None:
|
|
return jsonify({'error': 'Auth not initialised'}), 500
|
|
data = request.get_json(silent=True) or {}
|
|
username = (data.get('username') or '').strip()
|
|
password = data.get('password') or ''
|
|
if not username or not password:
|
|
return jsonify({'error': 'username and password required'}), 400
|
|
|
|
# Detect lockout up-front so we can return 423 instead of generic 401.
|
|
pre = auth_manager.get_user(username)
|
|
if pre and pre.get('locked_until'):
|
|
try:
|
|
from datetime import datetime
|
|
until = datetime.strptime(pre['locked_until'], '%Y-%m-%dT%H:%M:%SZ')
|
|
if datetime.utcnow() < until:
|
|
return jsonify({'error': 'Account locked', 'locked_until': pre['locked_until']}), 423
|
|
except Exception:
|
|
pass
|
|
|
|
user = auth_manager.verify_password(username, password)
|
|
if not user:
|
|
# Re-check lockout after the attempt (this attempt may have triggered it).
|
|
post = auth_manager.get_user(username)
|
|
if post and post.get('locked_until'):
|
|
try:
|
|
from datetime import datetime
|
|
until = datetime.strptime(post['locked_until'], '%Y-%m-%dT%H:%M:%SZ')
|
|
if datetime.utcnow() < until:
|
|
return jsonify({'error': 'Account locked', 'locked_until': post['locked_until']}), 423
|
|
except Exception:
|
|
pass
|
|
return jsonify({'error': 'Invalid credentials'}), 401
|
|
|
|
session.permanent = True
|
|
session['username'] = user['username']
|
|
session['role'] = user.get('role')
|
|
session['peer_name'] = user.get('peer_name')
|
|
session['csrf_token'] = secrets.token_hex(32)
|
|
return jsonify({
|
|
'username': user['username'],
|
|
'role': user.get('role'),
|
|
'peer_name': user.get('peer_name'),
|
|
'must_change_password': bool(user.get('must_change_password', False)),
|
|
'csrf_token': session['csrf_token'],
|
|
})
|
|
|
|
|
|
@auth_bp.route('/logout', methods=['POST'])
|
|
def logout():
|
|
session.clear()
|
|
return jsonify({'ok': True})
|
|
|
|
|
|
@auth_bp.route('/me', methods=['GET'])
|
|
def me():
|
|
username = session.get('username')
|
|
if not username:
|
|
return jsonify({'error': 'Not authenticated'}), 401
|
|
return jsonify({
|
|
'username': username,
|
|
'role': session.get('role'),
|
|
'peer_name': session.get('peer_name'),
|
|
})
|
|
|
|
|
|
@auth_bp.route('/change-password', methods=['POST'])
|
|
@require_auth()
|
|
def change_password():
|
|
if auth_manager is None:
|
|
return jsonify({'error': 'Auth not initialised'}), 500
|
|
data = request.get_json(silent=True) or {}
|
|
old_pw = data.get('old_password') or ''
|
|
new_pw = data.get('new_password') or ''
|
|
if not old_pw or not new_pw:
|
|
return jsonify({'error': 'old_password and new_password required'}), 400
|
|
if len(new_pw) < 10:
|
|
return jsonify({'error': 'new_password must be at least 10 characters'}), 400
|
|
username = session.get('username')
|
|
ok = auth_manager.change_password(username, old_pw, new_pw)
|
|
if not ok:
|
|
return jsonify({'error': 'Password change failed'}), 400
|
|
return jsonify({'ok': True})
|
|
|
|
|
|
@auth_bp.route('/admin/reset-password', methods=['POST'])
|
|
@require_auth('admin')
|
|
def admin_reset_password():
|
|
if auth_manager is None:
|
|
return jsonify({'error': 'Auth not initialised'}), 500
|
|
data = request.get_json(silent=True) or {}
|
|
username = (data.get('username') or '').strip()
|
|
new_pw = data.get('new_password') or ''
|
|
if not username or not new_pw:
|
|
return jsonify({'error': 'username and new_password required'}), 400
|
|
if len(new_pw) < 10:
|
|
return jsonify({'error': 'new_password must be at least 10 characters'}), 400
|
|
ok = auth_manager.set_password_admin(username, new_pw)
|
|
if not ok:
|
|
return jsonify({'error': 'Reset failed (user not found?)'}), 400
|
|
return jsonify({'ok': True})
|
|
|
|
|
|
@auth_bp.route('/csrf-token', methods=['GET'])
|
|
def get_csrf_token():
|
|
"""Return the current session's CSRF token, generating one if absent."""
|
|
token = session.get('csrf_token')
|
|
if not token:
|
|
token = secrets.token_hex(32)
|
|
session['csrf_token'] = token
|
|
return jsonify({'csrf_token': token})
|
|
|
|
|
|
@auth_bp.route('/users', methods=['GET'])
|
|
@require_auth('admin')
|
|
def list_users():
|
|
if auth_manager is None:
|
|
return jsonify({'error': 'Auth not initialised'}), 500
|
|
return jsonify(auth_manager.list_users())
|