File size: 12,430 Bytes
fe40b87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
"""N01 to N05, the export worker and C07 consent enforcement."""

import httpx
import pytest
from sqlalchemy import select

from app.core.config import get_settings
from app.core.database import get_session_factory
from app.integrations.storage import get_storage
from app.jobs.exports import run_exports
from app.modules.settings.models import ConsentEvent, ExportJob
from tests.factories import create_session, make_account, session_body, upload
from tests.helpers import register


async def _events(account_id, category=None) -> list[tuple[str, str]]:
    async with get_session_factory()() as db:
        query = select(ConsentEvent.category, ConsentEvent.action).where(ConsentEvent.account_id == account_id)
        if category:
            query = query.where(ConsentEvent.category == category)
        return [tuple(r) for r in (await db.execute(query.order_by(ConsentEvent.created_at))).all()]


async def test_get_defaults_without_creating_a_row(client):
    me = await register(client)
    response = await client.get("/v1/me/settings", headers=me["headers"])
    assert response.status_code == 200
    s = response.json()["settings"]
    assert s["coach_can_see_sessions"] is True and s["share_with_parent"] is False
    assert s["consented_at"] is None and s["consent_version"] is None and s["version"] == 1
    assert s["parent_email"] is None and s["notify_weekly"] is True


async def test_settings_require_auth(client):
    assert (await client.get("/v1/me/settings")).status_code == 401
    assert (await client.patch("/v1/me/settings", json={"private_links": True})).status_code == 401


async def test_patch_updates_and_bumps_version(client):
    me = await register(client)
    h = me["headers"]
    response = await client.patch("/v1/me/settings", json={"private_links": True, "expected_version": 1}, headers=h)
    assert response.status_code == 200
    s = response.json()["settings"]
    assert s["private_links"] is True and s["version"] == 2
    again = (await client.get("/v1/me/settings", headers=h)).json()["settings"]
    assert again == s


async def test_patch_stale_version(client):
    me = await register(client)
    h = me["headers"]
    await client.patch("/v1/me/settings", json={"notify_drills": False}, headers=h)
    response = await client.patch("/v1/me/settings", json={"notify_drills": True, "expected_version": 1}, headers=h)
    assert response.status_code == 409 and response.json()["error"]["code"] == "STALE_VERSION"


async def test_patch_validation(client):
    h = (await register(client))["headers"]
    assert (await client.patch("/v1/me/settings", json={}, headers=h)).status_code == 400
    assert (await client.patch("/v1/me/settings", json={"private_links": "yes"}, headers=h)).status_code == 400
    assert (await client.patch("/v1/me/settings", json={"private_links": None}, headers=h)).status_code == 400
    assert (await client.patch("/v1/me/settings", json={"version": 3}, headers=h)).status_code == 400
    assert (await client.patch("/v1/me/settings", json={"parent_email": "nope"}, headers=h)).status_code == 400


async def test_auto_report_needs_sharing_and_email(client):
    h = (await register(client))["headers"]
    response = await client.patch("/v1/me/settings", json={"auto_monthly_report": True}, headers=h)
    assert response.status_code == 422
    response = await client.patch(
        "/v1/me/settings", json={"share_with_parent": True, "auto_monthly_report": True}, headers=h)
    assert response.status_code == 422
    response = await client.patch(
        "/v1/me/settings", json={"share_with_parent": True, "parent_email": "Mum@Example.com",
                                 "auto_monthly_report": True}, headers=h)
    assert response.status_code == 200
    s = response.json()["settings"]
    assert s["parent_email"] == "mum@example.com" and s["auto_monthly_report"] is True

    off = await client.patch("/v1/me/settings", json={"share_with_parent": False}, headers=h)
    assert off.json()["settings"]["auto_monthly_report"] is False


