Files
pic/api/auth_routes.py
T
roof 8b50fb1036
Unit Tests / test (push) Successful in 12m47s
feat: audit/change log — owner-visible record of who changed what
Add AuditManager (api/audit_manager.py): JSONL append-only log at
data/api/audit/audit.log with SHA-256 hash chain for tamper detection,
verify endpoint, size-based rotation, and automatic redaction of secret
fields before any entry is written. Supports structured query (actor,
action, date range) and CSV export.

Wire an @app.after_request hook in app.py that fires on every mutating
/api/* request: captures actor, role, remote IP, and maps the route +
method to a human-readable action via ROUTE_ACTION_MAP. Explicit audit
entries for password_change and password_reset are added in
auth_routes.py so those events record the actor without logging secret
values.

Expose an admin-only blueprint (api/routes/audit.py):
  GET /api/audit          — paginated query
  GET /api/audit/export   — CSV download
  GET /api/audit/verify   — hash-chain integrity check

Register AuditManager in managers.py and add api/audit to
config_manager.py critical_data_paths so it is included in backups and
restored with other persistent state.

Add Activity page (webui/src/pages/Activity.jsx, admin-only) reachable
from the nav in App.jsx. New auditAPI helper in api.js covers all three
endpoints.

Tests: test_audit_manager.py (unit: hash chain, redaction, rotation,
query, csv, verify) and test_audit_hook_routes.py (integration: hook
fires on mutating routes, skips safe methods, records actor/ip/action,
backup-inclusion assertion).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-10 20:19:38 -04:00

197 lines
7.1 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 _audit(action, target_type, target_id, summary, result, status):
"""Record an explicit audit entry for auth actions the generic hook skips.
Never raises and never includes any password value.
"""
try:
from app import audit_manager
ip = request.remote_addr or ''
xff = request.headers.get('X-Forwarded-For', '')
if xff:
last = xff.split(',')[-1].strip()
if last:
ip = last
audit_manager.record(
actor=session.get('username', 'anonymous'),
role=session.get('role', 'system'),
ip=ip, action=action, target_type=target_type, target_id=target_id,
summary=summary, result=result, status=status,
method=request.method, path=request.path,
)
except Exception:
pass
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:
_audit('user.password_change', 'user', username or '',
'password changed', 'failure', 400)
return jsonify({'error': 'Password change failed'}), 400
_audit('user.password_change', 'user', username or '',
'password changed', 'success', 200)
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:
_audit('user.password_reset', 'user', username,
f'admin reset password for peer {username}', 'failure', 400)
return jsonify({'error': 'Reset failed (user not found?)'}), 400
_audit('user.password_reset', 'user', username,
f'admin reset password for peer {username}', 'success', 200)
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())