Skip to content

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

Python

Recordings served only as audio or video, never as a page (#438)

Murtaza Nasir2dda803e6141
diff --git a/src/api/api_v1.py b/src/api/api_v1.py
index 82a92a17..c0c1400e 100644
--- a/src/api/api_v1.py
+++ b/src/api/api_v1.py
@@ -44,6 +44,7 @@ from src.api.recordings import (
upload_file as _upload_file_ui,
)
from src.services.storage import get_storage_service
+from src.utils.mime import served_media_mime, sandbox_media_response
from src.utils.token_auth import load_user_from_token_value
# Create blueprint with /api/v1 prefix
@@ -3372,7 +3373,7 @@ def download_audio(recording_id):
delivery = storage.get_audio_delivery(
recording.audio_path,
download=download,
- mime_type=recording.mime_type or 'audio/mpeg',
+ mime_type=served_media_mime(recording.mime_type or 'audio/mpeg'),
download_name=safe_download_name,
is_public=False,
)
@@ -3383,12 +3384,12 @@ def download_audio(recording_id):
if not delivery.local_path or not os.path.exists(delivery.local_path):
return jsonify({'error': 'Audio file not found'}), 404
- return send_file(
+ return sandbox_media_response(send_file(
delivery.local_path,
- mimetype=recording.mime_type or 'audio/mpeg',
+ mimetype=served_media_mime(recording.mime_type or 'audio/mpeg'),
as_attachment=download,
download_name=safe_download_name,
- )
+ ))
# =============================================================================
diff --git a/src/api/recordings.py b/src/api/recordings.py
index 06388006..224ef556 100644
--- a/src/api/recordings.py
+++ b/src/api/recordings.py
@@ -52,6 +52,7 @@ from src.services.document import process_markdown_to_docx
from src.services.llm import client, chat_client, call_llm_completion, call_chat_completion, process_streaming_with_thinking, TokenBudgetExceeded
from src.services.embeddings import process_recording_chunks
from src.file_exporter import export_recording, mark_export_as_deleted
+from src.utils.mime import served_media_mime, sandbox_media_response
from src.utils.ffprobe import get_codec_info, get_creation_date, get_duration, try_repair_malformed_webm, FFProbeError
from src.utils.audio_conversion import convert_if_needed
from src.services.storage import get_storage_service
@@ -2577,6 +2578,13 @@ def ingest_uploaded_recording(
current_app.logger.info(f"Resolved video mime {mime_type!r} -> {corrected!r} from container for {filepath}")
mime_type = corrected
+ # The extension is the uploader's choice: an audio file named .html
+ # was stored as text/html (#438). A guess that is not audio or video
+ # is replaced by the type of the contents.
+ if not (mime_type or '').startswith(('audio/', 'video/')):
+ from src.utils.mime import resolve_media_mime
+ mime_type = served_media_mime(resolve_media_mime(filepath, codec_info=codec_info))
+
current_app.logger.info(f"Final MIME type: {mime_type} for file {filepath}")
# Cache media duration while the upload is still available locally.
@@ -3718,10 +3726,11 @@ def get_audio(recording_id):
ext = os.path.splitext(recording.original_filename or '')[1] or '.mp3'
download_name = f"{filename}{ext}"
+ serve_mime = served_media_mime(recording.mime_type, recording.audio_path)
delivery = storage.get_audio_delivery(
recording.audio_path,
download=download,
- mime_type=recording.mime_type,
+ mime_type=serve_mime,
download_name=download_name,
is_public=False,
)
@@ -3734,15 +3743,15 @@ def get_audio(recording_id):
return jsonify({'error': 'Audio file missing from server'}), 404
if download:
- return send_file(
+ return sandbox_media_response(send_file(
delivery.local_path,
as_attachment=True,
download_name=download_name,
- mimetype=recording.mime_type,
+ mimetype=serve_mime,
conditional=True,
- )
+ ))
- return send_file(delivery.local_path, mimetype=recording.mime_type, conditional=True)
+ return sandbox_media_response(send_file(delivery.local_path, mimetype=serve_mime, conditional=True))
except Exception as e:
current_app.logger.error(f"Error serving audio for recording {recording_id}: {e}", exc_info=True)
return jsonify({'error': 'An unexpected error occurred.'}), 500
diff --git a/src/api/shares.py b/src/api/shares.py
index ea97dcce..2e2bd079 100644
--- a/src/api/shares.py
+++ b/src/api/shares.py
@@ -19,6 +19,7 @@ from src.models import Recording, Share, InternalShare, SharedRecordingState, Us
from src.utils import md_to_html
from src.services.storage import get_storage_service
from src.services.public_shares import active_share_or_404
+from src.utils.mime import served_media_mime, sandbox_media_response
# Configuration from environment
ENABLE_PUBLIC_SHARING = os.environ.get('ENABLE_PUBLIC_SHARING', 'true').lower() == 'true'
@@ -159,10 +160,11 @@ def get_shared_audio(public_id):
recording = share.recording
if not recording or not recording.audio_path:
return jsonify({'error': 'Recording or audio file not found'}), 404
+ serve_mime = served_media_mime(recording.mime_type, recording.audio_path)
delivery = get_storage_service().get_audio_delivery(
recording.audio_path,
download=False,
- mime_type=recording.mime_type,
+ mime_type=serve_mime,
download_name=recording.original_filename,
is_public=True,
)
@@ -171,7 +173,7 @@ def get_shared_audio(public_id):
if not delivery.local_path or not os.path.exists(delivery.local_path):
current_app.logger.error(f"Audio file missing from server: {recording.audio_path}")
return jsonify({'error': 'Audio file missing from server'}), 404
- return send_file(delivery.local_path, mimetype=(recording.mime_type or delivery.mimetype), conditional=True)
+ return sandbox_media_response(send_file(delivery.local_path, mimetype=serve_mime, conditional=True))
except HTTPException:
# Let first_or_404() (and any other HTTP error) keep its real status —
# an unknown public_id must stay a 404, not be masked as a 500.
diff --git a/src/utils/mime.py b/src/utils/mime.py
index 53aa7ea0..7ee10cdb 100644
--- a/src/utils/mime.py
+++ b/src/utils/mime.py
@@ -139,3 +139,27 @@ def resolve_media_mime(path, codec_info=None, has_video=None, timeout=10):
return video_mime_for_path(path)
guessed, _ = mimetypes.guess_type(path)
return guessed or 'application/octet-stream'
+
+
+def served_media_mime(mime, path=None):
+ """Content type for serving a stored recording (#438).
+
+ The stored type came from the uploaded file's extension, so an audio file
+ named ``.html`` was stored as ``text/html`` and opened as a page on the
+ app's own origin. Anything other than ``audio/*`` or ``video/*`` is served
+ as ``application/octet-stream``; media elements still play it, and a
+ browser never renders it as a document. Without a stored type, the type is
+ guessed from ``path`` under the same rule.
+ """
+ if not mime and path:
+ mime, _ = mimetypes.guess_type(path)
+ base = (mime or '').split(';')[0].strip().lower()
+ if base.startswith(('audio/', 'video/')):
+ return mime
+ return 'application/octet-stream'
+
+
+def sandbox_media_response(response):
+ """Mark a media response so that it can never run script (#438)."""
+ response.headers['Content-Security-Policy'] = 'sandbox'
+ return response
diff --git a/tests/test_cov_recordings_write.py b/tests/test_cov_recordings_write.py
index 9d543faf..42303a7d 100644
--- a/tests/test_cov_recordings_write.py
+++ b/tests/test_cov_recordings_write.py
@@ -204,6 +204,21 @@ def test_upload_creates_recording_row_with_locator_and_enqueues():
_cleanup(rec, user)
+def test_upload_with_html_extension_is_not_stored_as_html():
+ """An audio file named .html was stored as text/html (#438)."""
+ with app.app_context():
+ user = _mk_user("up_html")
+ client = app.test_client()
+ _login(client, user)
+ staging = os.path.join(app.config["UPLOAD_FOLDER"], f"stg_{uuid.uuid4().hex[:6]}")
+ with _upload_mocks(staging):
+ resp = _do_upload(client, filename="song.mp3.html")
+ assert resp.status_code == 202, resp.data
+ rec = _latest_rec(user)
+ assert rec.mime_type == "application/octet-stream"
+ _cleanup(rec, user)
+
+
def test_upload_default_title_is_placeholder():
with app.app_context():
user = _mk_user("up_title")
diff --git a/tests/test_media_content_type.py b/tests/test_media_content_type.py
new file mode 100644
index 00000000..68668690
--- /dev/null
+++ b/tests/test_media_content_type.py
@@ -0,0 +1,87 @@
+"""Content type of served recordings (#438).
+
+The stored MIME type came from the uploaded file's extension, so an audio file
+named ``.html`` was stored as ``text/html`` and opened as a page on the app's
+own origin from a public share link. Only audio and video types are served as
+such; anything else is served as ``application/octet-stream``, and every media
+response carries ``Content-Security-Policy: sandbox``.
+"""
+
+import os
+import tempfile
+import uuid
+
+import pytest
+
+from src.app import app, db
+from src.models import User, Recording, Share
+from src.utils.mime import served_media_mime
+
+
[email protected]('stored,expected', [
+ ('audio/mpeg', 'audio/mpeg'),
+ ('video/webm', 'video/webm'),
+ ('audio/webm;codecs=opus', 'audio/webm;codecs=opus'),
+ ('text/html', 'application/octet-stream'),
+ ('image/svg+xml', 'application/octet-stream'),
+ ('application/xhtml+xml', 'application/octet-stream'),
+ ('', 'application/octet-stream'),
+])
+def test_served_media_mime(stored, expected):
+ assert served_media_mime(stored) == expected
+
+
+def test_without_a_stored_type_the_path_is_checked_under_the_same_rule():
+ assert served_media_mime(None, '/x/a.mp3') == 'audio/mpeg'
+ assert served_media_mime(None, '/x/a.html') == 'application/octet-stream'
+
+
+def html_named_share():
+ folder = tempfile.mkdtemp(prefix='speakr_mime_')
+ path = os.path.join(folder, 'evil.html')
+ with open(path, 'wb') as f:
+ f.write(b'ID3\x00' + b'<script>alert(1)</script>')
+ with app.app_context():
+ suffix = uuid.uuid4().hex[:8]
+ user = User(username=f'mime_{suffix}', email=f'mime_{suffix}@local.test', password='x')
+ db.session.add(user)
+ db.session.commit()
+ rec = Recording(user_id=user.id, title='t', audio_path=path, status='COMPLETED',
+ mime_type='text/html', original_filename='evil.html')
+ db.session.add(rec)
+ db.session.commit()
+ share = Share(recording_id=rec.id, user_id=user.id)
+ db.session.add(share)
+ db.session.commit()
+ ids = (user.id, rec.id, share.public_id)
+ yield ids
+ with app.app_context():
+ Share.query.filter_by(recording_id=ids[1]).delete()
+ db.session.delete(db.session.get(Recording, ids[1]))
+ db.session.delete(db.session.get(User, ids[0]))
+ db.session.commit()
+ os.remove(path)
+ os.rmdir(folder)
+
+
+def test_public_share_never_serves_html(html_named_share):
+ _, _, public_id = html_named_share
+ resp = app.test_client().get(f'/share/audio/{public_id}')
+ assert resp.status_code == 200
+ assert resp.mimetype == 'application/octet-stream'
+ assert resp.headers['Content-Security-Policy'] == 'sandbox'
+ resp.close()
+
+
+def test_owner_audio_route_never_serves_html(html_named_share):
+ user_id, rec_id, _ = html_named_share
+ client = app.test_client()
+ with client.session_transaction() as sess:
+ sess['_user_id'] = str(user_id)
+ sess['_fresh'] = True
+ resp = client.get(f'/audio/{rec_id}')
+ assert resp.status_code == 200
+ assert resp.mimetype == 'application/octet-stream'
+ assert resp.headers['Content-Security-Policy'] == 'sandbox'
+ resp.close()