async def test_opt_ins_are_recorded_as_consent_events(client):
    me = await register(client)
    h = me["headers"]
    await client.patch("/v1/me/settings", json={"help_improve_ai": True, "clips_as_examples": True}, headers=h)
    await client.patch("/v1/me/settings", json={"help_improve_ai": True}, headers=h)  # unchanged: no event
    await client.patch("/v1/me/settings", json={"help_improve_ai": False}, headers=h)
    account_id = me["user"]["id"]
    assert await _events(account_id, "help_improve_ai") == [("help_improve_ai", "accepted"),
                                                           ("help_improve_ai", "withdrawn")]
    assert await _events(account_id, "clips_as_examples") == [("clips_as_examples", "accepted")]
    # the opt-ins never count as analysis consent
    assert (await client.get("/v1/me/settings", headers=h)).json()["settings"]["consented_at"] is None


async def test_consent_accept_and_withdraw(client):
    me = await register(client)
    h = me["headers"]
    response = await client.post("/v1/me/consent", json={"version": "1.0", "accepted": True}, headers=h)
    assert response.status_code == 201
    consent = response.json()["consent"]
    assert consent["version"] == "1.0" and consent["withdrawn_at"] is None
    s = (await client.get("/v1/me/settings", headers=h)).json()["settings"]
    assert s["consent_version"] == "1.0" and s["consented_at"] == consent["accepted_at"]

    assert (await client.delete("/v1/me/consent", headers=h)).status_code == 204
    assert (await client.delete("/v1/me/consent", headers=h)).status_code == 204  # repeat is a no-op
    s = (await client.get("/v1/me/settings", headers=h)).json()["settings"]
    assert s["consented_at"] is None and s["consent_version"] is None
    assert [a for _, a in await _events(me["user"]["id"], "analysis")] == ["accepted", "withdrawn"]


async def test_consent_withdraw_without_acceptance_is_noop(client):
    me = await register(client)
    assert (await client.delete("/v1/me/consent", headers=me["headers"])).status_code == 204
    assert await _events(me["user"]["id"]) == []


async def test_consent_errors(client):
    h = (await register(client))["headers"]
    stale = await client.post("/v1/me/consent", json={"version": "0.1", "accepted": True}, headers=h)
    assert stale.status_code == 409 and stale.json()["error"]["code"] == "TERMS_CHANGED"
    for body in ({"version": "1.0", "accepted": False}, {"version": "1.0"}, {"accepted": True}):
        assert (await client.post("/v1/me/consent", json=body, headers=h)).status_code == 400
    assert (await client.post("/v1/me/consent", json={"version": "1.0", "accepted": True})).status_code == 401
    assert (await client.delete("/v1/me/consent")).status_code == 401


async def test_consent_idempotent(client):
    me = await register(client)
    h = {**me["headers"], "Idempotency-Key": "k1"}
    body = {"version": "1.0", "accepted": True}
    first = await client.post("/v1/me/consent", json=body, headers=h)
    second = await client.post("/v1/me/consent", json=body, headers=h)
    assert first.status_code == second.status_code == 201 and first.json() == second.json()
    assert len(await _events(me["user"]["id"], "analysis")) == 1
    other = await client.post("/v1/me/consent", json={"version": "1.0", "accepted": True}, headers=me["headers"])
    assert other.json() == first.json()  # already accepted: no second event
    assert len(await _events(me["user"]["id"], "analysis")) == 1


# ---------- exports ----------

class FakeEmail:
    def __init__(self, fail: bool = False):
        self.sent: list[tuple[str, str, str]] = []
        self.fail = fail

    async def send(self, to: str, subject: str, text: str) -> None:
        if self.fail:
            raise RuntimeError("down")
        self.sent.append((to, subject, text))


async def _run_exports(email: FakeEmail) -> dict:
    async with get_session_factory()() as db:
        return await run_exports(db, get_storage(), email)


