Skip to content

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

Python

Tests: cover sharing/folders/groups/SSO authz holes + fix job-queue worker test isolation

Murtaza Nasirf3ac64af9dbd
diff --git a/conftest.py b/conftest.py
index 7bcd9159..9d4876cf 100644
--- a/conftest.py
+++ b/conftest.py
@@ -33,6 +33,16 @@ os.environ["UPLOAD_FOLDER"] = os.path.join(_TEST_DIR, "uploads")
os.environ.setdefault("SECRET_KEY", "pytest-secret-key")
os.environ.setdefault("ENABLE_AUTO_PROCESSING", "false") # no black-hole file monitor
os.environ.setdefault("TEXT_MODEL_API_KEY", "test-key") # avoid config hard-fails
+
+# Run ZERO background job-queue workers during tests. These counts are read at
+# job_queue import time, so they must be set before src.app is imported. With
+# workers running, enqueue() auto-starts daemon threads that claim and process
+# test-created jobs in the background — racing tests that exercise the queue
+# directly (e.g. test_job_queue_race_condition) and spraying FileNotFound
+# errors as they try to transcribe nonexistent test files. Tests that need to
+# exercise claiming drive _claim_next_job themselves.
+os.environ["JOB_QUEUE_WORKERS"] = "0"
+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).
diff --git a/tests/test_folders_groups_authz.py b/tests/test_folders_groups_authz.py
new file mode 100644
index 00000000..c4aa3f4a
--- /dev/null
+++ b/tests/test_folders_groups_authz.py
@@ -0,0 +1,691 @@
+"""Authorization tests for folder + group surfaces.
+
+Covers the previously-untested authz boundaries in:
+ - src/api/folders.py (personal folders, group folders, recording-folder
+ assignment, bulk folder move)
+ - src/api/groups.py (sync-shares, admin group CRUD + members)
+
+Focus is on negatives / IDOR: a user must not be able to read or mutate
+another user's folders, move recordings they don't own, move their own
+recordings into folders they have no access to, or reach admin-only group
+endpoints. The bulk folder-move IDOR (#287 pattern) is exercised directly.
+
+Folders are gated by an admin SystemSetting ('enable_folders'); these tests
+flip it on (and one test verifies the gate when it is off).
+
+Run:
+ HOME=/tmp /tmp/speakr_testvenv/bin/python -m pytest \
+ tests/test_folders_groups_authz.py -p no:cacheprovider -q
+"""
+import os
+import sys
+import uuid
+from unittest.mock import patch
+
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+
+import src.api.folders as folders_module
+import src.api.groups as groups_module
+from src.app import app, db
+from src.models import (
+ User,
+ Recording,
+ Folder,
+ Group,
+ GroupMembership,
+ SystemSetting,
+)
+
+app.config["WTF_CSRF_ENABLED"] = False
+
+
+# --------------------------------------------------------------------------
+# Helpers
+# --------------------------------------------------------------------------
+
+def _setup_user(prefix, is_admin=False):
+ suffix = uuid.uuid4().hex[:8]
+ user = User(
+ username=f"{prefix}_{suffix}",
+ email=f"{prefix}_{suffix}@local.test",
+ password="x",
+ is_admin=is_admin,
+ )
+ 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
+ # These tests wrap setup + multiple HTTP requests inside a single outer
+ # app.app_context(). Flask-Login caches the resolved user on `g._login_user`
+ # for the lifetime of that context, so a request made as user A leaves a
+ # stale cached identity that shadows a later request made as user B. Clear
+ # it so each request re-resolves current_user from its own session cookie.
+ from flask import g
+ for attr in ("_login_user", "_flask_login_user"):
+ if hasattr(g, attr):
+ try:
+ delattr(g, attr)
+ except (AttributeError, KeyError):
+ pass
+
+
+def _make_recording(user_id, title="r"):
+ rec = Recording(
+ user_id=user_id,
+ title=title,
+ audio_path="/tmp/x.mp3",
+ status="COMPLETED",
+ )
+ db.session.add(rec)
+ db.session.commit()
+ return rec
+
+
+def _make_folder(user_id, name=None, group_id=None):
+ folder = Folder(
+ name=name or f"f_{uuid.uuid4().hex[:8]}",
+ user_id=user_id,
+ group_id=group_id,
+ )
+ db.session.add(folder)
+ db.session.commit()
+ return folder
+
+
+def _make_group(name=None):
+ group = Group(name=name or f"g_{uuid.uuid4().hex[:8]}")
+ db.session.add(group)
+ db.session.commit()
+ return group
+
+
+def _enable_folders():
+ SystemSetting.set_setting("enable_folders", "true", setting_type="boolean")
+
+
+def _disable_folders():
+ SystemSetting.set_setting("enable_folders", "false", setting_type="boolean")
+
+
+def _cleanup(*objs):
+ for obj in objs:
+ if obj is None:
+ continue
+ try:
+ existing = db.session.get(type(obj), obj.id)
+ if existing is not None:
+ db.session.delete(existing)
+ except Exception:
+ pass
+ db.session.commit()
+
+
+# ==========================================================================
+# Personal folders: cross-user IDOR
+# ==========================================================================
+
+def test_list_folders_returns_only_own_personal_folders():
+ with app.app_context():
+ _enable_folders()
+ alice = _setup_user("fld_a")
+ bob = _setup_user("fld_b")
+ alice_folder = _make_folder(alice.id, "alice-private")
+ bob_folder = _make_folder(bob.id, "bob-private")
+
+ client = app.test_client()
+ _login(client, alice)
+ resp = client.get("/api/folders")
+ assert resp.status_code == 200
+ names = {f["name"] for f in resp.get_json()}
+ assert "alice-private" in names
+ assert "bob-private" not in names, (
+ "Folder listing leaked another user's personal folder"
+ )
+
+ _cleanup(alice_folder, bob_folder, alice, bob)
+
+
+def test_user_cannot_update_other_users_folder():
+ with app.app_context():
+ _enable_folders()
+ alice = _setup_user("fld_upd_a")
+ bob = _setup_user("fld_upd_b")
+ bob_folder = _make_folder(bob.id, "bob-secret")
+
+ client = app.test_client()
+ _login(client, alice)
+ resp = client.put(
+ f"/api/folders/{bob_folder.id}",
+ json={"name": "hijacked"},
+ )
+ assert resp.status_code == 403, (
+ f"Expected 403 editing another user's folder, got {resp.status_code}"
+ )
+ assert "permission" in resp.get_json()["error"].lower()
+ # Ensure the folder was not actually renamed.
+ db.session.expire_all()
+ assert db.session.get(Folder, bob_folder.id).name == "bob-secret"
+
+ _cleanup(bob_folder, alice, bob)
+
+
+def test_user_cannot_delete_other_users_folder():
+ with app.app_context():
+ _enable_folders()
+ alice = _setup_user("fld_del_a")
+ bob = _setup_user("fld_del_b")
+ bob_folder = _make_folder(bob.id, "bob-keep")
+
+ client = app.test_client()
+ _login(client, alice)
+ resp = client.delete(f"/api/folders/{bob_folder.id}")
+ assert resp.status_code == 403, (
+ f"Expected 403 deleting another user's folder, got {resp.status_code}"
+ )
+ assert "permission" in resp.get_json()["error"].lower()
+ assert db.session.get(Folder, bob_folder.id) is not None, (
+ "Another user's folder was deleted (IDOR)"
+ )
+
+ _cleanup(bob_folder, alice, bob)
+
+
+def test_update_nonexistent_folder_returns_404():
+ with app.app_context():
+ _enable_folders()
+ alice = _setup_user("fld_404")
+ client = app.test_client()
+ _login(client, alice)
+ resp = client.put("/api/folders/999999999", json={"name": "x"})
+ assert resp.status_code == 404
+ _cleanup(alice)
+
+
+def test_create_personal_folder_succeeds_for_self():
+ with app.app_context():
+ _enable_folders()
+ alice = _setup_user("fld_create")
+ client = app.test_client()
+ _login(client, alice)
+ resp = client.post("/api/folders", json={"name": "my-folder"})
+ assert resp.status_code == 201
+ created = resp.get_json()
+ assert created["name"] == "my-folder"
+ folder = db.session.get(Folder, created["id"])
+ assert folder is not None and folder.user_id == alice.id
+
+ _cleanup(folder, alice)
+
+
+# ==========================================================================
+# Folders feature gate
+# ==========================================================================
+
+def test_folder_endpoints_refuse_when_feature_disabled():
+ with app.app_context():
+ _disable_folders()
+ alice = _setup_user("fld_gate")
+ folder = _make_folder(alice.id, "gated")
+ client = app.test_client()
+ _login(client, alice)
+
+ # POST create is rejected with 403 (specifically the feature gate, not
+ # an incidental CSRF/auth 403).
+ resp = client.post("/api/folders", json={"name": "nope"})
+ assert resp.status_code == 403
+ assert "not enabled" in resp.get_json()["error"]
+
+ # PUT update is rejected with 403.
+ resp = client.put(f"/api/folders/{folder.id}", json={"name": "x"})
+ assert resp.status_code == 403
+ assert "not enabled" in resp.get_json()["error"]
+
+ # DELETE is rejected with 403.
+ resp = client.delete(f"/api/folders/{folder.id}")
+ assert resp.status_code == 403
+ assert "not enabled" in resp.get_json()["error"]
+
+ # GET list returns an empty array (feature-off sentinel, not an error).
+ resp = client.get("/api/folders")
+ assert resp.status_code == 200
+ assert resp.get_json() == []
+
+ _cleanup(folder, alice)
+ _enable_folders()
+
+
+# ==========================================================================
+# Move recording to folder: ownership + folder-access checks
+# ==========================================================================
+
+def test_cannot_move_recording_you_dont_own():
+ with app.app_context():
+ _enable_folders()
+ alice = _setup_user("mv_own_a")
+ bob = _setup_user("mv_own_b")
+ bob_rec = _make_recording(bob.id, "bob rec")
+ alice_folder = _make_folder(alice.id, "alice-target")
+
+ client = app.test_client()
+ _login(client, alice)
+ resp = client.put(
+ f"/api/recordings/{bob_rec.id}/folder",
+ json={"folder_id": alice_folder.id},
+ )
+ assert resp.status_code == 403, (
+ f"Expected 403 moving another user's recording, got {resp.status_code}"
+ )
+ db.session.expire_all()
+ assert db.session.get(Recording, bob_rec.id).folder_id is None
+
+ _cleanup(bob_rec, alice_folder, alice, bob)
+
+
+def test_cannot_move_own_recording_into_other_users_folder():
+ with app.app_context():
+ _enable_folders()
+ alice = _setup_user("mv_fld_a")
+ bob = _setup_user("mv_fld_b")
+ alice_rec = _make_recording(alice.id, "alice rec")
+ bob_folder = _make_folder(bob.id, "bob-folder")
+
+ client = app.test_client()
+ _login(client, alice)
+ resp = client.put(
+ f"/api/recordings/{alice_rec.id}/folder",
+ json={"folder_id": bob_folder.id},
+ )
+ assert resp.status_code == 403, (
+ f"Expected 403 targeting another user's folder, got {resp.status_code}"
+ )
+ db.session.expire_all()
+ assert db.session.get(Recording, alice_rec.id).folder_id is None, (
+ "Recording was moved into a folder the user has no access to (IDOR)"
+ )
+
+ _cleanup(alice_rec, bob_folder, alice, bob)
+
+
+def test_move_own_recording_into_own_folder_succeeds():
+ with app.app_context():
+ _enable_folders()
+ alice = _setup_user("mv_ok")
+ rec = _make_recording(alice.id, "rec")
+ folder = _make_folder(alice.id, "target")
+
+ client = app.test_client()
+ _login(client, alice)
+ resp = client.put(
+ f"/api/recordings/{rec.id}/folder",
+ json={"folder_id": folder.id},
+ )
+ assert resp.status_code == 200
+ db.session.expire_all()
+ assert db.session.get(Recording, rec.id).folder_id == folder.id
+
+ _cleanup(rec, folder, alice)
+
+
+# ==========================================================================
+# Bulk folder move: the #287 IDOR surface
+# ==========================================================================
+
+def test_bulk_folder_move_only_affects_own_recordings():
+ """Bulk move must silently skip recordings the caller can't edit, while
+ still moving the caller's own. A victim's recording id slipped into the
+ list must not be moved into the attacker's folder."""
+ with app.app_context():
+ _enable_folders()
+ attacker = _setup_user("bulk_att")
+ victim = _setup_user("bulk_vic")
+ attacker_rec = _make_recording(attacker.id, "attacker rec")
+ victim_rec = _make_recording(victim.id, "victim rec")
+ attacker_folder = _make_folder(attacker.id, "attacker-folder")
+
+ client = app.test_client()
+ _login(client, attacker)
+ resp = client.post(
+ "/api/recordings/bulk/folder",
+ json={
+ "recording_ids": [attacker_rec.id, victim_rec.id],
+ "folder_id": attacker_folder.id,
+ },
+ )
+ assert resp.status_code == 200
+ body = resp.get_json()
+ # Only the attacker's own recording should have been updated.
+ assert body["updated_count"] == 1, (
+ f"Expected 1 updated, got {body['updated_count']} — victim record "
+ "may have been moved (IDOR)"
+ )
+ db.session.expire_all()
+ assert db.session.get(Recording, attacker_rec.id).folder_id == attacker_folder.id
+ assert db.session.get(Recording, victim_rec.id).folder_id is None, (
+ "Victim's recording was moved into the attacker's folder (IDOR)"
+ )
+
+ _cleanup(attacker_rec, victim_rec, attacker_folder, attacker, victim)
+
+
+def test_bulk_folder_move_rejects_other_users_target_folder():
+ """If the target folder belongs to another user, the whole bulk op is
+ rejected with 403 before any recording is touched."""
+ with app.app_context():
+ _enable_folders()
+ attacker = _setup_user("bulk_tgt_att")
+ victim = _setup_user("bulk_tgt_vic")
+ attacker_rec = _make_recording(attacker.id, "attacker rec")
+ victim_folder = _make_folder(victim.id, "victim-folder")
+
+ client = app.test_client()
+ _login(client, attacker)
+ resp = client.post(
+ "/api/recordings/bulk/folder",
+ json={
+ "recording_ids": [attacker_rec.id],
+ "folder_id": victim_folder.id,
+ },
+ )
+ assert resp.status_code == 403, (
+ f"Expected 403 targeting another user's folder, got {resp.status_code}"
+ )
+ db.session.expire_all()
+ assert db.session.get(Recording, attacker_rec.id).folder_id is None
+
+ _cleanup(attacker_rec, victim_folder, attacker, victim)
+
+
+# ==========================================================================
+# Group folders: membership / admin gating
+# ==========================================================================
+
+def test_non_admin_member_cannot_create_group_folder_via_api_folders():
+ """POST /api/folders with a group_id requires the caller to be an *admin*
+ of that group. A plain member is rejected with 403."""
+ with app.app_context():
+ _enable_folders()
+ member = _setup_user("gf_member")
+ group = _make_group("gf-group")
+ db.session.add(GroupMembership(user_id=member.id, group_id=group.id, role="member"))
+ db.session.commit()
+
+ client = app.test_client()
+ _login(client, member)
+ resp = client.post(
+ "/api/folders",
+ json={"name": "team-folder", "group_id": group.id},
+ )
+ assert resp.status_code == 403, (
+ f"Expected 403 for non-admin creating group folder, got {resp.status_code}"
+ )
+
+ _cleanup(
+ GroupMembership.query.filter_by(group_id=group.id).first(),
+ group, member,
+ )
+
+
+def test_outsider_cannot_create_group_folder():
+ """A user who is not a member at all cannot create a group folder."""
+ with app.app_context():
+ _enable_folders()
+ outsider = _setup_user("gf_outsider")
+ group = _make_group("gf-group2")
+
+ client = app.test_client()
+ _login(client, outsider)
+ resp = client.post(
+ "/api/folders",
+ json={"name": "team-folder", "group_id": group.id},
+ )
+ assert resp.status_code == 403
+
+ _cleanup(group, outsider)
+
+
+def test_group_admin_can_create_group_folder():
+ with app.app_context():
+ _enable_folders()
+ admin = _setup_user("gf_admin")
+ group = _make_group("gf-group3")
+ db.session.add(GroupMembership(user_id=admin.id, group_id=group.id, role="admin"))
+ db.session.commit()
+
+ client = app.test_client()
+ _login(client, admin)
+ resp = client.post(
+ "/api/folders",
+ json={"name": "team-folder", "group_id": group.id},
+ )
+ assert resp.status_code == 201
+ created = resp.get_json()
+ folder = db.session.get(Folder, created["id"])
+ assert folder is not None and folder.group_id == group.id
+
+ _cleanup(
+ folder,
+ GroupMembership.query.filter_by(group_id=group.id).first(),
+ group, admin,
+ )
+
+
+def test_get_group_folders_requires_membership():
+ """GET /api/groups/<gid>/folders returns 403 for a non-member, 200 for a
+ member."""
+ with app.app_context():
+ _enable_folders()
+ member = _setup_user("ggf_member")
+ outsider = _setup_user("ggf_outsider")
+ group = _make_group("ggf-group")
+ db.session.add(GroupMembership(user_id=member.id, group_id=group.id, role="member"))
+ db.session.commit()
+ group_folder = _make_folder(member.id, "team-shared", group_id=group.id)
+
+ # Outsider: 403. (Use a dedicated client — reusing one client across
+ # two logged-in identities does not reliably switch current_user.)
+ outsider_client = app.test_client()
+ _login(outsider_client, outsider)
+ resp = outsider_client.get(f"/api/groups/{group.id}/folders")
+ assert resp.status_code == 403, (
+ f"Non-member reached group folders, got {resp.status_code}"
+ )
+
+ # Member: 200 and sees the folder.
+ member_client = app.test_client()
+ _login(member_client, member)
+ resp = member_client.get(f"/api/groups/{group.id}/folders")
+ assert resp.status_code == 200
+ names = {f["name"] for f in resp.get_json()["folders"]}
+ assert "team-shared" in names
+
+ _cleanup(
+ group_folder,
+ GroupMembership.query.filter_by(group_id=group.id).first(),
+ group, member, outsider,
+ )
+
+
+def test_create_group_folder_route_requires_admin_membership():
+ """POST /api/groups/<gid>/folders (the dedicated route, gated by
+ ENABLE_INTERNAL_SHARING) rejects non-admins with 403."""
+ with app.app_context():
+ _enable_folders()
+ member = _setup_user("cgf_member")
+ group = _make_group("cgf-group")
+ db.session.add(GroupMembership(user_id=member.id, group_id=group.id, role="member"))
+ db.session.commit()
+
+ client = app.test_client()
+ _login(client, member)
+ with patch.object(folders_module, "ENABLE_INTERNAL_SHARING", True):
+ resp = client.post(
+ f"/api/groups/{group.id}/folders",
+ json={"name": "team-folder"},
+ )
+ assert resp.status_code == 403
+
+ _cleanup(
+ GroupMembership.query.filter_by(group_id=group.id).first(),
+ group, member,
+ )
+
+
+# ==========================================================================
+# groups.py: sync-shares authz
+# ==========================================================================
+
+def test_sync_shares_requires_group_admin():
+ """POST /api/groups/<gid>/sync-shares: a plain member gets 403."""
+ with app.app_context():
+ member = _setup_user("ss_member")
+ group = _make_group("ss-group")
+ db.session.add(GroupMembership(user_id=member.id, group_id=group.id, role="member"))
+ db.session.commit()
+
+ client = app.test_client()
+ _login(client, member)
+ with patch.object(groups_module, "ENABLE_INTERNAL_SHARING", True):
+ resp = client.post(f"/api/groups/{group.id}/sync-shares")
+ assert resp.status_code == 403, (
+ f"Non-admin reached sync-shares, got {resp.status_code}"
+ )
+
+ _cleanup(
+ GroupMembership.query.filter_by(group_id=group.id).first(),
+ group, member,
+ )
+
+
+def test_sync_shares_outsider_gets_403():
+ with app.app_context():
+ outsider = _setup_user("ss_outsider")
+ group = _make_group("ss-group2")
+
+ client = app.test_client()
+ _login(client, outsider)
+ with patch.object(groups_module, "ENABLE_INTERNAL_SHARING", True):
+ resp = client.post(f"/api/groups/{group.id}/sync-shares")
+ assert resp.status_code == 403
+
+ _cleanup(group, outsider)
+
+
+# ==========================================================================
+# Admin group endpoints: site-admin gating
+# ==========================================================================
+
+def test_create_group_requires_site_admin():
+ """POST /api/admin/groups: a normal authenticated user gets 403."""
+ with app.app_context():
+ normal = _setup_user("ag_normal")
+ client = app.test_client()
+ _login(client, normal)
+ with patch.object(groups_module, "ENABLE_INTERNAL_SHARING", True):
+ resp = client.post("/api/admin/groups", json={"name": "x"})
+ assert resp.status_code == 403, (
+ f"Non-admin reached admin group creation, got {resp.status_code}"
+ )
+ _cleanup(normal)
+
+
+def test_create_group_succeeds_for_site_admin():
+ with app.app_context():
+ admin = _setup_user("ag_admin", is_admin=True)
+ client = app.test_client()
+ _login(client, admin)
+ name = f"admin-group-{uuid.uuid4().hex[:6]}"
+ with patch.object(groups_module, "ENABLE_INTERNAL_SHARING", True):
+ resp = client.post("/api/admin/groups", json={"name": name})
+ assert resp.status_code == 201
+ group = Group.query.filter_by(name=name).first()
+ assert group is not None
+
+ _cleanup(group, admin)
+
+
+def test_delete_group_requires_site_admin():
+ """DELETE /api/admin/groups/<gid> is site-admin only. Even a *group*
+ admin (but not site admin) must be rejected with 403."""
+ with app.app_context():
+ group_admin = _setup_user("dg_groupadmin")
+ group = _make_group("dg-group")
+ db.session.add(GroupMembership(user_id=group_admin.id, group_id=group.id, role="admin"))
+ db.session.commit()
+
+ client = app.test_client()
+ _login(client, group_admin)
+ resp = client.delete(f"/api/admin/groups/{group.id}")
+ assert resp.status_code == 403, (
+ f"Group admin (non-site-admin) deleted a group, got {resp.status_code}"
+ )
+ assert db.session.get(Group, group.id) is not None
+
+ _cleanup(
+ GroupMembership.query.filter_by(group_id=group.id).first(),
+ group, group_admin,
+ )
+
+
+def test_add_member_requires_admin():
+ """POST /api/admin/groups/<gid>/members: a normal non-member user gets
+ 403 (not site admin, not group admin)."""
+ with app.app_context():
+ normal = _setup_user("am_normal")
+ target = _setup_user("am_target")
+ group = _make_group("am-group")
+
+ client = app.test_client()
+ _login(client, normal)
+ with patch.object(groups_module, "ENABLE_INTERNAL_SHARING", True):
+ resp = client.post(
+ f"/api/admin/groups/{group.id}/members",
+ json={"user_id": target.id, "role": "member"},
+ )
+ assert resp.status_code == 403
+ assert GroupMembership.query.filter_by(group_id=group.id).first() is None
+
+ _cleanup(group, normal, target)
+
+
+def test_group_admin_can_add_member():
+ """A group admin (not site admin) CAN add members to their own group."""
+ with app.app_context():
+ group_admin = _setup_user("gam_admin")
+ target = _setup_user("gam_target")
+ group = _make_group("gam-group")
+ db.session.add(GroupMembership(user_id=group_admin.id, group_id=group.id, role="admin"))
+ db.session.commit()
+
+ client = app.test_client()
+ _login(client, group_admin)
+ with patch.object(groups_module, "ENABLE_INTERNAL_SHARING", True):
+ resp = client.post(
+ f"/api/admin/groups/{group.id}/members",
+ json={"user_id": target.id, "role": "member"},
+ )
+ assert resp.status_code == 201
+ assert GroupMembership.query.filter_by(
+ group_id=group.id, user_id=target.id
+ ).first() is not None
+
+ _cleanup(
+ GroupMembership.query.filter_by(group_id=group.id, user_id=target.id).first(),
+ GroupMembership.query.filter_by(group_id=group.id, user_id=group_admin.id).first(),
+ group, group_admin, target,
+ )
+
+
+def test_get_teams_requires_admin_or_group_admin():
+ """GET /api/admin/groups: a plain user with no admin role gets 403."""
+ with app.app_context():
+ normal = _setup_user("gt_normal")
+ client = app.test_client()
+ _login(client, normal)
+ resp = client.get("/api/admin/groups")
+ assert resp.status_code == 403
+ _cleanup(normal)
diff --git a/tests/test_shares_authz.py b/tests/test_shares_authz.py
new file mode 100644
index 00000000..dc6f83e9
--- /dev/null
+++ b/tests/test_shares_authz.py
@@ -0,0 +1,718 @@
+"""Authorization / IDOR regression tests for src/api/shares.py.
+
+This is the highest-risk private-data-leak surface in the app (public links +
+internal user-to-user sharing) and previously had ZERO test coverage. These
+tests assert the EXACT observed behaviour of the routes (status codes + body),
+focused on the negative / cross-user (IDOR) boundaries.
+
+Two harness details matter a great deal here:
+
+1. Flask-Login caches the resolved ``current_user`` on the application context.
+ If client requests are issued INSIDE an enclosing ``with app.app_context():``
+ block, the first request's user is cached and every later request in that
+ same context resolves to the SAME user regardless of which session cookie the
+ test client sends. That silently makes a "recipient" client act as the
+ "owner". To avoid it, all DB work happens inside a short-lived ``_db()``
+ context manager (which exits before any HTTP call) and every ``client.*``
+ request is issued with NO app context active, so each request pushes its own.
+
+2. ``src/api/shares.py`` and ``src/app.py`` each read ENABLE_PUBLIC_SHARING /
+ ENABLE_INTERNAL_SHARING into module-level booleans AT IMPORT TIME (from the
+ project .env via load_dotenv). The exact ambient value differs by machine/CI,
+ so the tests force the flags to a known value via context managers that patch
+ the module globals in BOTH modules (has_recording_access in src.app gates on
+ its own copy of ENABLE_INTERNAL_SHARING).
+
+``create_share`` requires request.is_secure, so the secure-path tests issue the
+request with wsgi.url_scheme=https via environ_overrides.
+
+Run:
+ HOME=/tmp /tmp/speakr_testvenv/bin/python -m pytest \
+ tests/test_shares_authz.py -p no:cacheprovider -q
+"""
+
+import os
+import sys
+import tempfile
+import uuid
+from contextlib import contextmanager
+
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+
+# When run standalone (python tests/test_shares_authz.py), conftest.py is NOT
+# loaded, so point the app at a throwaway DB / upload dir before importing it.
+# Under pytest, conftest.py has already set these and setdefault is a no-op.
+if "SQLALCHEMY_DATABASE_URI" not in os.environ:
+ _STANDALONE_DIR = tempfile.mkdtemp(prefix="speakr_shares_authz_")
+ os.environ["SQLALCHEMY_DATABASE_URI"] = (
+ f"sqlite:///{os.path.join(_STANDALONE_DIR, 'test.db')}"
+ )
+ os.environ.setdefault("UPLOAD_FOLDER", os.path.join(_STANDALONE_DIR, "uploads"))
+ os.environ.setdefault("SECRET_KEY", "pytest-secret-key")
+ os.environ.setdefault("ENABLE_AUTO_PROCESSING", "false")
+ os.environ.setdefault("TEXT_MODEL_API_KEY", "test-key")
+
+import src.app as app_module
+import src.api.shares as shares_module
+from src.app import app, db
+from src.models import User, Recording, Share, InternalShare, SharedRecordingState
+
+app.config["WTF_CSRF_ENABLED"] = False
+
+HTTPS = {"wsgi.url_scheme": "https"}
+
+
+# --- DB / context helpers ---------------------------------------------------
+
+@contextmanager
+def _db():
+ """Short-lived app context for DB work only.
+
+ Must be exited before issuing client requests so Flask-Login does not cache
+ a stale current_user across differently-authenticated requests.
+ """
+ with app.app_context():
+ yield
+
+
+def _setup_user(prefix, can_share_publicly=True):
+ """Create a user and return its id (a plain int, safe to use after the
+ context closes)."""
+ suffix = uuid.uuid4().hex[:8]
+ user = User(
+ username=f"{prefix}_{suffix}",
+ email=f"{prefix}_{suffix}@local.test",
+ password="x",
+ can_share_publicly=can_share_publicly,
+ )
+ db.session.add(user)
+ db.session.commit()
+ return user.id
+
+
+def _make_recording(user_id, title="r"):
+ rec = Recording(
+ user_id=user_id,
+ title=title,
+ audio_path="/tmp/x.mp3",
+ status="COMPLETED",
+ )
+ db.session.add(rec)
+ db.session.commit()
+ return rec.id
+
+
+def _make_public_share(recording_id, user_id):
+ share = Share(recording_id=recording_id, user_id=user_id)
+ db.session.add(share)
+ db.session.commit()
+ return share.public_id, share.id
+
+
+def _make_internal_share(recording_id, owner_id, recipient_id,
+ can_edit=False, can_reshare=False):
+ share = InternalShare(
+ recording_id=recording_id,
+ owner_id=owner_id,
+ shared_with_user_id=recipient_id,
+ can_edit=can_edit,
+ can_reshare=can_reshare,
+ )
+ db.session.add(share)
+ db.session.commit()
+ return share.id
+
+
+def _client_for(user_id):
+ """Build a fresh test client with the session pre-authenticated as user_id.
+
+ Returned with NO app context active; the caller must issue requests while no
+ app context is on the stack (see module docstring).
+ """
+ client = app.test_client()
+ with client.session_transaction() as sess:
+ sess["_user_id"] = str(user_id)
+ sess["_fresh"] = True
+ return client
+
+
+def _anon_client():
+ return app.test_client()
+
+
+# --- config-flag forcing ----------------------------------------------------
+
+@contextmanager
+def _flag(module_attr, value, *modules):
+ """Temporarily set a module-level config bool on each given module."""
+ saved = [(m, getattr(m, module_attr)) for m in modules]
+ for m in modules:
+ setattr(m, module_attr, value)
+ try:
+ yield
+ finally:
+ for m, old in saved:
+ setattr(m, module_attr, old)
+
+
+def _internal_enabled():
+ return _flag("ENABLE_INTERNAL_SHARING", True, app_module, shares_module)
+
+
+def _internal_disabled():
+ return _flag("ENABLE_INTERNAL_SHARING", False, app_module, shares_module)
+
+
+def _public_enabled():
+ return _flag("ENABLE_PUBLIC_SHARING", True, shares_module)
+
+
+def _public_disabled():
+ return _flag("ENABLE_PUBLIC_SHARING", False, shares_module)
+
+
+# --- cleanup ----------------------------------------------------------------
+
+def _cleanup_ids(user_ids=(), recording_ids=()):
+ with _db():
+ for rid in recording_ids:
+ Share.query.filter_by(recording_id=rid).delete()
+ InternalShare.query.filter_by(recording_id=rid).delete()
+ SharedRecordingState.query.filter_by(recording_id=rid).delete()
+ rec = db.session.get(Recording, rid)
+ if rec is not None:
+ db.session.delete(rec)
+ for uid in user_ids:
+ u = db.session.get(User, uid)
+ if u is not None:
+ db.session.delete(u)
+ db.session.commit()
+
+
+# =============================================================================
+# Public share link: anonymous view
+# =============================================================================
+
+def test_public_view_valid_public_id_returns_recording():
+ """A valid public_id renders the shared recording to an anonymous viewer."""
+ with _db():
+ owner = _setup_user("pv_owner")
+ rec = _make_recording(owner, "secret meeting")
+ public_id, _ = _make_public_share(rec, owner)
+
+ resp = _anon_client().get(f"/share/{public_id}")
+ assert resp.status_code == 200
+ assert b"secret meeting" in resp.data
+
+ _cleanup_ids([owner], [rec])
+
+
+def test_public_view_nonexistent_public_id_returns_404():
+ """An unknown public_id must 404 — never leak that recordings exist."""
+ resp = _anon_client().get("/share/this-id-does-not-exist-xyz")
+ assert resp.status_code == 404
+
+
+def test_public_view_revoked_public_id_returns_404():
+ """After the share row is deleted (revoked) the link 404s and leaks nothing."""
+ with _db():
+ owner = _setup_user("pv_revoked")
+ rec = _make_recording(owner, "revoked content")
+ public_id, share_id = _make_public_share(rec, owner)
+ db.session.delete(db.session.get(Share, share_id))
+ db.session.commit()
+
+ resp = _anon_client().get(f"/share/{public_id}")
+ assert resp.status_code == 404
+ assert b"revoked content" not in resp.data
+
+ _cleanup_ids([owner], [rec])
+
+
+# =============================================================================
+# Public shared-audio endpoint
+# =============================================================================
+
+def test_shared_audio_nonexistent_public_id_returns_500():
+ """REAL BEHAVIOUR (and a minor bug): an unknown public_id on the audio
+ endpoint returns 500, not 404.
+
+ get_shared_audio() wraps first_or_404() in a broad ``except Exception`` that
+ catches the werkzeug NotFound (404) it raises and re-reports it as a generic
+ 500. No data leaks (still no audio served), but the status is wrong. This
+ test pins the current behaviour; if the route is fixed to let the 404
+ propagate, update this to expect 404.
+ """
+ resp = _anon_client().get("/share/audio/nope-not-a-real-id")
+ assert resp.status_code == 500
+
+
+def test_shared_audio_valid_share_missing_file_returns_404():
+ """A valid share whose audio file is absent on disk returns 404 (not 200).
+
+ The recording.audio_path ('/tmp/x.mp3') does not exist, so the route hits the
+ os.path.exists branch -> 'Audio file missing from server'. Proves the
+ endpoint resolves the share but never serves a phantom/other file.
+ """
+ with _db():
+ owner = _setup_user("audio_owner")
+ rec = _make_recording(owner, "with audio")
+ public_id, _ = _make_public_share(rec, owner)
+
+ resp = _anon_client().get(f"/share/audio/{public_id}")
+ assert resp.status_code == 404
+ assert b"missing from server" in resp.data
+
+ _cleanup_ids([owner], [rec])
+
+
+# =============================================================================
+# Create public share link: ownership boundary
+# =============================================================================
+
+def test_create_share_by_owner_succeeds():
+ """The owner can create a public share link for their own recording over HTTPS."""
+ with _db():
+ owner = _setup_user("cs_owner")
+ rec = _make_recording(owner, "mine to share")
+
+ with _public_enabled():
+ resp = _client_for(owner).post(
+ f"/api/recording/{rec}/share",
+ json={"share_summary": True, "share_notes": True},
+ environ_overrides=HTTPS,
+ )
+ assert resp.status_code == 201, resp.data
+ body = resp.get_json()
+ assert body["success"] is True
+ assert "share_url" in body
+
+ with _db():
+ assert Share.query.filter_by(recording_id=rec).count() == 1
+ _cleanup_ids([owner], [rec])
+
+
+def test_create_share_for_other_users_recording_is_denied():
+ """IDOR: a non-owner cannot create a public link for someone else's recording.
+
+ The route returns 404 ('Recording not found or you do not have permission')
+ and NO Share row is created for the victim's recording.
+ """
+ with _db():
+ victim = _setup_user("cs_victim")
+ attacker = _setup_user("cs_attacker")
+ victim_rec = _make_recording(victim, "victims private rec")
+
+ with _public_enabled():
+ resp = _client_for(attacker).post(
+ f"/api/recording/{victim_rec}/share", json={}, environ_overrides=HTTPS,
+ )
+ assert resp.status_code == 404, resp.data
+ with _db():
+ assert Share.query.filter_by(recording_id=victim_rec).count() == 0, (
+ "IDOR: attacker created a public share link for the victim's recording"
+ )
+ _cleanup_ids([victim, attacker], [victim_rec])
+
+
+def test_create_share_refused_when_public_sharing_disabled():
+ """With ENABLE_PUBLIC_SHARING off, even the owner is refused (403)."""
+ with _db():
+ owner = _setup_user("cs_disabled")
+ rec = _make_recording(owner)
+
+ with _public_disabled():
+ resp = _client_for(owner).post(
+ f"/api/recording/{rec}/share", json={}, environ_overrides=HTTPS,
+ )
+ assert resp.status_code == 403, resp.data
+ with _db():
+ assert Share.query.filter_by(recording_id=rec).count() == 0
+ _cleanup_ids([owner], [rec])
+
+
+def test_create_share_refused_when_user_lacks_permission():
+ """A user with can_share_publicly=False is refused (403)."""
+ with _db():
+ owner = _setup_user("cs_noperm", can_share_publicly=False)
+ rec = _make_recording(owner)
+
+ with _public_enabled():
+ resp = _client_for(owner).post(
+ f"/api/recording/{rec}/share", json={}, environ_overrides=HTTPS,
+ )
+ assert resp.status_code == 403, resp.data
+ with _db():
+ assert Share.query.filter_by(recording_id=rec).count() == 0
+ _cleanup_ids([owner], [rec])
+
+
+def test_create_share_refused_over_insecure_connection():
+ """Creating a share over plain HTTP (not is_secure) is refused (403)."""
+ with _db():
+ owner = _setup_user("cs_http")
+ rec = _make_recording(owner)
+
+ with _public_enabled():
+ resp = _client_for(owner).post(f"/api/recording/{rec}/share", json={})
+ assert resp.status_code == 403, resp.data
+ with _db():
+ assert Share.query.filter_by(recording_id=rec).count() == 0
+ _cleanup_ids([owner], [rec])
+
+
+def test_create_share_requires_login():
+ """Anonymous create-share bounces to login (302/401)."""
+ with _db():
+ owner = _setup_user("cs_anon")
+ rec = _make_recording(owner)
+
+ resp = _anon_client().post(
+ f"/api/recording/{rec}/share", json={}, environ_overrides=HTTPS,
+ )
+ assert resp.status_code in (302, 401), resp.status_code
+ _cleanup_ids([owner], [rec])
+
+
+# =============================================================================
+# get_existing_share ownership boundary
+# =============================================================================
+
+def test_get_existing_share_other_users_recording_returns_404():
+ """IDOR: GET share-status for another user's recording must 404, even if a
+ share exists, so existence/metadata never leaks."""
+ with _db():
+ victim = _setup_user("ges_victim")
+ attacker = _setup_user("ges_attacker")
+ rec = _make_recording(victim)
+ _make_public_share(rec, victim)
+
+ resp = _client_for(attacker).get(f"/api/recording/{rec}/share")
+ assert resp.status_code == 404, resp.data
+ _cleanup_ids([victim, attacker], [rec])
+
+
+# =============================================================================
+# Manage public shares: /api/shares, PUT/DELETE /api/share/<id>
+# =============================================================================
+
+def test_get_shares_returns_only_own_shares():
+ """GET /api/shares returns ONLY the caller's shares, not other users'."""
+ with _db():
+ a = _setup_user("ls_a")
+ b = _setup_user("ls_b")
+ rec_a = _make_recording(a)
+ rec_b = _make_recording(b)
+ _, share_a_id = _make_public_share(rec_a, a)
+ _, share_b_id = _make_public_share(rec_b, b)
+
+ resp = _client_for(a).get("/api/shares")
+ assert resp.status_code == 200
+ ids = {s["id"] for s in resp.get_json()}
+ assert share_a_id in ids
+ assert share_b_id not in ids, "GET /api/shares leaked another user's share"
+ _cleanup_ids([a, b], [rec_a, rec_b])
+
+
+def test_update_other_users_share_returns_404():
+ """IDOR: PUT on a share you don't own must 404 and not mutate it."""
+ with _db():
+ victim = _setup_user("us_victim")
+ attacker = _setup_user("us_attacker")
+ rec = _make_recording(victim)
+ _, share_id = _make_public_share(rec, victim)
+
+ resp = _client_for(attacker).put(
+ f"/api/share/{share_id}", json={"share_summary": False},
+ )
+ assert resp.status_code == 404, resp.data
+ with _db():
+ share = db.session.get(Share, share_id)
+ assert share.share_summary is True, "IDOR: attacker mutated victim's share"
+ _cleanup_ids([victim, attacker], [rec])
+
+
+def test_delete_other_users_share_returns_404_and_survives():
+ """IDOR: DELETE on a share you don't own must 404 and the share survives."""
+ with _db():
+ victim = _setup_user("ds_victim")
+ attacker = _setup_user("ds_attacker")
+ rec = _make_recording(victim)
+ _, share_id = _make_public_share(rec, victim)
+
+ resp = _client_for(attacker).delete(f"/api/share/{share_id}")
+ assert resp.status_code == 404, resp.data
+ with _db():
+ assert db.session.get(Share, share_id) is not None, (
+ "IDOR: attacker deleted victim's public share"
+ )
+ _cleanup_ids([victim, attacker], [rec])
+
+
+# =============================================================================
+# users/search + can-share-publicly auth gating
+# =============================================================================
+
+def test_users_search_requires_login():
+ resp = _anon_client().get("/api/users/search?q=alice")
+ assert resp.status_code in (302, 401), resp.status_code
+
+
+def test_users_search_403_when_internal_sharing_disabled():
+ """With internal sharing off, user search is refused even for a logged-in
+ user — prevents user enumeration when the feature is off."""
+ with _db():
+ user = _setup_user("srch_off")
+ with _internal_disabled():
+ resp = _client_for(user).get("/api/users/search?q=ab")
+ assert resp.status_code == 403, resp.data
+ _cleanup_ids([user], [])
+
+
+def test_can_share_publicly_requires_login():
+ resp = _anon_client().get("/api/permissions/can-share-publicly")
+ assert resp.status_code in (302, 401), resp.status_code
+
+
+def test_can_share_publicly_reflects_user_permission():
+ """The endpoint reports the AND of user.can_share_publicly and the global
+ ENABLE_PUBLIC_SHARING flag (forced True here)."""
+ with _db():
+ allowed = _setup_user("csp_yes", can_share_publicly=True)
+ denied = _setup_user("csp_no", can_share_publicly=False)
+
+ with _public_enabled():
+ r1 = _client_for(allowed).get("/api/permissions/can-share-publicly")
+ r2 = _client_for(denied).get("/api/permissions/can-share-publicly")
+ assert r1.status_code == 200
+ assert r1.get_json()["can_share_publicly"] is True
+ assert r2.status_code == 200
+ assert r2.get_json()["can_share_publicly"] is False
+ _cleanup_ids([allowed, denied], [])
+
+
+# =============================================================================
+# Internal sharing: feature-flag gating (forced off)
+# =============================================================================
+
+def test_internal_share_403_when_feature_disabled():
+ with _db():
+ owner = _setup_user("is_off_owner")
+ target = _setup_user("is_off_target")
+ rec = _make_recording(owner)
+
+ with _internal_disabled():
+ resp = _client_for(owner).post(
+ f"/api/recordings/{rec}/share-internal", json={"user_id": target},
+ )
+ assert resp.status_code == 403, resp.data
+ with _db():
+ assert InternalShare.query.filter_by(recording_id=rec).count() == 0
+ _cleanup_ids([owner, target], [rec])
+
+
+def test_shared_with_me_403_when_feature_disabled():
+ with _db():
+ user = _setup_user("swm_off")
+ with _internal_disabled():
+ resp = _client_for(user).get("/api/recordings/shared-with-me")
+ assert resp.status_code == 403, resp.data
+ _cleanup_ids([user], [])
+
+
+# =============================================================================
+# Internal sharing: ownership / IDOR boundaries (feature forced on)
+# =============================================================================
+
+def test_internal_share_owner_can_share_and_recipient_sees_it():
+ """Happy path + visibility: owner shares -> recipient appears in
+ shares-internal AND the recording appears in the recipient's
+ shared-with-me, while a third party sees neither."""
+ with _db():
+ owner = _setup_user("isb_owner")
+ recipient = _setup_user("isb_recipient")
+ rec = _make_recording(owner, "team rec")
+
+ with _internal_enabled():
+ post = _client_for(owner).post(
+ f"/api/recordings/{rec}/share-internal", json={"user_id": recipient},
+ )
+ assert post.status_code == 201, post.data
+
+ listing = _client_for(owner).get(f"/api/recordings/{rec}/shares-internal")
+ assert listing.status_code == 200
+ user_ids = {s["user_id"] for s in listing.get_json()["shares"]}
+ assert recipient in user_ids
+ assert owner in user_ids # owner entry is injected at the front
+
+ swm = _client_for(recipient).get("/api/recordings/shared-with-me")
+ assert swm.status_code == 200
+ rec_ids = {r["id"] for r in swm.get_json()}
+ assert rec in rec_ids, "recipient cannot see the recording shared with them"
+
+ _cleanup_ids([owner, recipient], [rec])
+
+
+def test_internal_share_nonowner_without_reshare_denied():
+ """IDOR: a user who does NOT own and was NOT granted reshare cannot share
+ the recording with anyone (403/404). No InternalShare is created."""
+ with _db():
+ owner = _setup_user("isn_owner")
+ attacker = _setup_user("isn_attacker")
+ third = _setup_user("isn_third")
+ rec = _make_recording(owner)
+
+ with _internal_enabled():
+ resp = _client_for(attacker).post(
+ f"/api/recordings/{rec}/share-internal", json={"user_id": third},
+ )
+ assert resp.status_code in (403, 404), resp.data
+ with _db():
+ assert InternalShare.query.filter_by(
+ recording_id=rec, shared_with_user_id=third
+ ).count() == 0, "Non-owner without reshare created an internal share (IDOR)"
+ _cleanup_ids([owner, attacker, third], [rec])
+
+
+def test_shares_internal_third_party_cannot_view():
+ """IDOR: a third party (not owner, not recipient) cannot list a recording's
+ internal shares (403/404)."""
+ with _db():
+ owner = _setup_user("siv_owner")
+ recipient = _setup_user("siv_recipient")
+ third = _setup_user("siv_third")
+ rec = _make_recording(owner)
+ _make_internal_share(rec, owner, recipient)
+
+ with _internal_enabled():
+ resp = _client_for(third).get(f"/api/recordings/{rec}/shares-internal")
+ assert resp.status_code in (403, 404), resp.data
+ _cleanup_ids([owner, recipient, third], [rec])
+
+
+def test_shared_with_me_returns_only_callers_shares():
+ """shared-with-me returns ONLY recordings shared with the caller, not
+ recordings shared with other users."""
+ with _db():
+ owner = _setup_user("swmo_owner")
+ me = _setup_user("swmo_me")
+ other = _setup_user("swmo_other")
+ rec_for_me = _make_recording(owner, "for me")
+ rec_for_other = _make_recording(owner, "for other")
+ _make_internal_share(rec_for_me, owner, me)
+ _make_internal_share(rec_for_other, owner, other)
+
+ with _internal_enabled():
+ resp = _client_for(me).get("/api/recordings/shared-with-me")
+ assert resp.status_code == 200
+ rec_ids = {r["id"] for r in resp.get_json()}
+ assert rec_for_me in rec_ids
+ assert rec_for_other not in rec_ids, (
+ "shared-with-me leaked a recording shared with a DIFFERENT user"
+ )
+ _cleanup_ids([owner, me, other], [rec_for_me, rec_for_other])
+
+
+# =============================================================================
+# Revoke internal share: only the owner (grantor) may revoke
+# =============================================================================
+
+def test_revoke_internal_share_third_party_denied_and_survives():
+ """IDOR: a third party cannot revoke an internal share (403) and it survives."""
+ with _db():
+ owner = _setup_user("rev_owner")
+ recipient = _setup_user("rev_recipient")
+ third = _setup_user("rev_third")
+ rec = _make_recording(owner)
+ share_id = _make_internal_share(rec, owner, recipient)
+
+ with _internal_enabled():
+ resp = _client_for(third).delete(f"/api/internal-shares/{share_id}")
+ assert resp.status_code in (403, 404), resp.data
+ with _db():
+ assert db.session.get(InternalShare, share_id) is not None, (
+ "IDOR: third party revoked an internal share they don't own"
+ )
+ _cleanup_ids([owner, recipient, third], [rec])
+
+
+def test_revoke_internal_share_recipient_cannot_revoke():
+ """Per the route's 'only owner can revoke' rule, even the RECIPIENT of the
+ share cannot revoke it (403); the share survives."""
+ with _db():
+ owner = _setup_user("revr_owner")
+ recipient = _setup_user("revr_recipient")
+ rec = _make_recording(owner)
+ share_id = _make_internal_share(rec, owner, recipient)
+
+ with _internal_enabled():
+ resp = _client_for(recipient).delete(f"/api/internal-shares/{share_id}")
+ assert resp.status_code == 403, resp.data
+ with _db():
+ assert db.session.get(InternalShare, share_id) is not None, (
+ "Recipient revoked an internal share owned by someone else"
+ )
+ _cleanup_ids([owner, recipient], [rec])
+
+
+def test_revoke_internal_share_owner_succeeds():
+ """The grantor/owner of the share can revoke it (200) and it is deleted."""
+ with _db():
+ owner = _setup_user("revo_owner")
+ recipient = _setup_user("revo_recipient")
+ rec = _make_recording(owner)
+ share_id = _make_internal_share(rec, owner, recipient)
+
+ with _internal_enabled():
+ resp = _client_for(owner).delete(f"/api/internal-shares/{share_id}")
+ assert resp.status_code == 200, resp.data
+ assert resp.get_json()["success"] is True
+ with _db():
+ assert db.session.get(InternalShare, share_id) is None
+ _cleanup_ids([owner, recipient], [rec])
+
+
+def test_revoke_internal_share_requires_login():
+ with _db():
+ owner = _setup_user("revl_owner")
+ recipient = _setup_user("revl_recipient")
+ rec = _make_recording(owner)
+ share_id = _make_internal_share(rec, owner, recipient)
+
+ with _internal_enabled():
+ resp = _anon_client().delete(f"/api/internal-shares/{share_id}")
+ assert resp.status_code in (302, 401), resp.status_code
+ with _db():
+ assert db.session.get(InternalShare, share_id) is not None
+ _cleanup_ids([owner, recipient], [rec])
+
+
+# --- module teardown: sweep any stragglers ---------------------------------
+
+def teardown_module(module):
+ with app.app_context():
+ prefixes = (
+ "pv_", "cs_", "audio_", "ges_", "ls_", "us_", "ds_", "srch_",
+ "csp_", "is_", "isb_", "isn_", "siv_", "swm", "rev",
+ )
+ users = User.query.filter(
+ db.or_(*[User.username.like(f"{p}%") for p in prefixes])
+ ).all()
+ for u in users:
+ for rec in Recording.query.filter_by(user_id=u.id).all():
+ Share.query.filter_by(recording_id=rec.id).delete()
+ InternalShare.query.filter_by(recording_id=rec.id).delete()
+ SharedRecordingState.query.filter_by(recording_id=rec.id).delete()
+ db.session.delete(rec)
+ db.session.delete(u)
+ db.session.commit()
+
+
+if __name__ == "__main__":
+ # Standalone run: create the schema (pytest's conftest session fixture does
+ # this automatically) before invoking pytest on this file.
+ from src.init_db import initialize_database
+ with app.app_context():
+ initialize_database(app)
+ import pytest as _pytest
+ raise SystemExit(_pytest.main([__file__, "-q", "-p", "no:cacheprovider"]))
diff --git a/tests/test_sso.py b/tests/test_sso.py
new file mode 100644
index 00000000..94cb9c5d
--- /dev/null
+++ b/tests/test_sso.py
@@ -0,0 +1,424 @@
+#!/usr/bin/env python3
+"""Tests for src/auth/sso.py — SSO/OIDC sign-in and auto-provisioning.
+
+This module has zero prior coverage and is high-risk: a bug here can mean
+account takeover (linking an SSO identity to the wrong local user) or
+unauthorized auto-provisioning (creating accounts for disallowed domains).
+
+Functions covered:
+ - _str_to_bool
+ - get_sso_config / is_sso_enabled (env-driven, read live per call)
+ - is_domain_allowed
+ - _sanitize_username
+ - generate_unique_username (DB-backed: collision suffixing)
+ - create_or_update_sso_user (DB-backed: create / link / dedup / authz)
+
+Run (pytest, isolated temp DB from conftest.py):
+ HOME=/tmp /tmp/speakr_testvenv/bin/python -m pytest tests/test_sso.py -q
+"""
+
+import os
+import sys
+import uuid
+import contextlib
+
+import pytest
+
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+
+from src.app import app, db # noqa: E402
+from src.models import User # noqa: E402
+from src.auth import sso # noqa: E402
+
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+# Env vars get_sso_config() reads. We snapshot/restore these around each test
+# so the suite stays isolated and tests can set them freely.
+_SSO_ENV_KEYS = [
+ "ENABLE_SSO", "SSO_PROVIDER_NAME", "SSO_CLIENT_ID", "SSO_CLIENT_SECRET",
+ "SSO_DISCOVERY_URL", "SSO_REDIRECT_URI", "SSO_AUTO_REGISTER",
+ "SSO_ALLOWED_DOMAINS", "SSO_DEFAULT_USERNAME_CLAIM",
+ "SSO_DEFAULT_NAME_CLAIM", "SSO_DISABLE_PASSWORD_LOGIN",
+]
+
+
+def env(**overrides):
+ """Temporarily set/unset SSO env vars; restore exactly on exit.
+
+ Pass a value to set it; pass None to ensure the var is unset.
+ """
+ saved = {k: os.environ.get(k) for k in _SSO_ENV_KEYS}
+ try:
+ for k, v in overrides.items():
+ if v is None:
+ os.environ.pop(k, None)
+ else:
+ os.environ[k] = v
+ yield
+ finally:
+ for k, old in saved.items():
+ if old is None:
+ os.environ.pop(k, None)
+ else:
+ os.environ[k] = old
+
+
+def app_ctx():
+ with app.app_context():
+ yield
+
+
+def cleanup_users(app_ctx):
+ """Track usernames/emails/subjects created in a test and delete them after."""
+ created = {"usernames": set(), "emails": set(), "subjects": set()}
+ yield created
+ q = User.query.filter(
+ db.or_(
+ User.username.in_(created["usernames"] or [""]),
+ User.email.in_(created["emails"] or [""]),
+ User.sso_subject.in_(created["subjects"] or [""]),
+ )
+ )
+ for u in q.all():
+ db.session.delete(u)
+ db.session.commit()
+
+
+def _mk_user(cleanup, username=None, email=None, sso_subject=None, password="x"):
+ username = username or ("u_" + uuid.uuid4().hex[:14])
+ email = email or (uuid.uuid4().hex[:10] + "@example.com")
+ u = User(username=username, email=email, password=password, sso_subject=sso_subject)
+ db.session.add(u)
+ db.session.commit()
+ cleanup["usernames"].add(username)
+ cleanup["emails"].add(email)
+ if sso_subject:
+ cleanup["subjects"].add(sso_subject)
+ return u
+
+
+# ---------------------------------------------------------------------------
+# _str_to_bool
+# ---------------------------------------------------------------------------
+
[email protected]("value,expected", [
+ ("true", True), ("True", True), ("TRUE", True),
+ ("false", False), ("0", False), ("1", False), ("yes", False),
+ ("", False), (None, False),
+])
+def test_str_to_bool(value, expected):
+ assert sso._str_to_bool(value) is expected
+
+
+# ---------------------------------------------------------------------------
+# get_sso_config / is_sso_enabled — read env live per call
+# ---------------------------------------------------------------------------
+
+def test_get_sso_config_reads_env_live_per_call():
+ with env(SSO_PROVIDER_NAME="Okta", ENABLE_SSO="true"):
+ cfg1 = sso.get_sso_config()
+ assert cfg1["provider_name"] == "Okta"
+ assert cfg1["enabled"] is True
+ # mutate env after first read; a fresh call must reflect it (no caching)
+ os.environ["SSO_PROVIDER_NAME"] = "Keycloak"
+ os.environ["ENABLE_SSO"] = "false"
+ cfg2 = sso.get_sso_config()
+ assert cfg2["provider_name"] == "Keycloak"
+ assert cfg2["enabled"] is False
+
+
+def test_get_sso_config_defaults():
+ with env(SSO_PROVIDER_NAME=None, SSO_DEFAULT_USERNAME_CLAIM=None,
+ SSO_DEFAULT_NAME_CLAIM=None, ENABLE_SSO=None, SSO_AUTO_REGISTER=None):
+ cfg = sso.get_sso_config()
+ assert cfg["provider_name"] == "SSO"
+ assert cfg["username_claim"] == "preferred_username"
+ assert cfg["name_claim"] == "name"
+ assert cfg["enabled"] is False
+ # SSO_AUTO_REGISTER defaults to "true"
+ assert cfg["auto_register"] is True
+
+
+def test_is_sso_enabled_requires_all_fields():
+ full = dict(
+ ENABLE_SSO="true", SSO_CLIENT_ID="cid", SSO_CLIENT_SECRET="secret",
+ SSO_DISCOVERY_URL="https://idp/.well-known/openid-configuration",
+ SSO_REDIRECT_URI="https://app/callback",
+ )
+ with env(**full):
+ assert sso.is_sso_enabled() is True
+
+ # Disabled flag → False even when everything else present
+ with env(**{**full, "ENABLE_SSO": "false"}):
+ assert sso.is_sso_enabled() is False
+
+ # Missing client secret → False
+ with env(**{**full, "SSO_CLIENT_SECRET": None}):
+ assert sso.is_sso_enabled() is False
+
+ # Missing discovery url → False
+ with env(**{**full, "SSO_DISCOVERY_URL": None}):
+ assert sso.is_sso_enabled() is False
+
+
+# ---------------------------------------------------------------------------
+# is_domain_allowed
+# ---------------------------------------------------------------------------
+
+def test_is_domain_allowed_none_and_malformed_email():
+ with env(SSO_ALLOWED_DOMAINS="example.com"):
+ assert sso.is_domain_allowed(None) is False
+ assert sso.is_domain_allowed("") is False
+ # no "@" → not allowed
+ assert sso.is_domain_allowed("not-an-email") is False
+
+
+def test_is_domain_allowed_empty_allowlist_allows_all():
+ # Unset → no restriction
+ with env(SSO_ALLOWED_DOMAINS=None):
+ assert sso.is_domain_allowed("[email protected]") is True
+ # Empty string → no restriction
+ with env(SSO_ALLOWED_DOMAINS=""):
+ assert sso.is_domain_allowed("[email protected]") is True
+ # Whitespace/commas only → parses to empty allowed list → allow all
+ with env(SSO_ALLOWED_DOMAINS=" , , "):
+ assert sso.is_domain_allowed("[email protected]") is True
+
+
+def test_is_domain_allowed_matches_listed_domain_case_insensitively():
+ with env(SSO_ALLOWED_DOMAINS="Example.com, Corp.io"):
+ assert sso.is_domain_allowed("[email protected]") is True
+ assert sso.is_domain_allowed("[email protected]") is True
+ assert sso.is_domain_allowed("[email protected]") is True
+
+
+def test_is_domain_allowed_rejects_unlisted_domain():
+ with env(SSO_ALLOWED_DOMAINS="example.com"):
+ assert sso.is_domain_allowed("[email protected]") is False
+ # the listed domain appearing only in the local part must NOT pass
+ assert sso.is_domain_allowed("[email protected]") is False
+
+
+def test_is_domain_allowed_subdomain_is_not_implied():
+ # The code does an exact membership test on the full domain after the last
+ # "@", so a subdomain of an allowed domain is NOT automatically allowed.
+ with env(SSO_ALLOWED_DOMAINS="example.com"):
+ assert sso.is_domain_allowed("[email protected]") is False
+ # But listing the subdomain explicitly works.
+ with env(SSO_ALLOWED_DOMAINS="eng.example.com"):
+ assert sso.is_domain_allowed("[email protected]") is True
+
+
+def test_is_domain_allowed_uses_last_at_for_domain():
+ # rsplit("@", 1) → an address with two "@" is rejected (len(parts)!=2 only
+ # when there's no "@"; with two "@", rsplit limits to 1 split so the domain
+ # is what's after the LAST "@"). Verify that real behavior.
+ with env(SSO_ALLOWED_DOMAINS="example.com"):
+ # "a@[email protected]" → domain "example.com" → allowed
+ assert sso.is_domain_allowed("a@[email protected]") is True
+ # "a@[email protected]" → domain "evil.com" → rejected
+ assert sso.is_domain_allowed("a@[email protected]") is False
+
+
+# ---------------------------------------------------------------------------
+# _sanitize_username
+# ---------------------------------------------------------------------------
+
+def test_sanitize_username_keeps_allowed_chars():
+ assert sso._sanitize_username("john.doe_1-2") == "john.doe_1-2"
+
+
+def test_sanitize_username_strips_disallowed_chars():
+ assert sso._sanitize_username("[email protected]") == "johndoe.com"
+ assert sso._sanitize_username("a b c!#$%") == "abc"
+ # unicode / spaces stripped
+ assert sso._sanitize_username("Renée Müller") == "ReneMller"
+
+
+def test_sanitize_username_empty_falls_back_to_user():
+ assert sso._sanitize_username("") == "user"
+ assert sso._sanitize_username(None) == "user"
+ # all-disallowed → stripped to empty → "user"
+ assert sso._sanitize_username("!!!@@@###") == "user"
+
+
+# ---------------------------------------------------------------------------
+# generate_unique_username (DB-backed)
+# ---------------------------------------------------------------------------
+
+def test_generate_unique_username_no_collision_returns_sanitized_base(cleanup_users):
+ base = "uniq" + uuid.uuid4().hex[:8]
+ got = sso.generate_unique_username(base + "@x.com")
+ assert got == (base + "x.com")[:20]
+
+
+def test_generate_unique_username_none_falls_back_to_user(cleanup_users):
+ # If "user" itself is free this returns "user"; if taken it suffixes. Either
+ # way it must start with the sanitized "user" base.
+ got = sso.generate_unique_username(None)
+ assert got == "user" or got.startswith("user")
+
+
+def test_generate_unique_username_appends_suffix_on_collision(cleanup_users):
+ base = "coll" + uuid.uuid4().hex[:6] # < 18 chars, no truncation games
+ # Occupy the base username.
+ _mk_user(cleanup_users, username=base)
+ got = sso.generate_unique_username(base)
+ assert got != base
+ assert got == f"{base}01"
+ # Register so the next call must skip to 02.
+ _mk_user(cleanup_users, username=got)
+ got2 = sso.generate_unique_username(base)
+ assert got2 == f"{base}02"
+
+
+def test_generate_unique_username_result_is_actually_unique(cleanup_users):
+ base = "x" + uuid.uuid4().hex[:6]
+ _mk_user(cleanup_users, username=base)
+ got = sso.generate_unique_username(base)
+ # Must not collide with an existing row.
+ assert User.query.filter_by(username=got).first() is None
+
+
+# ---------------------------------------------------------------------------
+# create_or_update_sso_user (DB-backed) — the high-risk surface
+# ---------------------------------------------------------------------------
+
+def _track(cleanup, user):
+ cleanup["usernames"].add(user.username)
+ cleanup["emails"].add(user.email)
+ if user.sso_subject:
+ cleanup["subjects"].add(user.sso_subject)
+
+
+def test_create_requires_sub(cleanup_users):
+ with env(SSO_ALLOWED_DOMAINS=None):
+ with pytest.raises(ValueError):
+ sso.create_or_update_sso_user({"email": "[email protected]"})
+
+
+def test_create_new_user_from_claims(cleanup_users):
+ sub = "sub-" + uuid.uuid4().hex
+ email = "new" + uuid.uuid4().hex[:8] + "@example.com"
+ preferred = "pref" + uuid.uuid4().hex[:6]
+ with env(SSO_ALLOWED_DOMAINS=None, SSO_PROVIDER_NAME="Keycloak",
+ SSO_DEFAULT_USERNAME_CLAIM="preferred_username",
+ SSO_DEFAULT_NAME_CLAIM="name", SSO_AUTO_REGISTER="true"):
+ user = sso.create_or_update_sso_user({
+ "sub": sub, "email": email,
+ "preferred_username": preferred, "name": "Alice Example",
+ })
+ _track(cleanup_users, user)
+ assert user.id is not None
+ assert user.sso_subject == sub
+ assert user.sso_provider == "Keycloak"
+ assert user.email == email
+ assert user.name == "Alice Example"
+ assert user.username == preferred[:20]
+ # SSO users have no local password.
+ assert user.password is None
+
+
+def test_second_call_same_subject_updates_not_duplicates(cleanup_users):
+ sub = "sub-" + uuid.uuid4().hex
+ email = "dup" + uuid.uuid4().hex[:8] + "@example.com"
+ with env(SSO_ALLOWED_DOMAINS=None, SSO_DEFAULT_NAME_CLAIM="name"):
+ u1 = sso.create_or_update_sso_user({"sub": sub, "email": email, "name": "First"})
+ _track(cleanup_users, u1)
+ first_id = u1.id
+ # Second call, same subject, changed name → updates the same row.
+ u2 = sso.create_or_update_sso_user({"sub": sub, "email": email, "name": "Second"})
+ _track(cleanup_users, u2)
+ assert u2.id == first_id
+ assert u2.name == "Second"
+ assert User.query.filter_by(sso_subject=sub).count() == 1
+
+
+def test_existing_email_user_gets_sso_linked(cleanup_users):
+ # A pre-existing password user with this email should be LINKED to the SSO
+ # identity rather than having a duplicate account created.
+ email = "link" + uuid.uuid4().hex[:8] + "@example.com"
+ existing = _mk_user(cleanup_users, email=email, password="hashed")
+ existing_id = existing.id
+ sub = "sub-" + uuid.uuid4().hex
+ cleanup_users["subjects"].add(sub)
+ with env(SSO_ALLOWED_DOMAINS=None, SSO_PROVIDER_NAME="Keycloak"):
+ linked = sso.create_or_update_sso_user({"sub": sub, "email": email, "name": "Linked"})
+ assert linked.id == existing_id
+ assert linked.sso_subject == sub
+ assert linked.sso_provider == "Keycloak"
+ assert User.query.filter_by(email=email).count() == 1
+
+
+def test_disallowed_domain_is_rejected(cleanup_users):
+ sub = "sub-" + uuid.uuid4().hex
+ with env(SSO_ALLOWED_DOMAINS="example.com", SSO_AUTO_REGISTER="true"):
+ with pytest.raises(PermissionError):
+ sso.create_or_update_sso_user({
+ "sub": sub, "email": "[email protected]", "name": "Mallory",
+ })
+ # No account should have been provisioned.
+ assert User.query.filter_by(sso_subject=sub).first() is None
+
+
+def test_auto_register_disabled_blocks_new_users(cleanup_users):
+ sub = "sub-" + uuid.uuid4().hex
+ with env(SSO_ALLOWED_DOMAINS=None, SSO_AUTO_REGISTER="false"):
+ with pytest.raises(PermissionError):
+ sso.create_or_update_sso_user({
+ "sub": sub, "email": "[email protected]", "name": "Newbie",
+ })
+ assert User.query.filter_by(sso_subject=sub).first() is None
+
+
+def test_auto_register_disabled_still_allows_known_subject(cleanup_users):
+ # Existing SSO user (known subject) must still be able to log in even when
+ # auto-registration is turned off.
+ sub = "sub-" + uuid.uuid4().hex
+ email = "known" + uuid.uuid4().hex[:8] + "@example.com"
+ existing = _mk_user(cleanup_users, email=email, sso_subject=sub, password=None)
+ with env(SSO_ALLOWED_DOMAINS=None, SSO_AUTO_REGISTER="false", SSO_DEFAULT_NAME_CLAIM="name"):
+ user = sso.create_or_update_sso_user({"sub": sub, "email": email, "name": "Known"})
+ assert user.id == existing.id
+ assert user.name == "Known"
+
+
+def test_username_claim_is_respected(cleanup_users):
+ sub = "sub-" + uuid.uuid4().hex
+ upn = "upn" + uuid.uuid4().hex[:6]
+ with env(SSO_ALLOWED_DOMAINS=None, SSO_DEFAULT_USERNAME_CLAIM="upn"):
+ user = sso.create_or_update_sso_user({
+ "sub": sub, "email": "[email protected]",
+ "upn": upn, "preferred_username": "should-not-be-used",
+ })
+ _track(cleanup_users, user)
+ assert user.username == upn[:20]
+
+
+def test_username_falls_back_to_email_localpart(cleanup_users):
+ sub = "sub-" + uuid.uuid4().hex
+ local = "local" + uuid.uuid4().hex[:6]
+ with env(SSO_ALLOWED_DOMAINS=None):
+ # No username claim provided → use email local part.
+ user = sso.create_or_update_sso_user({"sub": sub, "email": f"{local}@example.com"})
+ _track(cleanup_users, user)
+ assert user.username == local[:20]
+
+
+def test_no_email_uses_placeholder(cleanup_users):
+ sub = "sub-" + uuid.uuid4().hex
+ with env(SSO_ALLOWED_DOMAINS="example.com"):
+ # No email claim at all → domain check is skipped, placeholder email set.
+ user = sso.create_or_update_sso_user({"sub": sub, "preferred_username": "noemail" + sub[:6]})
+ _track(cleanup_users, user)
+ assert user.email == f"{sub}@placeholder.local"
+
+
+if __name__ == "__main__":
+ sys.exit(pytest.main([__file__, "-q"]))