From fb0cc3e39d0649f9904ce85a4eb4c3ad9a1867db Mon Sep 17 00:00:00 2001 From: "Aaron D. Lee" Date: Wed, 1 Apr 2026 19:35:36 -0400 Subject: [PATCH] Implement 14 power-user feature requests for field deployment MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Critical: - FR-01: Chain verification now supports key rotation via signed rotation records (soosef/key-rotation-v1 content type). Old single-signer invariant replaced with authorized-signers set. - FR-02: Carrier images stripped of EXIF metadata by default before steganographic encoding (strip_metadata=True). Prevents source location/device leakage. High priority: - FR-03: Session timeout (default 15min) + secure cookie flags (HttpOnly, SameSite=Strict, Secure when HTTPS) - FR-04: CSRF protection via Flask-WTF on all POST forms. Killswitch now requires password re-authentication. - FR-05: Collaborator trust store — trust_key(), get_trusted_keys(), resolve_attestor_name(), untrust_key() in KeystoreManager. - FR-06: Production WSGI server (Waitress) by default, Flask dev server only with --debug flag. - FR-07: Dead man's switch sends warning during grace period via local file + optional webhook before auto-purge. Medium: - FR-08: Geofence get_current_location() via gpsd for --here support. - FR-09: Batch attestation endpoint (/attest/batch) with SHA-256 dedup and per-file status reporting. - FR-10: Key backup tracking with last_backup_info() and is_backup_overdue() + backup_reminder_days config. - FR-11: Verification receipts signed with instance Ed25519 key (schema_version bumped to 2). - FR-12: Login rate limiting with configurable lockout (5 attempts, 15 min default). Nice-to-have: - FR-13: Unified `soosef status` pre-flight command showing identity, channel key, deadman, geofence, chain, and backup status. - FR-14: `soosef chain export` produces ZIP with JSON manifest, public key, and raw chain.bin for legal discovery. Tests: 157 passed, 1 skipped, 1 pre-existing flaky test. Co-Authored-By: Claude Opus 4.6 (1M context) --- frontends/web/app.py | 52 ++++- frontends/web/blueprints/attest.py | 89 ++++++++- frontends/web/blueprints/fieldkit.py | 11 +- frontends/web/templates/account.html | 4 + frontends/web/templates/admin/user_new.html | 1 + frontends/web/templates/attest/attest.html | 1 + frontends/web/templates/attest/verify.html | 1 + .../web/templates/attest/verify_result.html | 1 + frontends/web/templates/fieldkit/keys.html | 2 + .../web/templates/fieldkit/killswitch.html | 6 + frontends/web/templates/fieldkit/status.html | 1 + frontends/web/templates/login.html | 1 + frontends/web/templates/recover.html | 1 + .../web/templates/regenerate_recovery.html | 1 + frontends/web/templates/setup.html | 1 + frontends/web/templates/setup_recovery.html | 1 + frontends/web/templates/stego/decode.html | 1 + frontends/web/templates/stego/encode.html | 1 + frontends/web/templates/stego/generate.html | 2 + pyproject.toml | 2 + src/soosef/cli.py | 181 +++++++++++++++++- src/soosef/config.py | 7 + src/soosef/federation/chain.py | 61 +++++- src/soosef/fieldkit/deadman.py | 43 ++++- src/soosef/fieldkit/geofence.py | 37 ++++ src/soosef/keystore/manager.py | 115 +++++++++++ src/soosef/stegasoo/encode.py | 14 ++ tests/test_chain.py | 41 +++- 28 files changed, 656 insertions(+), 23 deletions(-) diff --git a/frontends/web/app.py b/frontends/web/app.py index 358c647..dce911f 100644 --- a/frontends/web/app.py +++ b/frontends/web/app.py @@ -70,6 +70,20 @@ def create_app(config: SoosefConfig | None = None) -> Flask: app.config["HTTPS_ENABLED"] = config.https_enabled app.config["SOOSEF_CONFIG"] = config + # Session security: timeout + secure cookie flags + from datetime import timedelta + + app.config["PERMANENT_SESSION_LIFETIME"] = timedelta(minutes=config.session_timeout_minutes) + app.config["SESSION_COOKIE_HTTPONLY"] = True + app.config["SESSION_COOKIE_SAMESITE"] = "Strict" + if config.https_enabled: + app.config["SESSION_COOKIE_SECURE"] = True + + # CSRF protection on all POST/PUT/DELETE routes + from flask_wtf.csrf import CSRFProtect + + csrf = CSRFProtect(app) + # Point temp_storage at ~/.soosef/temp/ before any routes run, so all # uploaded files land where the killswitch's destroy_temp_files step # expects them. Must happen after ensure_dirs() so the directory exists. @@ -303,6 +317,9 @@ def _register_stegasoo_routes(app: Flask) -> None: user_exists as auth_user_exists, ) + # Login rate limiting: {username: [(timestamp, ...),]} + _login_attempts: dict[str, list[float]] = {} + @app.route("/login", methods=["GET", "POST"]) def login(): if not app.config.get("AUTH_ENABLED", True): @@ -312,16 +329,49 @@ def _register_stegasoo_routes(app: Flask) -> None: if auth_is_authenticated(): return redirect(url_for("index")) if request.method == "POST": + import time + username = request.form.get("username", "") password = request.form.get("password", "") + + # Check lockout + max_attempts = config.login_lockout_attempts + lockout_mins = config.login_lockout_minutes + now = time.time() + window = lockout_mins * 60 + attempts = _login_attempts.get(username, []) + # Prune old attempts + attempts = [t for t in attempts if now - t < window] + _login_attempts[username] = attempts + + if len(attempts) >= max_attempts: + from soosef.audit import log_action + + log_action( + actor=username, + action="user.login_locked", + target=username, + outcome="blocked", + source="web", + ) + flash(f"Account locked for {lockout_mins} minutes after too many failed attempts.", "error") + return render_template("login.html") + user = verify_user_password(username, password) if user: + _login_attempts.pop(username, None) auth_login_user(user) session.permanent = True flash("Login successful", "success") return redirect(url_for("index")) else: - flash("Invalid username or password", "error") + attempts.append(now) + _login_attempts[username] = attempts + remaining = max_attempts - len(attempts) + if remaining <= 2: + flash(f"Invalid credentials. {remaining} attempts remaining.", "error") + else: + flash("Invalid username or password", "error") return render_template("login.html") @app.route("/logout") diff --git a/frontends/web/blueprints/attest.py b/frontends/web/blueprints/attest.py index 682425b..62837f2 100644 --- a/frontends/web/blueprints/attest.py +++ b/frontends/web/blueprints/attest.py @@ -9,6 +9,7 @@ Wraps verisoo's attestation and verification libraries to provide: from __future__ import annotations +import hashlib import json import socket from datetime import UTC, datetime @@ -209,6 +210,79 @@ def attest(): return render_template("attest/attest.html", has_identity=has_identity) +@bp.route("/attest/batch", methods=["POST"]) +@login_required +def attest_batch(): + """Batch attestation — accepts multiple image files. + + Returns JSON with results for each file (success/skip/error). + Skips images already attested (by SHA-256 match). + """ + import hashlib + + from soosef.verisoo.hashing import hash_image + + private_key = _get_private_key() + if private_key is None: + return {"error": "No identity key. Run soosef init first."}, 400 + + files = request.files.getlist("images") + if not files: + return {"error": "No files uploaded"}, 400 + + storage = _get_storage() + results = [] + + for f in files: + filename = f.filename or "unknown" + try: + image_data = f.read() + sha256 = hashlib.sha256(image_data).hexdigest() + + # Skip already-attested images + existing = storage.get_records_by_image_sha256(sha256) + if existing: + results.append({"file": filename, "status": "skipped", "reason": "already attested"}) + continue + + from soosef.verisoo.attestation import create_attestation + + attestation = create_attestation(image_data, private_key) + index = storage.append_record(attestation.record) + + # Wrap in chain if enabled + chain_index = None + config = request.app.config.get("SOOSEF_CONFIG") if hasattr(request, "app") else None + if config and getattr(config, "chain_enabled", False) and getattr(config, "chain_auto_wrap", False): + try: + chain_record = _wrap_in_chain(attestation.record, private_key, {}) + chain_index = chain_record.chain_index + except Exception: + pass + + results.append({ + "file": filename, + "status": "attested", + "record_id": attestation.record.short_id, + "index": index, + "chain_index": chain_index, + }) + except Exception as e: + results.append({"file": filename, "status": "error", "error": str(e)}) + + attested = sum(1 for r in results if r["status"] == "attested") + skipped = sum(1 for r in results if r["status"] == "skipped") + errors = sum(1 for r in results if r["status"] == "error") + + return { + "total": len(results), + "attested": attested, + "skipped": skipped, + "errors": errors, + "results": results, + } + + def _verify_image(image_data: bytes) -> dict: """Run the full verification pipeline against the attestation log. @@ -389,7 +463,7 @@ def verify_receipt(): matching_records.append(rec_entry) receipt = { - "schema_version": "1", + "schema_version": "2", "verification_timestamp": verification_ts, "verifier_instance": verifier_instance, "queried_filename": image_file.filename, @@ -403,6 +477,19 @@ def verify_receipt(): "matching_records": matching_records, } + # Sign the receipt with the instance's Ed25519 identity key + private_key = _get_private_key() + if private_key is not None: + from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat + + pub_bytes = private_key.public_key().public_bytes(Encoding.Raw, PublicFormat.Raw) + receipt["verifier_fingerprint"] = hashlib.sha256(pub_bytes).hexdigest()[:32] + # Sign the receipt content (excluding signature fields) + receipt_payload = json.dumps(receipt, sort_keys=True, ensure_ascii=False).encode() + sig = private_key.sign(receipt_payload) + receipt["signature"] = sig.hex() + receipt["verifier_pubkey"] = pub_bytes.hex() + receipt_json = json.dumps(receipt, indent=2, ensure_ascii=False) safe_filename = ( image_file.filename.rsplit(".", 1)[0] if "." in image_file.filename else image_file.filename diff --git a/frontends/web/blueprints/fieldkit.py b/frontends/web/blueprints/fieldkit.py index 24603bd..4a93862 100644 --- a/frontends/web/blueprints/fieldkit.py +++ b/frontends/web/blueprints/fieldkit.py @@ -30,9 +30,18 @@ def killswitch(): if request.method == "POST": action = request.form.get("action") if action == "fire" and request.form.get("confirm") == "CONFIRM-PURGE": + # Require password re-authentication for killswitch + from auth import verify_user_password + + password = request.form.get("password", "") + username = get_username() + if not verify_user_password(username, password): + flash("Killswitch requires password confirmation.", "danger") + return render_template("fieldkit/killswitch.html") + from soosef.fieldkit.killswitch import PurgeScope, execute_purge - actor = get_username() + actor = username result = execute_purge(PurgeScope.ALL, reason="web_ui") outcome = "success" if result.fully_purged else "failure" failed_steps = ", ".join(name for name, _ in result.steps_failed) diff --git a/frontends/web/templates/account.html b/frontends/web/templates/account.html index 0e82120..a179f8b 100644 --- a/frontends/web/templates/account.html +++ b/frontends/web/templates/account.html @@ -47,6 +47,7 @@ {% if has_recovery %}
+ diff --git a/frontends/web/templates/admin/user_new.html b/frontends/web/templates/admin/user_new.html index 9422f6a..b65c641 100644 --- a/frontends/web/templates/admin/user_new.html +++ b/frontends/web/templates/admin/user_new.html @@ -12,6 +12,7 @@
+