async def test_export_request_and_worker(client):
    me = await register(client)
    h = me["headers"]
    session = await create_session(client, h)
    gone = await create_session(client, h)
    await client.delete(f"/v1/sessions/{gone['id']}", headers=h)

    response = await client.post("/v1/me/exports", json={"scope": "videos"}, headers=h)
    assert response.status_code == 202
    export = response.json()["export"]
    assert export["status"] == "queued" and export["delivery"] == "account_email"

    dup = await client.post("/v1/me/exports", json={"scope": "videos"}, headers=h)
    assert dup.status_code == 409 and dup.json()["error"]["code"] == "EXPORT_IN_PROGRESS"

    email = FakeEmail()
    assert await _run_exports(email) == {"ready": 1, "failed": 0}
    (to, _, text), = email.sent
    assert to.endswith("@example.com") and text.count("http") == 1 and session["id"]
    async with get_session_factory()() as db:
        job = await db.get(ExportJob, __import__("uuid").UUID(export["id"]))
        assert job.status == "ready" and job.expires_at is not None
    assert await _run_exports(email) == {"ready": 0, "failed": 0}

    again = await client.post("/v1/me/exports", json={"scope": "videos"}, headers=h)
    assert again.status_code == 202


async def test_export_worker_marks_failed(client):
    h = (await register(client))["headers"]
    await client.post("/v1/me/exports", json={"scope": "videos"}, headers=h)
    assert await _run_exports(FakeEmail(fail=True)) == {"ready": 0, "failed": 1}
    async with get_session_factory()() as db:
        job = (await db.scalars(select(ExportJob))).one()
        assert job.status == "failed" and job.error_code == "DELIVERY_FAILED"


async def test_export_validation_auth_and_idempotency(client):
    me = await register(client)
    h = me["headers"]
    assert (await client.post("/v1/me/exports", json={"scope": "consent"}, headers=h)).status_code == 400
    assert (await client.post("/v1/me/exports", json={}, headers=h)).status_code == 400
    assert (await client.post("/v1/me/exports", json={"scope": "videos"})).status_code == 401
    keyed = {**h, "Idempotency-Key": "e1"}
    first = await client.post("/v1/me/exports", json={"scope": "videos"}, headers=keyed)
    second = await client.post("/v1/me/exports", json={"scope": "videos"}, headers=keyed)
    assert first.status_code == second.status_code == 202 and first.json() == second.json()


# ---------- C07 ----------

async def _post_session(client, headers) -> httpx.Response:
    video = await upload(client, headers, "video")
    thumb = await upload(client, headers, "thumbnail")
    return await client.post("/v1/sessions", json=session_body(video, thumb), headers=headers)


async def test_withdrawn_consent_blocks_new_analysis(client):
    me = await register(client)
    h = me["headers"]
    assert (await _post_session(client, h)).status_code == 201  # no event, consent not required
    await client.post("/v1/me/consent", json={"version": "1.0", "accepted": True}, headers=h)
    assert (await _post_session(client, h)).status_code == 201
    await client.delete("/v1/me/consent", headers=h)
    blocked = await _post_session(client, h)
    assert blocked.status_code == 403 and blocked.json()["error"]["code"] == "CONSENT_REQUIRED"
    # saved sessions stay readable
    assert (await client.get("/v1/sessions", headers=h)).status_code == 200
    await client.post("/v1/me/consent", json={"version": "1.0", "accepted": True}, headers=h)
    assert (await _post_session(client, h)).status_code == 201


async def test_required_consent_blocks_without_acceptance(client, monkeypatch):
    monkeypatch.setenv("REQUIRE_ANALYSIS_CONSENT", "true")
    get_settings.cache_clear()
    try:
        h = (await register(client))["headers"]
        blocked = await _post_session(client, h)
        assert blocked.status_code == 403 and blocked.json()["error"]["code"] == "CONSENT_REQUIRED"
        await client.post("/v1/me/consent", json={"version": "1.0", "accepted": True}, headers=h)
        assert (await _post_session(client, h)).status_code == 201
    finally:
        monkeypatch.undo()
        get_settings.cache_clear()


@pytest.mark.parametrize("role", ["player", "coach"])
async def test_settings_for_both_roles(client, role):
    account = await make_account(role)
    assert (await client.get("/v1/me/settings", headers=account["headers"])).status_code == 200