Skip to content

Speakr is a personal, self-hosted web application designed for transcribing audio recordings

Python

Harden app from audit: enforce auth rate limits (was a no-op), fix bulk-toggle IDOR, re-validate webhook URLs at delivery against DNS rebinding, stop leaking exception text; bound all ffmpeg/ffprobe subprocesses with timeouts, clean up incognito/converted/extracted temp files on every path, stop post-completion side effects from corrupting finished recordings; close the recording AudioContext and display stream on stop/discard/error to fix the record-cycle leak, and unstick the incognito upload modal

Murtaza Nasir72aaaca5571c
diff --git a/config/env.asr.example b/config/env.asr.example
index dcfa5b91..bcea4492 100644
--- a/config/env.asr.example
+++ b/config/env.asr.example
@@ -303,6 +303,17 @@ VIDEO_RETENTION=false
# Maximum number of simultaneous file uploads (default: 3)
MAX_CONCURRENT_UPLOADS=3
+# --- Reliability / Security (optional) ---
+# Hard wall-clock cap (seconds) on any single ffmpeg/ffprobe invocation, so a
+# malformed or adversarial media file can't hang a processing worker forever.
+# Default: 3600 (1 hour).
+# FFMPEG_TIMEOUT_SECONDS=3600
+#
+# Per-endpoint rate limiting on auth routes (login, register, password reset).
+# Set to false only if a reverse proxy in front of Speakr already rate-limits
+# these. Default: true.
+# RATELIMIT_ENABLED=true
+
# --- Server-Side Recording Sessions (optional) ---
# Opt-in: in-app recordings stream audio chunks to the server as they record,
# instead of buffering the entire recording in browser RAM. This enables
diff --git a/config/env.transcription.example b/config/env.transcription.example
index 0cb540ad..298d5f52 100644
--- a/config/env.transcription.example
+++ b/config/env.transcription.example
@@ -385,6 +385,17 @@ VIDEO_RETENTION=false
# Maximum number of simultaneous file uploads (default: 3)
MAX_CONCURRENT_UPLOADS=3
+# --- Reliability / Security (optional) ---
+# Hard wall-clock cap (seconds) on any single ffmpeg/ffprobe invocation, so a
+# malformed or adversarial media file can't hang a processing worker forever.
+# Default: 3600 (1 hour).
+# FFMPEG_TIMEOUT_SECONDS=3600
+#
+# Per-endpoint rate limiting on auth routes (login, register, password reset).
+# Set to false only if a reverse proxy in front of Speakr already rate-limits
+# these. Default: true.
+# RATELIMIT_ENABLED=true
+
# =============================================================================
# SERVER-SIDE RECORDING SESSIONS (optional)
# =============================================================================
diff --git a/config/env.whisper.example b/config/env.whisper.example
index 01082fa3..d83a14a8 100644
--- a/config/env.whisper.example
+++ b/config/env.whisper.example
@@ -299,6 +299,17 @@ VIDEO_RETENTION=false
# Maximum number of simultaneous file uploads (default: 3)
MAX_CONCURRENT_UPLOADS=3
+# --- Reliability / Security (optional) ---
+# Hard wall-clock cap (seconds) on any single ffmpeg/ffprobe invocation, so a
+# malformed or adversarial media file can't hang a processing worker forever.
+# Default: 3600 (1 hour).
+# FFMPEG_TIMEOUT_SECONDS=3600
+#
+# Per-endpoint rate limiting on auth routes (login, register, password reset).
+# Set to false only if a reverse proxy in front of Speakr already rate-limits
+# these. Default: true.
+# RATELIMIT_ENABLED=true
+
# --- Server-Side Recording Sessions (optional) ---
# Opt-in: in-app recordings stream audio chunks to the server as they record,
# instead of buffering the entire recording in browser RAM. This enables
diff --git a/config/env.whisperx.example b/config/env.whisperx.example
index f215d4c6..3fe2d4d2 100644
--- a/config/env.whisperx.example
+++ b/config/env.whisperx.example
@@ -222,6 +222,17 @@ VIDEO_RETENTION=false
# Maximum number of simultaneous file uploads (default: 3)
MAX_CONCURRENT_UPLOADS=3
+# --- Reliability / Security (optional) ---
+# Hard wall-clock cap (seconds) on any single ffmpeg/ffprobe invocation, so a
+# malformed or adversarial media file can't hang a processing worker forever.
+# Default: 3600 (1 hour).
+# FFMPEG_TIMEOUT_SECONDS=3600
+#
+# Per-endpoint rate limiting on auth routes (login, register, password reset).
+# Set to false only if a reverse proxy in front of Speakr already rate-limits
+# these. Default: true.
+# RATELIMIT_ENABLED=true
+
# --- Background Processing Queues ---
# Separate queues for transcription (slow) and summary (fast) jobs
# This prevents slow ASR jobs from blocking quick summary generation
diff --git a/conftest.py b/conftest.py
index 266d5e01..69bb5226 100644
--- a/conftest.py
+++ b/conftest.py
@@ -53,6 +53,12 @@ os.environ["SUMMARY_QUEUE_WORKERS"] = "0"
# NB: do NOT force WEBHOOK_GLOBAL_ENABLED=false here — the webhook suite needs
# delivery enabled (it mocks the actual HTTP POST), so leave the default (true).
+# Disable per-endpoint rate limiting under test: several auth tests POST
+# /login many times from the same client IP within one run, which the real
+# "10 per minute" login limit would reject with 429. Production leaves this
+# enabled (default true).
+os.environ.setdefault("RATELIMIT_ENABLED", "false")
+
import pytest # noqa: E402
diff --git a/src/api/api_v1.py b/src/api/api_v1.py
index 76ab8064..2a80d1c5 100644
--- a/src/api/api_v1.py
+++ b/src/api/api_v1.py
@@ -2206,7 +2206,7 @@ def assign_speakers(recording_id):
except Exception as e:
db.session.rollback()
current_app.logger.error(f"Error assigning speakers for recording {recording_id}: {e}", exc_info=True)
- return jsonify({'error': str(e)}), 500
+ return jsonify({'error': 'An unexpected error occurred'}), 500
@api_v1_bp.route('/recordings/<int:recording_id>/speakers/identify', methods=['POST'])
@@ -2251,7 +2251,7 @@ def identify_speakers(recording_id):
return jsonify({'error': str(ve)}), 503
except Exception as e:
current_app.logger.error(f"Error during auto speaker identification for recording {recording_id}: {e}", exc_info=True)
- return jsonify({'error': f'An unexpected error occurred: {str(e)}'}), 500
+ return jsonify({'error': 'An unexpected error occurred'}), 500
# =============================================================================
diff --git a/src/api/auth.py b/src/api/auth.py
index 661adfbd..42ac1059 100644
--- a/src/api/auth.py
+++ b/src/api/auth.py
@@ -58,13 +58,27 @@ def init_auth_extensions(_bcrypt, _csrf, _limiter):
def rate_limit(limit_string):
- """Decorator that applies rate limiting if limiter is available."""
+ """Decorator that applies a per-endpoint Flask-Limiter limit.
+
+ The limiter is injected via init_auth_extensions AFTER this module is
+ imported (and after the routes below are decorated), so we can't wrap the
+ view with limiter.limit() at decoration time. Instead we apply and cache
+ it lazily on the first request. Previously this decorator was a no-op that
+ only stashed the limit string, so login/register/password-reset ran with
+ only the loose global default — a brute-force exposure.
+ """
def decorator(f):
from functools import wraps
+ state = {'limited': None}
+
@wraps(f)
def wrapper(*args, **kwargs):
+ if limiter is not None and getattr(limiter, 'enabled', True):
+ if state['limited'] is None:
+ state['limited'] = limiter.limit(limit_string)(f)
+ return state['limited'](*args, **kwargs)
return f(*args, **kwargs)
- # Store the limit string for later application
+
wrapper._rate_limit = limit_string
return wrapper
return decorator
diff --git a/src/api/push_notifications.py b/src/api/push_notifications.py
index f7b18ecf..d7521b69 100644
--- a/src/api/push_notifications.py
+++ b/src/api/push_notifications.py
@@ -2,7 +2,7 @@
Push Notification API Endpoints
Handles push notification subscriptions and delivery
"""
-from flask import Blueprint, request, jsonify
+from flask import Blueprint, request, jsonify, current_app
from flask_login import login_required, current_user
from src.database import db
from src.models.push_subscription import PushSubscription
@@ -98,10 +98,10 @@ def subscribe():
except Exception as e:
db.session.rollback()
- print(f"[Push] Subscription error: {e}")
+ current_app.logger.error(f"[Push] Subscription error: {e}", exc_info=True)
return jsonify({
'success': False,
- 'error': str(e)
+ 'error': 'An unexpected error occurred'
}), 500
@@ -142,10 +142,10 @@ def unsubscribe():
except Exception as e:
db.session.rollback()
- print(f"[Push] Unsubscribe error: {e}")
+ current_app.logger.error(f"[Push] Unsubscribe error: {e}", exc_info=True)
return jsonify({
'success': False,
- 'error': str(e)
+ 'error': 'An unexpected error occurred'
}), 500
diff --git a/src/api/recordings.py b/src/api/recordings.py
index 85025998..e484ca33 100644
--- a/src/api/recordings.py
+++ b/src/api/recordings.py
@@ -134,7 +134,11 @@ def _blank_column_condition(column):
def _prefixed_column_condition(column, prefixes):
- return db.or_(*[column.like(f'{prefix}%') for prefix in prefixes])
+ # Escape LIKE metacharacters in the literal prefixes so a '_' or '%' in a
+ # prefix (e.g. 'ERROR_JSON:') matches literally instead of as a wildcard.
+ def _esc(p):
+ return p.replace('\\', '\\\\').replace('%', '\\%').replace('_', '\\_')
+ return db.or_(*[column.like(f'{_esc(prefix)}%', escape='\\') for prefix in prefixes])
def _transcription_error_condition():
@@ -4496,6 +4500,15 @@ def bulk_toggle():
if not recording:
continue
+ # Authorization: only act on recordings the user actually has
+ # access to. Without this, set_user_recording_status would
+ # create a per-user status row for ANY recording id (treating
+ # the caller as a "shared recipient"), leaking a cross-user
+ # existence oracle and polluting the table. Mirrors the single
+ # toggle_inbox / toggle_highlight endpoints.
+ if not has_recording_access(recording, current_user):
+ continue
+
# Use set_user_recording_status which handles both owners and shared users
if field == 'inbox':
set_user_recording_status(recording, current_user, is_inbox=value)
diff --git a/src/api/shares.py b/src/api/shares.py
index 4f1b2725..2fbc1188 100644
--- a/src/api/shares.py
+++ b/src/api/shares.py
@@ -459,8 +459,8 @@ def share_recording_internal(recording_id):
except Exception as e:
db.session.rollback()
- current_app.logger.error(f"Error sharing recording internally: {e}")
- return jsonify({'error': str(e)}), 500
+ current_app.logger.error(f"Error sharing recording internally: {e}", exc_info=True)
+ return jsonify({'error': 'An unexpected error occurred'}), 500
@shares_bp.route('/api/recordings/<int:recording_id>/shares-internal', methods=['GET'])
@@ -582,8 +582,8 @@ def revoke_internal_share(share_id):
except Exception as e:
db.session.rollback()
- current_app.logger.error(f"Error revoking internal share: {e}")
- return jsonify({'error': str(e)}), 500
+ current_app.logger.error(f"Error revoking internal share: {e}", exc_info=True)
+ return jsonify({'error': 'An unexpected error occurred'}), 500
@shares_bp.route('/api/recordings/shared-with-me', methods=['GET'])
diff --git a/src/api/tokens.py b/src/api/tokens.py
index 1c19339b..90598b12 100644
--- a/src/api/tokens.py
+++ b/src/api/tokens.py
@@ -32,12 +32,23 @@ def init_tokens_helpers(_bcrypt, _csrf, _limiter):
def rate_limit(limit_string):
- """Decorator that applies rate limiting if limiter is available."""
+ """Decorator that applies a per-endpoint Flask-Limiter limit.
+
+ Applied lazily because the limiter is injected after this module is
+ imported (see the matching helper in src/api/auth.py). Previously a no-op.
+ """
def decorator(f):
from functools import wraps
+ state = {'limited': None}
+
@wraps(f)
def wrapper(*args, **kwargs):
+ if limiter is not None and getattr(limiter, 'enabled', True):
+ if state['limited'] is None:
+ state['limited'] = limiter.limit(limit_string)(f)
+ return state['limited'](*args, **kwargs)
return f(*args, **kwargs)
+
wrapper._rate_limit = limit_string
return wrapper
return decorator
diff --git a/src/app.py b/src/app.py
index 1e96ff6c..a7bfee51 100644
--- a/src/app.py
+++ b/src/app.py
@@ -174,11 +174,16 @@ _markdown_instance = markdown.Markdown(extensions=[
])
# --- Rate Limiting Setup (will be configured after app creation) ---
-# TEMPORARILY INCREASED FOR TESTING - REVERT FOR PRODUCTION!
+# RATELIMIT_ENABLED (default true) lets the test suite and any deployment that
+# fronts its own rate limiting turn Flask-Limiter off. The per-endpoint auth
+# limits (login/register/password-reset) are applied via the rate_limit
+# decorator in src/api/auth.py and src/api/tokens.py.
+_RATELIMIT_ENABLED = os.environ.get('RATELIMIT_ENABLED', 'true').lower() != 'false'
limiter = Limiter(
get_remote_address,
app=None, # Defer initialization
- default_limits=["5000 per day", "1000 per hour"] # Increased from 200/day, 50/hour for testing
+ default_limits=["5000 per day", "1000 per hour"],
+ enabled=_RATELIMIT_ENABLED,
)
# --- Utility Functions ---
diff --git a/src/audio_chunking.py b/src/audio_chunking.py
index 093a380c..97f70371 100644
--- a/src/audio_chunking.py
+++ b/src/audio_chunking.py
@@ -26,6 +26,14 @@ if TYPE_CHECKING:
# Configure logging
logger = logging.getLogger(__name__)
+# Wall-clock cap on ffmpeg/ffprobe subprocesses in the chunking path. Without
+# it a malformed/adversarial media file can stall the subprocess forever and
+# permanently wedge a job-queue worker. Shares the ffmpeg_utils env knob.
+try:
+ _SUBPROCESS_TIMEOUT_SECONDS = max(30, int(os.getenv('FFMPEG_TIMEOUT_SECONDS', '3600')))
+except (TypeError, ValueError):
+ _SUBPROCESS_TIMEOUT_SECONDS = 3600
+
@dataclass
class EffectiveChunkingConfig:
@@ -340,11 +348,11 @@ class AudioChunkingService:
result = subprocess.run([
'ffprobe', '-v', 'error', '-show_entries', 'format=duration',
'-of', 'default=noprint_wrappers=1:nokey=1', file_path
- ], capture_output=True, text=True, check=True)
-
+ ], capture_output=True, text=True, check=True, timeout=_SUBPROCESS_TIMEOUT_SECONDS)
+
duration = float(result.stdout.strip())
return duration
- except (subprocess.CalledProcessError, ValueError, FileNotFoundError) as e:
+ except (subprocess.CalledProcessError, subprocess.TimeoutExpired, ValueError, FileNotFoundError) as e:
logger.error(f"Error getting audio duration for {file_path}: {e}")
return None
@@ -608,7 +616,11 @@ class AudioChunkingService:
chunk_path
]
- result = subprocess.run(cmd, capture_output=True, text=True)
+ try:
+ result = subprocess.run(cmd, capture_output=True, text=True, timeout=_SUBPROCESS_TIMEOUT_SECONDS)
+ except subprocess.TimeoutExpired:
+ logger.error(f"ffmpeg timed out extracting chunk {chunk_index} after {_SUBPROCESS_TIMEOUT_SECONDS}s")
+ continue
if result.returncode != 0:
logger.error(f"ffmpeg failed for chunk {chunk_index}: {result.stderr}")
continue
@@ -810,9 +822,9 @@ class AudioChunkingService:
'-show_format', '-show_streams', chunk_path
]
- result = subprocess.run(cmd, capture_output=True, text=True, check=True)
+ result = subprocess.run(cmd, capture_output=True, text=True, check=True, timeout=_SUBPROCESS_TIMEOUT_SECONDS)
probe_data = json.loads(result.stdout)
-
+
audio_stream = None
for stream in probe_data.get('streams', []):
if stream.get('codec_type') == 'audio':
@@ -984,7 +996,7 @@ def get_audio_duration_ffprobe(file_path: str) -> Optional[float]:
result = subprocess.run([
'ffprobe', '-v', 'error', '-show_entries', 'format=duration',
'-of', 'default=noprint_wrappers=1:nokey=1', file_path
- ], capture_output=True, text=True, check=True)
+ ], capture_output=True, text=True, check=True, timeout=_SUBPROCESS_TIMEOUT_SECONDS)
return float(result.stdout.strip())
except Exception:
return None
@@ -1129,7 +1141,11 @@ def extract_speaker_samples(
sample_path
]
- result = subprocess.run(cmd, capture_output=True, text=True)
+ try:
+ result = subprocess.run(cmd, capture_output=True, text=True, timeout=_SUBPROCESS_TIMEOUT_SECONDS)
+ except subprocess.TimeoutExpired:
+ logger.error(f"ffmpeg timed out extracting sample for speaker {speaker} after {_SUBPROCESS_TIMEOUT_SECONDS}s")
+ continue
if result.returncode != 0:
logger.error(f"Failed to extract sample for speaker {speaker}: {result.stderr}")
continue
diff --git a/src/services/recording_stitch.py b/src/services/recording_stitch.py
index 15df6d9a..59c7d4e3 100644
--- a/src/services/recording_stitch.py
+++ b/src/services/recording_stitch.py
@@ -296,13 +296,14 @@ def _apply_finalize_metadata(recording, metadata):
return metadata
-def stitch_recording_session(session_id: str) -> Tuple[int, str]:
- """Stitch a session's chunks into a final audio file.
-
- Returns ``(recording_id, audio_path)`` on success. Raises
- :class:`StitchError` on any failure; the caller (job_queue worker)
- is responsible for updating the Recording row's status and
- surfacing the error to the user.
+def stitch_recording_session(session_id: str) -> Tuple[int, str, dict]:
+ """Stitch a session's chunks into a final media file.
+
+ Returns ``(recording_id, media_path, metadata)`` on success, where
+ ``metadata`` is the parsed finalize metadata used to kick off the
+ downstream transcribe job. Raises :class:`StitchError` on any failure;
+ the caller (job_queue worker) is responsible for updating the Recording
+ row's status and surfacing the error to the user.
"""
session = db.session.get(RecordingSession, session_id)
if not session:
diff --git a/src/services/webhook_dispatch.py b/src/services/webhook_dispatch.py
index c581a679..70918f5d 100644
--- a/src/services/webhook_dispatch.py
+++ b/src/services/webhook_dispatch.py
@@ -299,6 +299,20 @@ def _post_delivery(delivery: WebhookDelivery, webhook: Webhook) -> tuple:
On network/timeout error, response_status is None and error is set.
"""
body_bytes = (delivery.payload or '').encode('utf-8')
+
+ # Re-validate the URL at SEND time, not just at create/update. The
+ # create-time check can be defeated by DNS rebinding: register a webhook on
+ # a domain that resolves to a public IP when validated, then repoint it at
+ # 127.0.0.1 / 169.254.169.254 / an internal host before delivery. Re-running
+ # the resolve-and-block check immediately before the POST closes that window
+ # (the stored response preview is readable back via the deliveries API, so
+ # an internal target would otherwise be an exfiltration channel). A transient
+ # DNS failure is NOT treated as a block — no resolution means no connection
+ # and thus no SSRF; we let requests surface it as a normal network error.
+ safe, reason = is_url_safe_for_webhook(webhook.url, allow_http=bool(webhook.allow_http))
+ if not safe and 'resolves to a private' in reason:
+ return None, None, f'blocked at delivery: {reason}'[:500]
+
signature = sign_payload(webhook.secret, body_bytes)
headers = {
'Content-Type': 'application/json',
diff --git a/src/tasks/processing.py b/src/tasks/processing.py
index 0d5e4ae6..c44bcc98 100644
--- a/src/tasks/processing.py
+++ b/src/tasks/processing.py
@@ -850,12 +850,18 @@ Summarization Instructions:
db.session.commit()
current_app.logger.info(f"Summarization completed for recording {recording_id} in {recording.summarization_duration_seconds}s.")
- # Apply auto-shares for group tags after processing completes
- apply_team_tag_auto_shares(recording_id)
-
- # Export to file if auto-export is enabled
- if ENABLE_AUTO_EXPORT:
- export_recording(recording_id)
+ # Best-effort post-completion side effects. The recording is
+ # already committed COMPLETED with a good summary; if either of
+ # these throws it must NOT bubble to the outer except, which
+ # would overwrite the summary with an error and flip the row to
+ # FAILED (a genuinely-complete recording corrupted by a share/
+ # export hiccup).
+ try:
+ apply_team_tag_auto_shares(recording_id)
+ if ENABLE_AUTO_EXPORT:
+ export_recording(recording_id)
+ except Exception as post_err:
+ current_app.logger.error(f"Post-completion step failed for recording {recording_id} (recording stays COMPLETED): {post_err}")
else:
current_app.logger.warning(f"Empty summary generated for recording {recording_id}")
recording.summary = "[Summary not generated]"
@@ -865,12 +871,14 @@ Summarization Instructions:
recording.summarization_duration_seconds = int(summarization_end_time - summarization_start_time)
db.session.commit()
- # Apply auto-shares for group tags after processing completes
- apply_team_tag_auto_shares(recording_id)
-
- # Export to file if auto-export is enabled (even with empty summary, transcription may be useful)
- if ENABLE_AUTO_EXPORT:
- export_recording(recording_id)
+ # Best-effort post-completion side effects (see the non-empty
+ # branch above): must not corrupt the completed recording.
+ try:
+ apply_team_tag_auto_shares(recording_id)
+ if ENABLE_AUTO_EXPORT:
+ export_recording(recording_id)
+ except Exception as post_err:
+ current_app.logger.error(f"Post-completion step failed for recording {recording_id} (recording stays COMPLETED): {post_err}")
# Process chunks for semantic search after completion (if inquire mode is enabled).
# Mirrors the non-summary path in generate_title_task; without this, Inquire
@@ -2122,12 +2130,19 @@ def transcribe_with_connector(app_context, recording_id, filepath, original_file
except OSError:
pass # Best effort cleanup
- # Clean up temp audio extracted from video when video retention is enabled
- if is_video and effective_video_retention and audio_filepath and audio_filepath != filepath:
+ # Clean up temp audio extracted from a video container. This covers
+ # BOTH the video-retention branch and the legacy non-retention
+ # extract branch: in both, audio_filepath is a local temp file
+ # distinct from filepath (the retention branch keeps the video as
+ # filepath; the legacy branch already uploaded the extracted audio
+ # to storage), so the local copy is always safe to remove after
+ # transcription. Previously this was gated on effective_video_retention,
+ # leaking the legacy branch's _audio.* into UPLOAD_FOLDER.
+ if is_video and audio_filepath and audio_filepath != filepath:
try:
if os.path.exists(audio_filepath):
os.remove(audio_filepath)
- current_app.logger.info(f"Cleaned up temp audio from video retention: {audio_filepath}")
+ current_app.logger.info(f"Cleaned up temp audio extracted from video: {audio_filepath}")
except OSError:
pass # Best effort cleanup
@@ -2282,6 +2297,20 @@ def transcribe_with_connector(app_context, recording_id, filepath, original_file
except Exception:
pass # Don't fail the error handling if we can't get timeout info
+ # Clean up derived temp files on the failure path too. The success
+ # path removes these below the retry loop, but a raised transcription
+ # error skips straight here — previously orphaning the converted MP3
+ # and the retained-video extracted audio (up to one per retry) in
+ # UPLOAD_FOLDER on the local backend.
+ for _tmp in (locals().get('converted_filepath'), locals().get('audio_filepath')):
+ if _tmp and _tmp != filepath:
+ try:
+ if os.path.exists(_tmp):
+ os.remove(_tmp)
+ current_app.logger.debug(f"Cleaned up temp file on failure path: {_tmp}")
+ except OSError:
+ pass
+
# Don't set recording.status = 'FAILED' here - let the job queue handle it
# The job queue will decide whether to retry or permanently fail,
# and only set FAILED status when all retries are exhausted
@@ -2380,6 +2409,13 @@ def transcribe_incognito(filepath, original_filename, language=None, min_speaker
'error': None
}
+ # Derived temp files this function creates (extracted audio from video,
+ # converted audio). The route only deletes the original upload temp, so
+ # these must be cleaned here — otherwise every incognito request on a
+ # video/convertible file leaves decoded audio in /tmp, which is both a
+ # disk leak and a violation of the incognito no-retention guarantee.
+ _incognito_derived_files = []
+
try:
# Get the active connector
registry = get_registry()
@@ -2422,6 +2458,8 @@ def transcribe_incognito(filepath, original_filename, language=None, min_speaker
actual_filepath = audio_filepath
actual_content_type = audio_mime_type
actual_filename = os.path.basename(audio_filepath)
+ if audio_filepath and audio_filepath != filepath:
+ _incognito_derived_files.append(audio_filepath)
except Exception as e:
current_app.logger.error(f"[Incognito] Failed to extract audio from video: {e}")
raise
@@ -2447,6 +2485,9 @@ def transcribe_incognito(filepath, original_filename, language=None, min_speaker
if conversion_result.was_converted:
current_app.logger.info(f"[Incognito] Audio converted: {conversion_result.original_codec} -> {conversion_result.final_codec}")
+ out_path = conversion_result.output_path
+ if out_path and out_path not in (filepath, actual_filepath):
+ _incognito_derived_files.append(out_path)
actual_filepath = conversion_result.output_path
actual_content_type = conversion_result.mime_type
actual_filename = os.path.basename(conversion_result.output_path)
@@ -2528,6 +2569,19 @@ def transcribe_incognito(filepath, original_filename, language=None, min_speaker
result['processing_time_seconds'] = int(time.time() - start_time)
return result
+ finally:
+ # Delete the derived temp files (extracted/converted audio) this
+ # function created. The original upload temp is owned and removed by
+ # the route's finally; we must never delete `filepath` here.
+ for _tmp in _incognito_derived_files:
+ if _tmp and _tmp != filepath:
+ try:
+ if os.path.exists(_tmp):
+ os.remove(_tmp)
+ current_app.logger.info(f"[Incognito] Derived temp file deleted: {_tmp}")
+ except OSError as _e:
+ current_app.logger.error(f"[Incognito] Failed to delete derived temp file {_tmp}: {_e}")
+
def _generate_incognito_title(transcription_text, user=None):
"""Generate a title for incognito recording without database storage."""
diff --git a/src/utils/ffmpeg_utils.py b/src/utils/ffmpeg_utils.py
index 50725280..797b7d36 100644
--- a/src/utils/ffmpeg_utils.py
+++ b/src/utils/ffmpeg_utils.py
@@ -14,6 +14,15 @@ DEFAULT_SAMPLE_RATE = os.getenv('AUDIO_SAMPLE_RATE', '44100')
DEFAULT_CHANNELS = int(os.getenv('AUDIO_CHANNELS', '1')) # Mono for speech
DEFAULT_COMPRESSION_LEVEL = int(os.getenv('AUDIO_COMPRESSION_LEVEL', '2'))
+# Hard wall-clock cap on any single ffmpeg invocation. Without it a malformed
+# or adversarial media file can stall ffmpeg forever and permanently wedge a
+# job-queue worker thread. 1 hour is generous for conversion/extraction of
+# even multi-hour recordings while still guaranteeing eventual recovery.
+try:
+ FFMPEG_TIMEOUT_SECONDS = max(30, int(os.getenv('FFMPEG_TIMEOUT_SECONDS', '3600')))
+except (TypeError, ValueError):
+ FFMPEG_TIMEOUT_SECONDS = 3600
+
class FFmpegError(Exception):
"""Custom exception for FFmpeg-related errors."""
@@ -433,15 +442,24 @@ def _run_ffmpeg_command(cmd: list, operation_description: str) -> None:
cmd,
check=True,
capture_output=True,
- text=True
+ text=True,
+ timeout=FFMPEG_TIMEOUT_SECONDS,
)
current_app.logger.debug(f"FFmpeg {operation_description} completed successfully")
-
+
except FileNotFoundError:
error_msg = "FFmpeg not found. Please ensure FFmpeg is installed and in the system's PATH."
current_app.logger.error(error_msg)
raise FFmpegNotFoundError(error_msg)
-
+
+ except subprocess.TimeoutExpired:
+ # subprocess.run already kills the process on timeout. Surface as a
+ # normal FFmpegError so the worker fails the job cleanly instead of
+ # hanging forever on a stalled/adversarial input.
+ error_msg = f"{operation_description} timed out after {FFMPEG_TIMEOUT_SECONDS}s"
+ current_app.logger.error(f"FFmpeg error: {error_msg}")
+ raise FFmpegError(error_msg)
+
except subprocess.CalledProcessError as e:
error_msg = f"{operation_description} failed: {e.stderr}"
current_app.logger.error(f"FFmpeg error: {error_msg}")
diff --git a/src/utils/ffprobe.py b/src/utils/ffprobe.py
index 08add8b8..0bdcbce0 100644
--- a/src/utils/ffprobe.py
+++ b/src/utils/ffprobe.py
@@ -7,6 +7,7 @@ structured information about their codecs, streams, and formats.
import json
import logging
+import os
import subprocess
from datetime import datetime
from typing import Optional, Dict, Any, Tuple
@@ -37,12 +38,17 @@ def probe(filename: str, cmd: str = 'ffprobe', timeout: Optional[int] = None) ->
args = [cmd, '-show_format', '-show_streams', '-of', 'json', filename]
p = None
+ # Always bound the probe: a caller that passes no explicit timeout still
+ # must not be able to hang a worker forever on a stalled/adversarial file.
+ if timeout is None:
+ try:
+ timeout = max(10, int(os.getenv('FFPROBE_TIMEOUT_SECONDS', '60')))
+ except (TypeError, ValueError):
+ timeout = 60
+
try:
p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
- communicate_kwargs = {}
- if timeout is not None:
- communicate_kwargs['timeout'] = timeout
- out, err = p.communicate(**communicate_kwargs)
+ out, err = p.communicate(timeout=timeout)
if p.returncode != 0:
error_msg = err.decode('utf-8', errors='ignore')
diff --git a/static/js/modules/composables/audio.js b/static/js/modules/composables/audio.js
index 47427e83..c8c84e79 100644
--- a/static/js/modules/composables/audio.js
+++ b/static/js/modules/composables/audio.js
@@ -160,6 +160,33 @@ export function useAudio(state, utils) {
if (recordingVideoActive) recordingVideoActive.value = false;
}
+ // Close the recording AudioContext and drop the analyser nodes. Browsers
+ // cap concurrent AudioContexts (~6 in Chromium); without this, a handful
+ // of record→stop cycles without a page reload exhausts the pool and
+ // `new AudioContext()` throws, killing recording until reload. Called on
+ // stop, discard, and the start-error path.
+ function _releaseAudioContext() {
+ if (audioContext.value) {
+ try { audioContext.value.close(); } catch (_) { /* already closed */ }
+ audioContext.value = null;
+ }
+ analyser.value = null;
+ if (micAnalyser) micAnalyser.value = null;
+ if (systemAnalyser) systemAnalyser.value = null;
+ }
+
+ // Stop any tracks still held on the pre-disclosure display stream. The
+ // display capture is acquired up front (Firefox transient-activation
+ // requirement) and parked in pendingDisplayStream; if start then fails
+ // before it's consumed, the browser's "sharing your screen" indicator
+ // would otherwise stay on with the tracks never released.
+ function _stopPendingDisplayStream() {
+ if (pendingDisplayStream) {
+ try { pendingDisplayStream.getTracks().forEach(t => t.stop()); } catch (_) {}
+ pendingDisplayStream = null;
+ }
+ }
+
// iOS detection
const isiOS = () => {
return /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;
@@ -830,6 +857,12 @@ export function useAudio(state, utils) {
});
activeStreams.value = [];
}
+ // Also release the display stream grabbed before the failure point
+ // (e.g. 'both' mode where the mic getUserMedia rejects after the
+ // screen share was already acquired) and the AudioContext.
+ _stopPendingDisplayStream();
+ _clearVideoPreview();
+ _releaseAudioContext();
}
};
@@ -858,6 +891,10 @@ export function useAudio(state, utils) {
activeStreams.value = [];
}
+ // Close the AudioContext so repeated record→stop cycles don't
+ // exhaust the browser's context pool.
+ _releaseAudioContext();
+
// Release wake lock
await releaseWakeLock();
@@ -1133,6 +1170,10 @@ export function useAudio(state, utils) {
// Auto-select the incognito recording and switch to detail view
selectedRecording.value = incognitoData;
currentView.value = 'detail';
+ // discardRecording() re-opened the upload modal (its normal
+ // return-to-form behaviour); close it here so it doesn't cover the
+ // finished incognito recording. Every other incognito path does this.
+ if (showUploadModal) showUploadModal.value = false;
// Reset incognito mode toggle
incognitoMode.value = false;
@@ -1147,12 +1188,26 @@ export function useAudio(state, utils) {
setGlobalError(`Incognito processing failed: ${error.message}`);
} finally {
incognitoProcessing.value = false;
+ // Reset the shared processing-progress state so it isn't left
+ // pinned at 100% / "ready" for the next operation.
+ processingProgress.value = 0;
+ processingMessage.value = '';
}
};
// Discard recording
const discardRecording = async () => {
_clearVideoPreview();
+ _stopPendingDisplayStream();
+ _releaseAudioContext();
+ // Stop any still-live capture tracks (e.g. discarding while the tab
+ // stayed on the finished-review pane with tracks not yet stopped).
+ if (activeStreams.value.length > 0) {
+ activeStreams.value.forEach(stream => {
+ try { stream.getTracks().forEach(track => track.stop()); } catch (_) {}
+ });
+ activeStreams.value = [];
+ }
if (audioBlobURL.value) {
URL.revokeObjectURL(audioBlobURL.value);
}
diff --git a/tests/test_ffmpeg_timeout.py b/tests/test_ffmpeg_timeout.py
new file mode 100644
index 00000000..d5fc4d19
--- /dev/null
+++ b/tests/test_ffmpeg_timeout.py
@@ -0,0 +1,79 @@
+#!/usr/bin/env python3
+"""
+Regression tests for the ffmpeg/ffprobe subprocess timeout hardening.
+
+An ffmpeg invocation with no timeout can hang a job-queue worker forever on a
+malformed/adversarial media file. These verify the shared executor now bounds
+every call and translates a timeout into a clean FFmpegError instead of
+blocking indefinitely.
+
+Hermetic: subprocess is mocked, no real ffmpeg needed.
+"""
+
+import subprocess
+import sys
+import os
+from unittest import mock
+
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+
+from src.app import app
+from src.utils import ffmpeg_utils
+from src.utils.ffmpeg_utils import _run_ffmpeg_command, FFmpegError
+
+
+def test_run_ffmpeg_passes_timeout():
+ with app.app_context():
+ with mock.patch("src.utils.ffmpeg_utils.subprocess.run") as m:
+ m.return_value = subprocess.CompletedProcess(args=[], returncode=0, stdout="", stderr="")
+ _run_ffmpeg_command(["ffmpeg", "-i", "x"], "test op")
+ assert m.call_count == 1
+ _, kwargs = m.call_args
+ assert kwargs.get("timeout") == ffmpeg_utils.FFMPEG_TIMEOUT_SECONDS
+ assert kwargs.get("timeout") and kwargs["timeout"] > 0
+
+
+def test_run_ffmpeg_timeout_raises_ffmpeg_error():
+ with app.app_context():
+ with mock.patch("src.utils.ffmpeg_utils.subprocess.run",
+ side_effect=subprocess.TimeoutExpired(cmd="ffmpeg", timeout=1)):
+ try:
+ _run_ffmpeg_command(["ffmpeg", "-i", "x"], "stalled op")
+ assert False, "expected FFmpegError on timeout"
+ except FFmpegError as e:
+ assert "timed out" in str(e).lower()
+
+
+def test_ffprobe_probe_defaults_to_a_bounded_timeout():
+ """probe() with no explicit timeout must still bound the call so a caller
+ that forgot to pass one can't hang forever."""
+ from src.utils import ffprobe
+
+ captured = {}
+
+ class FakeProc:
+ returncode = 0
+
+ def communicate(self, timeout=None):
+ captured["timeout"] = timeout
+ return b'{"streams": [], "format": {}}', b""
+
+ def kill(self):
+ pass
+
+ with mock.patch("src.utils.ffprobe.subprocess.Popen", return_value=FakeProc()):
+ ffprobe.probe("/tmp/x.mp3") # no timeout arg
+ assert captured["timeout"] is not None and captured["timeout"] > 0
+
+
+if __name__ == "__main__":
+ failures = 0
+ for name, fn in sorted(globals().items()):
+ if name.startswith("test_") and callable(fn):
+ try:
+ fn()
+ print(f"PASS {name}")
+ except AssertionError as e:
+ failures += 1
+ print(f"FAIL {name}: {e}")
+ sys.exit(1 if failures else 0)
diff --git a/tests/test_security_audit_fixes.py b/tests/test_security_audit_fixes.py
new file mode 100644
index 00000000..65a9de7e
--- /dev/null
+++ b/tests/test_security_audit_fixes.py
@@ -0,0 +1,229 @@
+#!/usr/bin/env python3
+"""
+Regression tests for the security-audit fixes.
+
+Covers:
+ - bulk_toggle IDOR: a user cannot toggle inbox/highlight on another user's
+ recording, and no SharedRecordingState row is created for it.
+ - rate_limit decorator actually applies a Flask-Limiter limit (it was a
+ silent no-op, leaving auth endpoints without per-endpoint limits).
+ - Webhook delivery re-validates the URL at SEND time, blocking a target that
+ resolves to a private/loopback address (DNS-rebinding SSRF).
+
+Standalone style (no pytest fixtures), matching the neighbouring suites.
+"""
+
+import secrets
+import sys
+import os
+from unittest.mock import patch, MagicMock
+
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+
+from src.app import app, db
+from src.models import User, Recording
+from src.models.sharing import SharedRecordingState
+
+# The bulk-toggle endpoint is a session-cookie POST guarded by CSRF; disable
+# CSRF for this suite so the test client can exercise it directly (matches the
+# other endpoint suites).
+app.config["WTF_CSRF_ENABLED"] = False
+
+
+def _make_user(suffix):
+ username = f"secfix_{suffix}_{secrets.token_hex(3)}"
+ user = User(username=username, email=f"{username}@local.test")
+ db.session.add(user)
+ db.session.commit()
+ return user
+
+
+def _login(client, user):
+ with client.session_transaction() as sess:
+ sess["_user_id"] = str(user.id)
+ sess["_fresh"] = True
+
+
+# ---------------------------------------------------------------------------
+# bulk_toggle IDOR
+# ---------------------------------------------------------------------------
+
+
+def test_bulk_toggle_ignores_other_users_recording():
+ with app.app_context():
+ owner = _make_user("owner")
+ attacker = _make_user("attacker")
+ victim_rec = Recording(user_id=owner.id, title="victim", status="COMPLETED")
+ db.session.add(victim_rec)
+ db.session.commit()
+ rec_id = victim_rec.id
+
+ client = app.test_client()
+ _login(client, attacker)
+ try:
+ resp = client.post("/api/recordings/bulk-toggle",
+ json={"recording_ids": [rec_id], "field": "highlight", "value": True})
+ assert resp.status_code == 200, resp.data
+ body = resp.get_json()
+ # The victim's recording must NOT be reported as affected...
+ assert rec_id not in body.get("affected_ids", [])
+ # ...and no per-user status row may have been created for the attacker.
+ leaked = SharedRecordingState.query.filter_by(
+ user_id=attacker.id, recording_id=rec_id).first()
+ assert leaked is None, "bulk_toggle created a status row for an inaccessible recording"
+ finally:
+ SharedRecordingState.query.filter_by(recording_id=rec_id).delete()
+ db.session.delete(db.session.get(Recording, rec_id))
+ db.session.delete(db.session.get(User, attacker.id))
+ db.session.delete(db.session.get(User, owner.id))
+ db.session.commit()
+
+
+def test_bulk_toggle_still_works_for_own_recording():
+ with app.app_context():
+ owner = _make_user("selfowner")
+ rec = Recording(user_id=owner.id, title="mine", status="COMPLETED")
+ db.session.add(rec)
+ db.session.commit()
+ rec_id = rec.id
+
+ client = app.test_client()
+ _login(client, owner)
+ try:
+ resp = client.post("/api/recordings/bulk-toggle",
+ json={"recording_ids": [rec_id], "field": "highlight", "value": True})
+ assert resp.status_code == 200, resp.data
+ assert rec_id in resp.get_json().get("affected_ids", [])
+ finally:
+ SharedRecordingState.query.filter_by(recording_id=rec_id).delete()
+ db.session.delete(db.session.get(Recording, rec_id))
+ db.session.delete(db.session.get(User, owner.id))
+ db.session.commit()
+
+
+# ---------------------------------------------------------------------------
+# rate_limit decorator actually applies a limit
+# ---------------------------------------------------------------------------
+
+
+def test_rate_limit_decorator_applies_limiter_limit():
+ """The auth rate_limit decorator must call limiter.limit() (previously it
+ was a no-op that only stashed the string on the wrapper)."""
+ import src.api.auth as auth_mod
+
+ calls = {"limit_arg": None, "applied": False}
+
+ class FakeLimiter:
+ enabled = True
+
+ def limit(self, limit_string):
+ calls["limit_arg"] = limit_string
+
+ def deco(f):
+ def wrapped(*a, **k):
+ calls["applied"] = True
+ return f(*a, **k)
+ return wrapped
+ return deco
+
+ original = auth_mod.limiter
+ auth_mod.limiter = FakeLimiter()
+ try:
+ @auth_mod.rate_limit("7 per minute")
+ def view():
+ return "ok"
+
+ assert view() == "ok"
+ assert calls["applied"] is True, "limiter.limit() was never applied — decorator is a no-op"
+ assert calls["limit_arg"] == "7 per minute"
+ assert getattr(view, "_rate_limit", None) == "7 per minute"
+ finally:
+ auth_mod.limiter = original
+
+
+def test_rate_limit_decorator_passthrough_when_disabled():
+ """When the limiter is disabled, the decorator must not block the view."""
+ import src.api.auth as auth_mod
+
+ class DisabledLimiter:
+ enabled = False
+
+ def limit(self, _): # pragma: no cover - must not be called
+ raise AssertionError("limiter.limit called while disabled")
+
+ original = auth_mod.limiter
+ auth_mod.limiter = DisabledLimiter()
+ try:
+ @auth_mod.rate_limit("1 per minute")
+ def view():
+ return "ok"
+
+ for _ in range(5):
+ assert view() == "ok"
+ finally:
+ auth_mod.limiter = original
+
+
+# ---------------------------------------------------------------------------
+# Webhook delivery-time SSRF re-validation
+# ---------------------------------------------------------------------------
+
+
+def test_webhook_delivery_blocks_private_ip_at_send_time():
+ """_post_delivery must re-validate the URL and refuse to POST to a target
+ that resolves to a private/loopback address, even if it passed at create
+ time (DNS rebinding)."""
+ from src.services import webhook_dispatch
+
+ wh = MagicMock()
+ wh.url = "http://127.0.0.1:8080/internal"
+ wh.allow_http = True
+ wh.secret = "s"
+ delivery = MagicMock()
+ delivery.payload = '{"x":1}'
+ delivery.event_id = "evt_1"
+ delivery.event_type = "recording.completed"
+
+ with app.app_context():
+ with patch("src.services.webhook_dispatch.requests.post") as mock_post:
+ status, preview, error = webhook_dispatch._post_delivery(delivery, wh)
+ assert mock_post.call_count == 0, "POST was sent to a private-IP target"
+ assert status is None and preview is None
+ assert error and "blocked at delivery" in error
+
+
+def test_webhook_delivery_allows_public_host():
+ """A public host must still be delivered to (POST is called)."""
+ from src.services import webhook_dispatch
+
+ wh = MagicMock()
+ wh.url = "https://example.com/hook"
+ wh.allow_http = False
+ wh.secret = "s"
+ delivery = MagicMock()
+ delivery.payload = '{"x":1}'
+ delivery.event_id = "evt_2"
+ delivery.event_type = "recording.completed"
+
+ with app.app_context():
+ with patch("src.services.webhook_dispatch.requests.post",
+ return_value=MagicMock(status_code=204, text="")) as mock_post:
+ status, preview, error = webhook_dispatch._post_delivery(delivery, wh)
+ # example.com resolves publicly; if DNS is unavailable the guard
+ # falls through (transient failure is not a block) and the POST is
+ # still attempted — either way the POST must be reached.
+ assert mock_post.call_count == 1
+ assert error is None
+
+
+if __name__ == "__main__":
+ failures = 0
+ for name, fn in sorted(globals().items()):
+ if name.startswith("test_") and callable(fn):
+ try:
+ fn()
+ print(f"PASS {name}")
+ except AssertionError as e:
+ failures += 1
+ print(f"FAIL {name}: {e}")
+ sys.exit(1 if failures else 0)
diff --git a/tests/test_video_passthrough.py b/tests/test_video_passthrough.py
index 6f5fcf02..1f317427 100644
--- a/tests/test_video_passthrough.py
+++ b/tests/test_video_passthrough.py
@@ -234,12 +234,12 @@ class TestRetentionNotBroken(unittest.TestCase):
self.assertIn('extract_audio_from_video(filepath)', video_block)
def test_temp_audio_cleanup_still_present(self):
- """Temp audio from retention is still cleaned up after transcription.
- After the per-upload keep_audio_only override landed, the cleanup
- branch checks effective_video_retention (env var AND per-recording
- flag) rather than VIDEO_RETENTION directly."""
- self.assertIn('is_video and effective_video_retention and audio_filepath', PROCESSING_MAIN)
- self.assertIn('Cleaned up temp audio from video retention', PROCESSING_MAIN)
+ """Temp audio extracted from a video container is still cleaned up
+ after transcription. The condition was broadened to also cover the
+ legacy non-retention extract branch (which previously leaked), so it
+ no longer gates on effective_video_retention."""
+ self.assertIn('is_video and audio_filepath and audio_filepath != filepath', PROCESSING_MAIN)
+ self.assertIn('Cleaned up temp audio extracted from video', PROCESSING_MAIN)
# ===========================================================================
diff --git a/tests/test_video_retention.py b/tests/test_video_retention.py
index 7f9b33e0..ae55f082 100644
--- a/tests/test_video_retention.py
+++ b/tests/test_video_retention.py
@@ -89,14 +89,16 @@ class TestProcessingPipelineVideoRetention(unittest.TestCase):
)
def test_temp_audio_cleanup_after_transcription(self):
- """Temp audio from video retention is cleaned up after transcription.
+ """Temp audio extracted from a video container is cleaned up after
+ transcription.
- After the per-upload keep_audio_only override was added, the
- cleanup branch checks the effective (per-recording) retention
- flag rather than the global env var directly.
+ The cleanup condition was broadened to cover BOTH the retention branch
+ and the legacy non-retention extract branch (the latter previously
+ leaked its _audio.* into UPLOAD_FOLDER), so it no longer gates on
+ effective_video_retention.
"""
- self.assertIn('is_video and effective_video_retention and audio_filepath', self.content)
- self.assertIn('Cleaned up temp audio from video retention', self.content)
+ self.assertIn('is_video and audio_filepath and audio_filepath != filepath', self.content)
+ self.assertIn('Cleaned up temp audio extracted from video', self.content)
def test_audio_filepath_initialized_to_none(self):
"""audio_filepath is initialized to None before the is_video check."""